tempest.games 0.1.2 → 0.1.3
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/bin/frontend.bun.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var My=Object.defineProperty;var Fy=(o,n)=>{for(var t in n)My(o,t,{get:n[t],enumerable:!0,configurable:!0,set:(S)=>n[t]=()=>S})};import{join as U0,normalize as V0,resolve as RJ}from"path";function zt(o=Math.random){return o().toString(36).slice(2)}class tS extends Promise{fate;resolve;reject;done=!1;constructor(o){let n,t;super((S,f)=>{n=S,t=f});this.resolve=n,this.reject=t,this.use(o instanceof Promise?o:new Promise(o))}pass(o,n){if(o===this.fate)this.resolve(n),this.done=!0}fail(o,n){if(o===this.fate)this.reject(n),this.done=!0}use(o){if(o instanceof Promise){const n=o;this.fate=n,n.then((t)=>{this.pass(n,t)},(t)=>{this.fail(n,t)})}else this.resolve(o),this.fate=void 0}}function PM(o){return Object.entries(o)}var gM=(o,n,t=ko.STORE)=>{return En(t,{key:`${o.key}:JSON`,get:({get:S})=>n.toJson(S(o)),set:({set:S},f)=>{S(o,n.fromJson(f))}})};function m(o){while(o.child!==null)o=o.child;return o}function lM(o){while(o.parent!==null)o=o.parent;return o}class s{Subscriber;subscribers=new Map;subscribe(o,n){return this.subscribers.set(o,n),()=>{this.unsubscribe(o)}}unsubscribe(o){this.subscribers.delete(o)}next(o){const n=this.subscribers.values();for(let t of n)t(o)}}class af extends s{state;constructor(o){super();this.state=o}next(o){this.state=o,super.next(o)}}function jn(o,n,t){const S={key:n.key,type:"atom_family"},f=o.families.get(n.key);if(f)o.logger.error("\u2757","atom_family",n.key,`Overwriting an existing ${Gn(f)} "${f.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const T=new s,F=Object.assign((k)=>{const A=l(k),$={key:n.key,subKey:A},O=`${n.key}(${A})`,w=m(o),G=n.default,r={key:O,default:G instanceof Function?G(k):G};if(n.effects)r.effects=n.effects(k);const H=nn(w,r,$);return T.next({type:"state_creation",token:H}),H},S,{subject:T,install:(k)=>jn(k,n),internalRoles:t});return o.families.set(n.key,F),o.defaults.set(n.key,n.default),S}function eM(o,n){if("mutable"in n)return SS(o,n);return jn(o,n)}function hn(o,n,t){const S={key:n.key,type:"readonly_selector_family"},f=o.families.get(n.key);if(f)o.logger.error("\u2757","readonly_selector_family",n.key,`Overwriting an existing ${Gn(f)} "${f.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const T=new s,F=Object.assign((k)=>{const A=l(k),$={key:n.key,subKey:A},O=`${n.key}(${A})`,w=m(o),G=fS(w,{key:O,get:n.get(k)},$);return T.next({type:"state_creation",token:G}),G},S,{internalRoles:t,subject:T,install:(k)=>hn(k,n),default:(k)=>{return n.get(k)({get:(...$)=>Go(o,...$),find:($,O)=>Ro(o,$,O),seek:($,O)=>Eo(o,$,O),json:($)=>ho(o,$)})}});return o.families.set(n.key,F),S}function TS(o,n){if("set"in n)return MS(o,n);return hn(o,n)}function Ht(o,n){const t=l(n),S=`${o.key}(${t})`,f=ky[o.type],T={key:S,type:f};if(f==="molecule")Object.assign(T,{key:n,family:o});else Object.assign(T,{family:{key:o.key,subKey:t}});return Object.assign(T,{counterfeit:!0}),T}var ky={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function Po(o){const n={key:o.key,type:o.type};if("family"in o)n.family=o.family;return n}function mt(o){return dM(ko.STORE,o)}function kt(o){return eM(ko.STORE,o)}function sf(...o){if(o.length===2)return Go(ko.STORE,...o);return Go(ko.STORE,...o)}var oT=(o)=>(n,t,S,f,...T)=>{console[o](`${n} ${t} "${S}" ${f}`,...T)},Ay={error:oT("error"),info:oT("info"),warn:oT("warn")};class nT{o;n;t;constructor(o,n,t=Ay){this.logLevel=o;this.filter=n;this.logger=t}error=(...o)=>{if((this.filter?.(...o)??!0)&&this.logLevel!==null)this.logger.error(...o)};info=(...o)=>{if((this.filter?.(...o)??!0)&&this.logLevel==="info")this.logger.info(...o)};warn=(...o)=>{if((this.filter?.(...o)??!0)&&this.logLevel!=="error"&&this.logLevel!==null)this.logger.warn(...o)}}function ZS(o){return TS(ko.STORE,o)}function FS(o){return tT(o,ko.STORE)}class Fn{a;b;cardinality;relations=new Map;contents=new Map;isContent;makeContentKey=(o,n)=>`${o}:${n}`;warn;getRelatedKeys(o){return this.relations.get(o)}addRelation(o,n){let t=this.relations.get(o),S=this.relations.get(n);if(t)t.add(n);else t=new Set([n]),this.relations.set(o,t);if(S)S.add(o);else S=new Set([o]),this.relations.set(n,S)}deleteRelation(o,n){const t=this.relations.get(o);if(t){if(t.delete(n),t.size===0)this.relations.delete(o);const S=this.relations.get(n);if(S){if(S.delete(o),S.size===0)this.relations.delete(n)}}}replaceRelationsUnsafely(o,n){this.relations.set(o,new Set(n));for(let t of n){const S=new Set([o]);this.relations.set(t,S)}}replaceRelationsSafely(o,n){const t=this.relations.get(o);if(t)for(let S of t){const f=this.relations.get(S);if(f){if(f.size===1)this.relations.delete(S);else f.delete(o);this.contents.delete(this.makeContentKey(o,S))}}this.relations.set(o,new Set(n));for(let S of n){let f=this.relations.get(S);if(f)f.add(o);else f=new Set([o]),this.relations.set(S,f)}}getContentInternal(o){return this.contents.get(o)}setContent(o,n){this.contents.set(o,n)}deleteContent(o){this.contents.delete(o)}constructor(o,n){if(this.a=o.between[0],this.b=o.between[1],this.cardinality=o.cardinality,!n?.externalStore)this.relations=new Map(o.relations?.map(([t,S])=>[t,new Set(S)])),this.contents=new Map(o.contents);if(this.isContent=n?.isContent??null,n?.makeContentKey)this.makeContentKey=n.makeContentKey;if(n?.externalStore){const t=n.externalStore;if(this.has=(S,f)=>t.has(S,f),this.addRelation=(S,f)=>{t.addRelation(S,f)},this.deleteRelation=(S,f)=>{t.deleteRelation(S,f)},this.replaceRelationsSafely=(S,f)=>{t.replaceRelationsSafely(S,f)},this.replaceRelationsUnsafely=(S,f)=>{t.replaceRelationsUnsafely(S,f)},this.getRelatedKeys=(S)=>t.getRelatedKeys(S),t.getContent)this.getContentInternal=(S)=>{return t.getContent(S)},this.setContent=(S,f)=>{t.setContent(S,f)},this.deleteContent=(S)=>{t.deleteContent(S)};for(let[S,f]of o.relations??[])for(let T of f)this.addRelation(S,T);for(let[S,f]of o.contents??[])this.setContent(S,f)}if(n?.warn)this.warn=n.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([o,n])=>[o,[...n]]),contents:[...this.contents.entries()]}}set(o,...n){const t=typeof n[0]==="string"?n[0]:o[this.b],S=n[1]??typeof n[0]==="string"?void 0:n[0];switch(o=typeof o==="string"?o:o[this.a],this.cardinality){case"1:1":{const f=this.getRelatedKey(o);if(f&&f!==t)this.delete(f,o)}case"1:n":{const f=this.getRelatedKey(t);if(f&&f!==o)this.delete(f,t)}}if(S){const f=this.makeContentKey(o,t);this.setContent(f,S)}return this.addRelation(o,t),this}delete(o,n){n=typeof n==="string"?n:o[this.b];const t=typeof o==="string"?o:o[this.a];if(t===void 0&&typeof n==="string"){const S=this.getRelatedKeys(n);if(S)for(let f of S)this.delete(f,n)}if(typeof t==="string"&&n===void 0){const S=this.getRelatedKeys(t);if(S)for(let f of S)this.delete(t,f)}if(typeof t==="string"&&typeof n==="string"){this.deleteRelation(t,n);const S=this.makeContentKey(t,n);this.deleteContent(S)}return this}getRelatedKey(o){const n=this.getRelatedKeys(o);if(n){if(n.size>1)this.warn?.(`${n.size} related keys were found for key "${o}": (${[...n].map((t)=>`"${t}"`).join(", ")}). Only one related key was expected.`);for(let t of n)return t}}replaceRelations(o,n,t){const S=!Array.isArray(n),f=S?Object.keys(n):n;if(t?.reckless)this.replaceRelationsUnsafely(o,f);else this.replaceRelationsSafely(o,f);if(S)for(let T of f){const M=this.makeContentKey(o,T),F=n[T];this.setContent(M,F)}return this}getContent(o,n){const t=this.makeContentKey(o,n);return this.getContentInternal(t)}getRelationEntries(o){const n=o[this.a],t=o[this.b];if(n!==void 0&&t===void 0){const S=this.getRelatedKeys(n);if(S)return[...S].map((f)=>{return[f,this.getContent(n,f)??null]})}if(n===void 0&&t!==void 0){const S=this.getRelatedKeys(t);if(S)return[...S].map((f)=>{return[f,this.getContent(f,t)??null]})}return[]}has(o,n){if(n)return this.getRelatedKeys(o)?.has(n)??!1;return this.relations.has(o)}}function bo(o){return"epoch"in o.transactionMeta}function Fo(o){return"phase"in o.transactionMeta}var aM=(o)=>{const n=m(o);if(!Fo(n)){o.logger.warn("\uD83D\uDC1E","transaction","???","abortTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}o.logger.info("\uD83E\uDE82","transaction",n.transactionMeta.update.key,"Aborting transaction"),n.parent.child=null};function Gn(o){return o.type.split("_").map($y).join(" ")}var $y=(o)=>o[0].toUpperCase()+o.slice(1);class tn extends Error{constructor(...o){const n=o[0],t=o.length===2?o[1]:o[2];if(o.length===2)super(`${Gn(n)} ${l(n.key)} not found in store "${t.config.name}".`);else{const S=o[1];super(`${Gn(n)} "${n.key}" member ${l(S)} not found in store "${t.config.name}".`)}}}function At(o,n,t){return(...S)=>{const f=u(o,t);if(f)return f.run(S,n);throw new tn(o,t)}}var PS=(o)=>(n)=>o instanceof Function?o(n):o;var en=(o,n)=>{if(n.valueMap.has(o.key))return n.logger.info("\uD83D\uDCD6",o.type,o.key,"reading cached value"),sM(o,n);if(o.type==="selector"||o.type==="readonly_selector")return n.logger.info("\uD83E\uDDEE",o.type,o.key,"computing value"),o.get();const t=o.default instanceof Function?o.default():o.default;return n.logger.info("\uD83D\uDC81","atom",o.key,"could not find cached value; using default",t),o.default instanceof Function?o.default():o.default};var oF=(o,n)=>{if(o.operation.open){const t=performance.now();return o.logger.info("\u2757",n.type,n.key,`deferring setState at T-${t} until setState for "${o.operation.token.key}" is done`),t}o.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:n},o.logger.info("\u2B55",n.type,n.key,`operation start in store "${o.config.name}"${!Fo(o)?"":` ${o.transactionMeta.phase} "${o.transactionMeta.update.key}"`}`)},nF=(o)=>{if(o.operation.open)o.logger.info("\uD83D\uDD34",o.operation.token.type,o.operation.token.key,`operation done in store "${o.config.name}"`);o.operation={open:!1},o.on.operationClose.next(o.operation)},tF=(o,n)=>{if(!o.operation.open)return o.logger.error("\uD83D\uDC1E","unknown",n,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return o.operation.done.has(n)},Qt=(o,n)=>{if(!o.operation.open){o.logger.error("\uD83D\uDC1E","unknown",n,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}o.operation.done.add(n)};var SF=(o,n,t)=>{switch(o.type){case"mutable_atom":t.logger.info("\uD83D\uDCE2",o.type,o.key,"is now (",n.newValue,") subscribers:",o.subject.subscribers);break;default:t.logger.info("\uD83D\uDCE2",o.type,o.key,"went (",n.oldValue,"->",n.newValue,") subscribers:",o.subject.subscribers)}o.subject.next(n)};var ST=(o,n)=>{const t=m(n),S=t.selectorAtoms.getRelatedKeys(o.key);if(t.logger.info("\uD83E\uDDF9",o.type,o.key,S?`evicting ${S.size} states downstream:`:"no downstream states",S??"to evict"),S){if(t.operation.open)t.logger.info("\uD83E\uDDF9",o.type,o.key,`[ ${[...t.operation.done].join(", ")} ] already done`);for(let f of S){if(tF(t,f))continue;fF(f,t),Qt(t,f)}}};function Jy(o,n){if(MF(n.newValue))return!1;if(o.includes("\uD83D\uDD0D"))return!1;return!0}var TF=(o,n,t)=>{const{key:S}=o,f=m(t);if(!Fo(f)||f.transactionMeta.phase!=="building"){t.logger.error("\uD83D\uDC1E","atom",S,"stowUpdate called outside of a transaction. This is probably a bug.");return}if(!Jy(S,n))return;const M={type:"atom_update",key:S,...n};if(o.family)M.family=o.family;f.transactionMeta.update.updates.push(M),t.logger.info("\uD83D\uDCC1","atom",S,"stowed (",n.oldValue,"->",n.newValue,")")};var FF=(o,n,t)=>{const S=en(o,t);let f=S;if(o.type==="mutable_atom"&&Fo(t)){const{parent:M}=t;f=kS(o,M,t)}if(f=PS(n)(f),t.logger.info("\uD83D\uDCDD","atom",o.key,"set to",f),f=Rn(o.key,f,o.subject,t),kF(o.key,t))AF(o.key,t);Qt(t,o.key),ST(o,t);const T={oldValue:S,newValue:f};if(bo(t))SF(o,T,t);else if(t.parent){if(t.on.transactionApplying.state===null)TF(o,T,t);else if(o.key.startsWith("*")){const M=o.key.slice(1),F=t.atoms.get(M);let k=t.valueMap.get(M);if(F.type==="mutable_atom"&&Fo(t)){const{parent:$}=t;k=kS(F,$,t)}if(k.do(T.newValue)===null)ST(F,t)}}};var gS=(o,n,t)=>{switch(o.type){case"atom":case"mutable_atom":FF(o,n,t);break;case"selector":o.set(n);break}};function lS(o,n){if(n.family){const t=o.families.get(n.family.key);if(t)return t}}function Co(o,...n){let t,S,f,T;if(n.length===2){if(t=n[0],T=n[1],S=lS(o,t)??null,S)f=t.family?Uo(t.family.subKey):null,t=Ro(o,S,f)}else S=n[0],f=n[1],T=n[2],t=Ro(o,S,f);if("counterfeit"in t){const k=o.disposalTraces.buffer.find((A)=>A?.key===t.key);o.logger.error("\u274C",t.type,t.key,`could not be set because it was not found in the store "${o.config.name}".`,k?`This state was previously disposed:\n${k.trace}`:"No previous disposal trace was found.");return}const M=oF(o,t);if(M){const k=o.on.operationClose.subscribe(`waiting to set "${t.key}" at T-${M}`,()=>{k(),o.logger.info("\uD83D\uDFE2",t.type,t.key,`resuming deferred setState from T-${M}`),Co(o,t,T)});return}const F=u(t,o);gS(F,T,o),nF(o)}function eS(o,n,t){const{key:S,newValue:f,oldValue:T}=n,M=o==="newValue"?f:T,F={key:S,type:"atom"};if(n.family)Object.assign(F,{family:n.family});Co(t,F,M)}function fT(o,n,t){const S=l(t);try{const f=[];let T;if(n==="root")f.push(o.molecules.get('"root"')),T="all";else if(n[0][0]===$F){T="any";const $=l(n),O=o.molecules.get($);if(!O)throw new Error(`Molecule ${$} not found in store "${o.config.name}"`);f.push(O)}else if(t[0][0]===$F){T="all";for(let O of n){const w=l(O),G=o.molecules.get(w);if(!G)throw new Error(`Molecule ${w} not found in store "${o.config.name}"`);f.push(G)}}else{T="any";const O=l(n),w=o.molecules.get(O);if(!w)throw new Error(`Molecule ${O} not found in store "${o.config.name}"`);f.push(w)}const M=new Dt(f,t);M._dependsOn=T,o.molecules.set(S,M);for(let $ of f)$.below.set(M.stringKey,M);const F={type:"molecule_creation",subType:"modern",key:M.key,provenance:n},k=m(o);if(Fo(k)&&k.transactionMeta.phase==="building")k.transactionMeta.update.updates.push(F);else k.on.moleculeCreationStart.next(F)}catch(f){if(f instanceof Error)o.logger.error("\u274C","molecule",S,"allocation failed:",f.message)}return t}function AS(o,n){const t=l(n),S=o.molecules.get(t);if(!S)throw new Error(`Molecule ${t} not found in store "${o.config.name}"`);for(let A of S.joins.values())A.relations.delete(S.key),A.molecules.delete(S.stringKey);let f;if(S.above.size===1)f=S.above.values().next().value.key;else f=[...S.above.values()].map(({key:A})=>A);const T=[];for(let A of S.tokens.values()){const $=A.family;T.push([$.key,o.valueMap.get(A.key)])}for(let A of S.tokens.values())uo(o,A);for(let A of S.below.values())if(A.dependsOn==="all")AS(o,A.key);else if(A.above.delete(S.stringKey),A.above.size===0)AS(o,A.key);S.below.clear();const M={type:"molecule_disposal",subType:"modern",key:S.key,values:T,provenance:f},F=m(o);if(Fo(F)&&F.transactionMeta.phase==="building")F.transactionMeta.update.updates.push(M);else F.on.moleculeDisposal.next(M);F.molecules.delete(S.stringKey);for(let A of S.above.values())A.below.delete(S.stringKey)}var wW=Symbol("provenance"),$F="T$";function JF(o,n){const t=new s,S={type:"molecule_family",key:n.key,dependsOn:n.dependsOn??"all"},f={...S,subject:t,new:n.new};return o.moleculeFamilies.set(n.key,f),S}function zn(o,n,t){const S=xn(t,n,o.key);o.tokens.set(S.key,S);const f=Fo(t)&&t.transactionMeta.phase==="building",T=t.moleculeInProgress===o.key;if(!f&&!T)o.subject.next({type:"state_creation",token:S});return S}class Bo extends Set{mode="record";subject=new s;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(o,n=0){super(o);if(o instanceof Bo)this.parent=o,this.cacheUpdateNumber=o.cacheUpdateNumber;if(n)this.cacheLimit=n,this.cache=new Array(n),this.subscribe("auto cache",(t)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=t})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(o){const n=new Bo(o.members,o.cacheLimit);return n.cache=o.cache,n.cacheIdx=o.cacheIdx,n.cacheUpdateNumber=o.cacheUpdateNumber,n}add(o){const n=super.add(o);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${l(o)}`);return n}clear(){const o=this.mode==="record"?[...this]:null;if(super.clear(),o)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(o)}`)}delete(o){const n=super.delete(o);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${l(o)}`);return n}parent;child=null;transactionUpdates=null;transaction(o){this.mode="transaction",this.transactionUpdates=[],this.child=new Bo(this);const n=this.child._subscribe("transaction",(t)=>{this.transactionUpdates?.push(t)});try{if(o(this.child)){for(let S of this.transactionUpdates)this.doStep(S);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(t){throw console.error("Failed to apply transaction to SetRTX:",t),t}finally{n(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(o,n){return this.subject.subscribe(o,n)}subscribe(o,n){return this.subject.subscribe(o,(t)=>{n(`${this.cacheUpdateNumber}=${t}`)})}emit(o){this.subject.next(o)}doStep(o){const n=o.indexOf(":"),t=o.substring(0,n),S=o.substring(n+1);switch(t){case"add":this.add(JSON.parse(S));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(S));break;case"tx":for(let f of S.split(";"))this.doStep(f)}}getUpdateNumber(o){const n=o.indexOf("=");return Number(o.substring(0,n))}do(o){const n=o.indexOf("="),t=Number(o.substring(0,n)),S=t-this.cacheUpdateNumber;if(S>0){if(S===1){this.mode="playback";const T=o.substring(n+1);return this.doStep(T),this.mode="record",this.cacheUpdateNumber=t,null}return this.cacheUpdateNumber+1}if(Math.abs(S)<this.cacheLimit){const T=this.cacheIdx+S;if(this.cache[T]===o)return null;this.mode="playback";let F=!1;while(!F){this.cacheIdx%=this.cacheLimit;const A=this.cache[this.cacheIdx];if(this.cacheIdx--,!A)return"OUT_OF_RANGE";this.undo(A),F=this.cacheIdx===T-1}const k=o.substring(n+1);return this.doStep(k),this.mode="record",this.cacheUpdateNumber=t,null}return"OUT_OF_RANGE"}undoStep(o){const n=o.indexOf(":"),t=o.substring(0,n),S=o.substring(n+1);switch(t){case"add":this.delete(JSON.parse(S));break;case"del":this.add(JSON.parse(S));break;case"clear":{const f=JSON.parse(S);for(let T of f)this.add(T);break}case"tx":{const f=S.split(";");for(let T=f.length-1;T>=0;T--)this.undoStep(f[T])}}}undo(o){const n=o.indexOf("=");if(Number(o.substring(0,n))===this.cacheUpdateNumber){this.mode="playback";const S=o.substring(n+1);return this.undoStep(S),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function zo(o){return o[0].toUpperCase()+o.slice(1)}function dS(o,n,t=ko.STORE){return TT(t).set(o.key,new FT(o,n,t)),{key:o.key,type:"join",a:o.between[0],b:o.between[1],cardinality:o.cardinality}}function TT(o){if("joins"in o&&o.joins instanceof Map)return o.joins;const n=new Map;return o.joins=n,n}function $S(o,n){const t=TT(n);let S=t.get(o.key);if(S===void 0){if(S=TT(ko.STORE).get(o.key)?.in(n),S===void 0)throw new Error(`Join "${o.key}" not found in store "${n.config.name}"`);t.set(o.key,S)}return S}function yF(o,n,t){const S=$S(o,t);let f;switch(o.cardinality){case"1:1":{const T=`${o.a}KeyOf${zo(o.b)}`,M=`${o.b}KeyOf${zo(o.a)}`;f={get[T](){const k=S.states[T];return S.retrieve(k,n)},get[M](){const k=S.states[M];return S.retrieve(k,n)}};const F=`${o.a}EntryOf${zo(o.b)}`;if(F in S.states){const k=`${o.b}EntryOf${zo(o.a)}`;Object.assign(f,{get[F](){const A=S.states[F];return S.retrieve(A,n)},get[k](){const A=S.states[k];return S.retrieve(A,n)}})}break}case"1:n":{const T=`${o.a}KeyOf${zo(o.b)}`,M=`${o.b}KeysOf${zo(o.a)}`;f={get[T](){const k=S.states[T];return S.retrieve(k,n)},get[M](){const k=S.states[M];return S.retrieve(k,n)}};const F=`${o.a}EntryOf${zo(o.b)}`;if(F in S.states){const k=`${o.b}EntriesOf${zo(o.a)}`;Object.assign(f,{get[F](){const A=S.states[F];return S.retrieve(A,n)},get[k](){const A=S.states[k];return S.retrieve(A,n)}})}break}case"n:n":{const T=`${o.a}KeysOf${zo(o.b)}`,M=`${o.b}KeysOf${zo(o.a)}`;f={get[T](){const k=S.states[T];return S.retrieve(k,n)},get[M](){const k=S.states[M];return S.retrieve(k,n)}};const F=`${o.a}EntriesOf${zo(o.b)}`;if(F in S.states){const k=`${o.b}EntriesOf${zo(o.a)}`;Object.assign(f,{get[F](){const A=S.states[F];return S.retrieve(A,n)},get[k](){const A=S.states[k];return S.retrieve(A,n)}})}}}return f}function RF(o,n){return yF(o,n,ko.STORE)}function uS(o,n,t){const S=$S(o,t),f=m(t);if(Fo(f)){const{toolkit:T}=f.transactionMeta;S.transact(T,({relations:M})=>{n(M)})}else n(S.relations)}function yy(o,n){return $S(o,n).core.findRelatedKeysState}function OF(o){return yy(o,ko.STORE)}class FT{options;defaultContent;toolkit;retrieve;molecules=new Map;relations;states;core;transact(o,n){const t=this.toolkit;this.toolkit=o,n(this),this.toolkit=t}store;alternates;[Symbol.dispose](){this.alternates.delete(this.store.config.name)}in(o){const n=o.config.name,t=this.alternates.get(n);if(t)return t;const S=new FT(this.options,this.defaultContent,o);return this.alternates.set(n,S),S.alternates=this.alternates,S}constructor(o,n,t=ko.STORE){this.store=t,this.options=o,this.defaultContent=n,this.alternates=new Map,this.alternates.set(t.config.name,this),this.store.miscResources.set(`join:${o.key}`,this),this.retrieve=(Y,K)=>{const Q=this.toolkit.seek(Y,K);if(Q)return Q;const i=this.molecules.get(l(K));if(i){const g=u(Y,t);return zn(i,g,t)}if(t.config.lifespan==="immortal")throw new tn(Y,K,t);return xn(t,Y,K)},this.toolkit={get:(...Y)=>Go(t,...Y),set:(...Y)=>{Co(t,...Y)},find:this.retrieve,seek:(...Y)=>Eo(t,...Y),json:(Y)=>ho(t,Y),dispose:(...Y)=>{uo(t,...Y)}};const S=o.between[0],f=o.between[1],T=SS(t,{key:`${o.key}/relatedKeys`,default:()=>new Bo,mutable:!0,fromJson:(Y)=>Bo.fromJSON(Y),toJson:(Y)=>Y.toJSON()},["join","relations"]);this.core={findRelatedKeysState:T};const M=({get:Y},K)=>Y(this.retrieve(T,K)),F=(Y,K,Q)=>{const{set:i}=Y,g=this.retrieve(T,K),_=this.retrieve(T,Q);i(g,(h)=>h.add(Q)),i(_,(h)=>h.add(K))},k=(Y,K,Q)=>{const{set:i}=Y,g=this.retrieve(T,K),_=this.retrieve(T,Q);let h,C;i(g,(a)=>{if(a.delete(Q),a.size===0)h=`"${K}"`;return a}),i(_,(a)=>{if(a.delete(K),a.size===0)C=`"${Q}"`;return a})},A=(Y,K,Q)=>{const{get:i,set:g}=Y,_=this.retrieve(T,K),h=i(_);for(let C of h){if(Q.includes(C))continue;const So=this.retrieve(T,C);g(So,(to)=>{return to.delete(K),to})}g(_,(C)=>{return C.transaction((a)=>{a.clear();for(let So of Q){const to=M(Y,So),Wo=to.has(K);if(this.relations.cardinality==="1:n"){const Mn=[];for(let E of to){if(E===K)continue;const x=M(Y,E);if(x.delete(So),x.size===0)Mn.push(E)}if(!Wo&&to.size>0)to.clear();for(let E of Mn){const x=[So,E].sort(),To=`"${x[0]}:${x[1]}"`;this.molecules.delete(To)}}if(!Wo)to.add(K);a.add(So)}return!0}),C})},$=(Y,K,Q)=>{const{set:i}=Y,g=this.retrieve(T,K);i(g,(_)=>{return _.transaction((h)=>{for(let C of Q)h.add(C);return!0}),_});for(let _ of Q){const h=this.retrieve(T,_);i(h,(C)=>{return C.add(K),C})}return!0},O=(Y,K,Q)=>{const i=M(Y,K);return Q?i.has(Q):i.size>0},w={getRelatedKeys:(Y)=>M(this.toolkit,Y),addRelation:(Y,K)=>{F(this.toolkit,Y,K)},deleteRelation:(Y,K)=>{k(this.toolkit,Y,K)},replaceRelationsSafely:(Y,K)=>{A(this.toolkit,Y,K)},replaceRelationsUnsafely:(Y,K)=>{$(this.toolkit,Y,K)},has:(Y,K)=>O(this.toolkit,Y,K)};let G,r,H;if(n){r=jn(t,{key:`${o.key}/content`,default:n},["join","content"]);const Y={key:o.key,type:"join",a:o.between[0],b:o.between[1],cardinality:o.cardinality};H=JF(t,{key:`${o.key}/content-molecules`,new:class _{C;constructor(h,C){this.key=C}}});const K=({get:_},h)=>_(this.retrieve(r,h)),Q=({set:_},h,C)=>{_(this.retrieve(r,h),C)},i=(_,h)=>{const C=t.molecules.get(`"${h}"`);if(C)this.toolkit.dispose(C),this.molecules.delete(`"${h}"`)};G=Object.assign(w,{getContent:(_)=>{return K(this.toolkit,_)},setContent:(_,h)=>{Q(this.toolkit,_,h)},deleteContent:(_)=>{i(this.toolkit,_)}})}else G=w;const D=new Fn(o,{externalStore:G,makeContentKey:(...Y)=>{const K=Y.sort(),Q=`${K[0]}:${K[1]}`,[i,g]=K.map((_)=>this.molecules.get(l(_)));if(t.config.lifespan==="immortal"&&i&&g){const _=m(t),h=vn(_,[i,g],H,Q);this.molecules.set(`"${Q}"`,u(h,_))}return Q}}),I=()=>hn(t,{key:`${o.key}/singleRelatedKey`,get:(Y)=>({get:K})=>{const Q=this.retrieve(T,Y),i=K(Q);for(let g of i)return g;return null}},["join","keys"]),v=()=>{return hn(t,{key:`${o.key}/multipleRelatedKeys`,get:(Y)=>({get:K})=>{const Q=MT(T,t),i=this.retrieve(Q,Y);return K(i).members}},["join","keys"])},N=()=>hn(t,{key:`${o.key}/singleRelatedEntry`,get:(Y)=>({get:K})=>{const Q=this.retrieve(T,Y),i=K(Q);for(let g of i){const _=D.makeContentKey(Y,g),h=this.retrieve(r,_),C=K(h);return[g,C]}return null}},["join","entries"]),P=()=>hn(t,{key:`${o.key}/multipleRelatedEntries`,get:(Y)=>({get:K})=>{const Q=MT(T,t),i=this.retrieve(Q,Y);return K(i).members.map((_)=>{const h=D.makeContentKey(Y,_),C=this.retrieve(r,h),a=K(C);return[_,a]})}},["join","entries"]);switch(o.cardinality){case"1:1":{const Y=I(),K=`${S}KeyOf${zo(f)}`,Q=`${f}KeyOf${zo(S)}`,i={[K]:Y,[Q]:Y};let g;if(n){const _=N(),h=`${S}EntryOf${zo(f)}`,C=`${f}EntryOf${zo(S)}`,a={[h]:_,[C]:_};g=Object.assign(i,a)}else g=i;this.relations=D,this.states=g;break}case"1:n":{const Y=I(),K=v(),Q=`${S}KeyOf${zo(f)}`,i=`${f}KeysOf${zo(S)}`,g={[Q]:Y,[i]:K};let _;if(n){const h=N(),C=P(),a=`${S}EntryOf${zo(f)}`,So=`${f}EntriesOf${zo(S)}`,to={[a]:h,[So]:C};_=Object.assign(g,to)}else _=g;this.relations=D,this.states=_;break}default:{const Y=v(),K=`${S}KeysOf${zo(f)}`,Q=`${f}KeysOf${zo(S)}`,i={[K]:Y,[Q]:Y};let g;if(n){const _=P(),h=`${S}EntriesOf${zo(f)}`,C=`${f}EntriesOf${zo(S)}`,a={[h]:_,[C]:_};g=Object.assign(i,a)}else g=i;this.relations=D,this.states=g}}}}function aS(o){return{store:o}}function Go(o,...n){let t,S,f;if(n.length===1){if(t=n[0],t.type!=="molecule"){if(S=lS(o,t)??null,S)f=t.family?Uo(t.family.subKey):null,t=Ro(o,S,f)}}else{S=n[0],f=n[1];let T;if(S.type==="molecule_family")T=Eo(o,S,f)??Ht(S,f);else T=Ro(o,S,f);t=T}if("counterfeit"in t&&"family"in t){S=t.type==="molecule"?u(t.family,o):o.families.get(t.family.key);const T=t.type==="molecule"?t.key:t.family.subKey,M=o.disposalTraces.buffer.find((F)=>F?.key===t.key);switch(o.logger.error("\u274C",t.type,t.key,`could not be retrieved because it was not found in the store "${o.config.name}".`,M?`This state was previously disposed:\n${M.trace}`:"No previous disposal trace was found."),S.type){case"atom_family":case"mutable_atom_family":return o.defaults.get(S.key);case"selector_family":case"readonly_selector_family":{if(o.defaults.has(S.key))return o.defaults.get(t.family.key);const F=u(S,o).default(T);return o.defaults.set(S.key,F),F}case"molecule_family":throw new tn(S,T,o)}}switch(t.type){case"atom":case"mutable_atom":case"selector":case"readonly_selector":return en(u(t,o),o);case"molecule":return u(t,o).instance}}class Dt{n;type="molecule";stringKey;family;_dependsOn;get dependsOn(){if(this.family)return this.family.dependsOn;return this._dependsOn}subject=new s;tokens=new Map;above=new Map;below=new Map;joins=new Map;instance;constructor(o,n,t){this.key=n;if(this.stringKey=l(n),t)this.family=t,this._dependsOn=t.dependsOn;if(o)for(let S of o)this.above.set(S.stringKey,S)}}function WF(o){return o[0].toUpperCase()+o.slice(1)}function vn(o,n,t,S,...f){const T=lM(o),M=m(o),F=l(S);M.moleculeInProgress=F;const k=Array.isArray(n)?n:[n],A=k.map((D)=>{if(D instanceof Dt)return D;const I=l(D.key),v=o.molecules.get(I);if(!v)throw new Error(`Molecule ${I} not found in store "${o.config.name}"`);return v}),$=new Dt(A,S,t);M.molecules.set(F,$);for(let D of A)D.below.set($.stringKey,$);const O={get:(...D)=>Go(m(T),...D),set:(...D)=>{Co(m(T),...D)},seek:(D,I)=>Eo(m(T),D,I),json:(D)=>ho(m(T),D),run:(D,I=zt())=>At(D,I,m(o)),make:(D,I,v,...N)=>vn(m(T),D,I,v,...N),dispose:(D)=>{uo(m(T),D)},env:()=>aS(m(T)),bond:(D,I)=>{if(D.type==="join"){const{as:v}=I,N=$S(D,T);N.molecules.set(F,$),$.joins.set(D.key,N);const P=w.subject.subscribe(`join:${D.key}-${F}`,(_)=>{if(_.type==="molecule_disposal"){if(l(_.token.key)===F)P(),N.molecules.delete(F)}});if(v===null)return;const Y=D.a===v?D.b:D.a,K=RF(D,S),Q=K[`${Y}KeysOf${WF(v)}`],i=K[`${Y}EntriesOf${WF(v)}`];let g={relatedKeys:Q};if(i)g=Object.assign(g,{relatedEntries:i});return g}return zn($,u(D,T),m(T))},claim:(D,I)=>{const{exclusive:v}=I,N=m(o).molecules.get(l(D.key));if(N)if(v){for(let P of N.above.values())P.below.delete(N.stringKey);N.above.clear(),N.above.set($.stringKey,$),$.below.set(N.stringKey,N)}else N.above.set($.stringKey,$),$.below.set(N.stringKey,N)},spawn:(D,I,...v)=>vn(m(o),[$],u(D,o),I,...v)},w=u(t,o),G=w.new;$.instance=new G(O,S,...f);const r={type:"molecule",key:S,family:t},H={type:"molecule_creation",subType:"classic",token:r,family:t,context:k,params:f};if(bo(M))w.subject.next(H);else if(Fo(M)&&M.on.transactionApplying.state===null)M.transactionMeta.update.updates.push(H);return M.moleculeInProgress=null,r}function kT(o,n,t){switch(n){case"newValue":{_F(o,t);break}case"oldValue":{uo(t,o.token);break}}}function AT(o,n,t){switch(n){case"newValue":{uo(t,o.token);break}case"oldValue":{_F(o,t),t.valueMap.set(o.token.key,o.value);break}}}function _F(o,n){const{family:t}=o.token;if(t){const S=n.families.get(t.key);if(S)Ro(n,S,Uo(t.subKey))}}function $T(o,n,t){switch(n){case"newValue":switch(o.subType){case"classic":vn(t,o.context,o.family,o.token.key,...o.params);break;case"modern":fT(t,o.provenance,o.key);break}break;case"oldValue":switch(o.subType){case"classic":uo(t,o.token);break;case"modern":AS(t,o.key);break}break}}function JT(o,n,t){switch(n){case"newValue":switch(o.subType){case"classic":uo(t,o.token);break;case"modern":AS(t,o.key);break}break;case"oldValue":switch(o.subType){case"classic":{const S=vn(t,o.context,o.family,o.token.key);for(let[f,T]of o.values){const M=`${f}(${l(S.key)})`,F=u(S,t),k=F.tokens.has(M),A=t.families.get(f);if(A&&!k)zn(F,A,t);t.valueMap.set(M,T)}}break;case"modern":{fT(t,o.provenance,o.key);for(let[S,f]of o.values){const T=t.families.get(S);if(T){Ro(t,T,o.key);const M=`${S}(${l(o.key)})`;t.valueMap.set(M,f)}}}}break}}function sS(o,n,t){const S=o==="newValue"?n.updates:[...n.updates].reverse();for(let f of S)switch(f.type){case"atom_update":case"selector_update":eS(o,f,t);break;case"state_creation":kT(f,o,t);break;case"state_disposal":AT(f,o,t);break;case"molecule_creation":$T(f,o,t);break;case"molecule_disposal":JT(f,o,t);break;case"transaction_update":sS(o,f,t);break}}function wF(o,n,t){if(!bo(t))return;const f=t.transactionMeta.actionContinuities.getRelatedKey(o);if(f!==void 0)t.transactionMeta.epoch.set(f,n)}var KF=(o,n)=>{const t=m(n),{parent:S}=t;if(S===null||!Fo(t)||t.transactionMeta?.phase!=="building"){n.logger.warn("\uD83D\uDC1E","transaction","???","applyTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}t.transactionMeta.phase="applying",t.transactionMeta.update.output=o,S.child=null,S.on.transactionApplying.next(t.transactionMeta);const{updates:f}=t.transactionMeta.update;if(n.logger.info("\uD83D\uDEC4","transaction",t.transactionMeta.update.key,`Applying transaction with ${f.length} updates:`,f),sS("newValue",t.transactionMeta.update,S),bo(S))wF(t.transactionMeta.update.key,t.transactionMeta.update.epoch,S),u({key:t.transactionMeta.update.key,type:"transaction"},n)?.subject.next(t.transactionMeta.update),n.logger.info("\uD83D\uDEEC","transaction",t.transactionMeta.update.key,"Finished applying transaction.");else if(Fo(S))S.transactionMeta.update.updates.push(t.transactionMeta.update);S.on.transactionApplying.next(null)};class On extends Map{o;deleted=new Set;constructor(o){super();this.source=o}get(o){if(super.has(o))return super.get(o);if(!this.deleted.has(o)&&this.source.has(o))return this.source.get(o);return}set(o,n){return this.deleted.delete(o),super.set(o,n)}hasOwn(o){return super.has(o)}has(o){return!this.deleted.has(o)&&(super.has(o)||this.source.has(o))}delete(o){return this.deleted.add(o),super.delete(o)}}var XF=(o,n,t,S)=>{const f=m(t),T={parent:f,child:null,on:f.on,loggers:f.loggers,logger:f.logger,config:f.config,atoms:new On(f.atoms),atomsThatAreDefault:new Set(f.atomsThatAreDefault),families:new On(f.families),operation:{open:!1},readonlySelectors:new On(f.readonlySelectors),timelines:new On(f.timelines),timelineTopics:new Fn(f.timelineTopics.toJSON()),trackers:new Map,transactions:new On(f.transactions),selectorAtoms:new Fn(f.selectorAtoms.toJSON()),selectorGraph:new Fn(f.selectorGraph.toJSON(),{makeContentKey:(...A)=>A.sort().join(":")}),selectors:new On(f.selectors),valueMap:new On(f.valueMap),defaults:f.defaults,disposalTraces:t.disposalTraces.copy(),molecules:new On(f.molecules),moleculeFamilies:new On(f.moleculeFamilies),moleculeInProgress:f.moleculeInProgress,miscResources:new On(f.miscResources)},M=YF(o,t),F={phase:"building",update:{type:"transaction_update",key:o,id:S,epoch:M===void 0?Number.NaN:M+1,updates:[],params:n,output:void 0},toolkit:{get:(...A)=>Go(k,...A),set:(...A)=>{Co(k,...A)},run:(A,$=zt())=>At(A,$,k),find:(A,$)=>Ro(k,A,$),seek:(A,$)=>Eo(k,A,$),json:(A)=>ho(k,A),make:(A,$,O,...w)=>vn(k,A,$,O,...w),dispose:(...A)=>{uo(k,...A)},env:()=>aS(k)}},k=Object.assign(T,{transactionMeta:F});return f.child=k,t.logger.info("\uD83D\uDEEB","transaction",o,"Building transaction with params:",n),k};function tT(o,n){const t={key:o.key,type:"transaction",run:(T,M)=>{const F=XF(o.key,T,n,M);try{const k=m(n),{toolkit:A}=F.transactionMeta,$=o.do(A,...T);return KF($,k),$}catch(k){throw aM(S),n.logger.warn("\uD83D\uDCA5","transaction",o.key,"caught:",k),k}},install:(T)=>tT(o,T),subject:new s},S=m(n);S.transactions.set(t.key,t);const f=Po(t);return n.on.transactionCreation.next(f),f}function YF(o,n){const t=bo(n),S=t?n.transactionMeta.actionContinuities.getRelatedKey(o):void 0;return t&&S!==void 0?n.transactionMeta.epoch.get(S):void 0}class of{_buffer;_index=0;constructor(o){let n;if(typeof o==="number")n=o;else n=o.length;this._buffer=Array.from({length:n})}get buffer(){return this._buffer}get index(){return this._index}add(o){this._buffer[this._index]=o,this._index=(this._index+1)%this._buffer.length}copy(){const o=new of([...this._buffer]);return o._index=this._index,o}}class EF{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;selectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new Fn({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new Fn({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...o)=>o.sort().join(":")});trackers=new Map;families=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new Fn({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new Fn({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new of(100);molecules=new Map;moleculeFamilies=new Map;moleculeInProgress=null;miscResources=new Map;on={atomCreation:new s,atomDisposal:new s,selectorCreation:new s,selectorDisposal:new s,timelineCreation:new s,transactionCreation:new s,transactionApplying:new af(null),operationClose:new s,moleculeCreationStart:new s,moleculeCreationDone:new s,moleculeDisposal:new s};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new nT("warn",(o,n,t)=>!t.includes("\uD83D\uDD0D"))];logger={error:(...o)=>{for(let n of this.loggers)n.error(...o)},info:(...o)=>{for(let n of this.loggers)n.info(...o)},warn:(...o)=>{for(let n of this.loggers)n.warn(...o)}};constructor(o,n=null){if(this.config={...n?.config,...o},n!==null){if(this.valueMap=new Map(n?.valueMap),this.operation={...n?.operation},bo(n))this.transactionMeta={epoch:new Map(n?.transactionMeta.epoch),actionContinuities:new Fn(n?.transactionMeta.actionContinuities.toJSON())};for(let[,S]of n.families){if(S.internalRoles?.includes("mutable")||S.internalRoles?.includes("join"))continue;S.install(this)}const t=new Set;for(let[,S]of n.atoms){if(t.has(S.key))continue;if(S.install(this),S.type==="mutable_atom"){const f=ho(n,S),T=dn(S);t.add(f.key),t.add(T.key)}}for(let[,S]of n.readonlySelectors)S.install(this);for(let[,S]of n.selectors){if(t.has(S.key))continue;S.install(this)}for(let[,S]of n.transactions)S.install(this);for(let[,S]of n.timelines)S.install(this)}}}var ko={get STORE(){if(!globalThis.ATOM_IO_IMPLICIT_STORE)globalThis.ATOM_IO_IMPLICIT_STORE=new EF({name:"IMPLICIT_STORE",lifespan:"ephemeral"});return globalThis.ATOM_IO_IMPLICIT_STORE}};function u(o,n){let t,S=n;while(S!==null){switch(o.type){case"atom":case"mutable_atom":t=S.atoms.get(o.key);break;case"selector":t=S.selectors.get(o.key);break;case"readonly_selector":t=S.readonlySelectors.get(o.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":t=S.families.get(o.key);break;case"timeline":t=S.timelines.get(o.key);break;case"transaction":t=S.transactions.get(o.key);break;case"molecule":t=S.molecules.get(l(o.key));break;case"molecule_family":t=S.moleculeFamilies.get(o.key);break}if(t)return t;S=S.child}throw new tn(o,n)}function nf(o,n){let t;t=u(o,n);const{family:S}=o;for(let M of t.joins.values())M.relations.delete(t.key),M.molecules.delete(t.stringKey);const f=[];for(let M of t.above.values())f.push(Po(M));const T=[];for(let M of t.tokens.values()){const F=M.family;T.push([F.key,n.valueMap.get(M.key)])}if(S){const M=u(S,n),F={type:"molecule_disposal",subType:"classic",token:o,family:S,context:f,values:T};if(o.family)F.family=o.family;for(let A of t.tokens.values())uo(n,A);for(let A of t.below.values())if(A.dependsOn==="all")nf(A,n);else if(A.above.delete(t.stringKey),A.above.size===0)nf(A,n);if(t.below.clear(),Fo(n)&&n.transactionMeta.phase==="building")n.transactionMeta.update.updates.push(F);else M.subject.next(F);n.molecules.delete(t.stringKey)}for(let M of t.above.values())M.below.delete(t.stringKey)}function xn(o,n,t){const S=o.families.get(n.key);if(S===void 0)throw new tn(n,o);const f=S(t),T=m(o);if(f.family&&T.moleculeInProgress===null){if(bo(T))switch(f.type){case"atom":case"mutable_atom":o.on.atomCreation.next(f);break;case"selector":case"readonly_selector":o.on.selectorCreation.next(f);break}else if(Fo(T)&&T.on.transactionApplying.state===null)T.transactionMeta.update.updates.push({type:"state_creation",token:f})}return f}function Eo(o,n,t){const S=l(t),f=`${n.key}(${S})`,T=m(o);let M;switch(n.type){case"atom_family":case"mutable_atom_family":M=T.atoms.get(f);break;case"selector_family":M=T.selectors.get(f);break;case"readonly_selector_family":M=T.readonlySelectors.get(f);break;case"molecule_family":M=T.molecules.get(l(t))}if(M)return Po(M);return M}function Ro(o,n,t){let S=Eo(o,n,t);if(S)return S;const f=o.molecules.get(l(t));if(f)return zn(f,n,o);if(o.config.lifespan==="immortal"){const T=Ht(n,t);return o.logger.error("\u274C",T.type,T.key,`was not found in store "${o.config.name}"; returned a counterfeit token.`),T}return S=xn(o,n,t),S}function uo(o,...n){let t,S;if(n.length===1)t=n[0],S=t.key;else{const T=n[0],M=n[1];t=T.type==="molecule_family"?Eo(o,T,M)??Ht(T,M):Ro(o,T,M)}try{u(t,o)}catch(T){const M=o.disposalTraces.buffer.find((F)=>F?.key===t.key);o.logger.error("\u274C",t.type,t.key,`could not be disposed because it was not found in the store "${o.config.name}".`,M?`\n This state was most recently disposed\n${M.trace}`:"No previous disposal trace was found.");return}switch(t.type){case"atom":case"mutable_atom":yT(t,o);break;case"selector":case"readonly_selector":GF(t,o);break;case"molecule":nf(t,o);break}const{stack:f}=new Error;if(f){const T=f?.split("\n")?.slice(3)?.join("\n");o.disposalTraces.add({key:t.key,trace:T})}}var tf=(o,n)=>m(n).atoms.has(o),Ry=(o,n)=>m(n).selectors.has(o),Oy=(o,n)=>m(n).readonlySelectors.has(o),zF=(o,n)=>tf(o,n)||Ry(o,n)||Oy(o,n);var Sf=(o,n)=>{return m(n).selectorGraph.getRelationEntries({downstreamSelectorKey:o}).filter(([S,{source:f}])=>f!==o).map(([S,{source:f}])=>f).filter((S)=>zF(S,n))};var RT=(o,n,t)=>{const S=[],f=Sf(o,t);while(f.length>0){const T=f.shift();if(n.has(T))continue;if(n.add(T),!tf(T,t))f.push(...Sf(T,t));else if(!S.includes(T))S.push(T)}return S},HF=(o,n)=>{const t=o.key,S=Sf(t,n),f=new Set;return S.flatMap((T)=>tf(T,n)?T:RT(T,f,n))};var mF=(o,n,t,S)=>{const f=m(S);if(n.type==="atom"||n.type==="mutable_atom")f.selectorAtoms.set({selectorKey:o,atomKey:n.key}),S.logger.info("\uD83D\uDD0D","selector",o,`discovers root atom "${n.key}"`);else{const T=RT(n.key,t,S);S.logger.info("\uD83D\uDD0D","selector",o,`discovers root atoms: [ ${T.map((M)=>`"${M}"`).join(", ")} ]`);for(let M of T)f.selectorAtoms=f.selectorAtoms.set({selectorKey:o,atomKey:M})}t.add(n.key)};var ff=(o,n,t)=>({get:(...S)=>{const f=m(t);let T;if(S.length===2){const[k,A]=S;switch(k.type){case"molecule_family":return Go(t,k,A);default:if(t.config.lifespan==="ephemeral")T=Ro(t,k,A);else{const $=Eo(t,k,A);if($)T=$;else throw new tn(k,A,t)}}}else[T]=S;if(T.type==="molecule")return Go(t,T);const M=u(T,t),F=en(M,t);return t.logger.info("\uD83D\uDD0C","selector",o,`registers dependency ( "${T.key}" =`,F,")"),f.selectorGraph.set({upstreamSelectorKey:T.key,downstreamSelectorKey:o},{source:T.key}),mF(o,T,n,t),F},set:(...S)=>{let f,T;if(S.length===2)f=S[0],T=S[1];else{const k=S[0],A=S[1];T=S[2];const $=t.config.lifespan==="ephemeral"?Ro(t,k,A):Eo(t,k,A);if(!$)throw new tn(k,A,t);f=$}const M=m(t),F=u(f,M);gS(F,T,M)},find:(S,f)=>Ro(t,S,f),seek:(S,f)=>Eo(t,S,f),json:(S)=>ho(t,S)});var fS=(o,n,t)=>{const S=m(o),f=new s,T=new Set,{get:M,find:F,seek:k,json:A}=ff(n.key,T,S),$=()=>{const r=n.get({get:M,find:F,seek:k,json:A});return Rn(n.key,r,f,m(o)),T.clear(),r},O={...n,subject:f,install:(r)=>fS(r,n,t),get:$,type:"readonly_selector",...t&&{family:t}};S.readonlySelectors.set(n.key,O);const w=$();o.logger.info("\u2728",O.type,O.key,"=",w);const G={key:n.key,type:"readonly_selector"};if(t)G.family=t;return G};var JS=(o,n,t)=>{const S=m(o),f=new s,T=new Set,M=ff(n.key,T,S),{find:F,get:k,seek:A,json:$}=M,O={find:F,get:k,seek:A,json:$},w=(I=n.get,v=m(o))=>{const N=I(O);return Rn(n.key,N,f,v),T.clear(),N},r={...n,subject:f,install:(I)=>JS(I,n,t),get:w,set:(I)=>{const v=m(o),N=w(n.get,v),P=PS(I)(N);if(o.logger.info("\uD83D\uDCDD","selector",n.key,"set (",N,"->",P,")"),Rn(n.key,P,f,v),Qt(v,n.key),bo(v))f.next({newValue:P,oldValue:N});n.set(M,P)},type:"selector",...t&&{family:t}};S.selectors.set(n.key,r);const H=w();o.logger.info("\u2728",r.type,r.key,"=",H);const D={key:n.key,type:"selector"};if(t)D.family=t;return D};function En(o,n){if("set"in n){const f=JS(o,n,void 0);return o.on.selectorCreation.next(f),f}const S=fS(o,n,void 0);return o.on.selectorCreation.next(S),S}function GF(o,n){const t=m(n),{key:S}=o,f=u(o,t);if(!f.family)n.logger.error("\u274C","selector",S,"Standalone selectors cannot be disposed.");else{const T=t.molecules.get(f.family.subKey);if(T)T.tokens.delete(S);switch(o.type){case"selector":t.selectors.delete(S),u({key:f.family.key,type:"selector_family"},n).subject.next({type:"state_disposal",token:o});break;case"readonly_selector":t.readonlySelectors.delete(S),u({key:f.family.key,type:"readonly_selector_family"},n).subject.next({type:"state_disposal",token:o});break}if(t.valueMap.delete(S),t.selectorAtoms.delete(S),t.selectorGraph.delete(S),n.logger.info("\uD83D\uDD25",o.type,S,"deleted"),Fo(t)&&t.transactionMeta.phase==="building")t.transactionMeta.update.updates.push({type:"state_disposal",token:o});else n.on.selectorDisposal.next(o)}}function MS(o,n,t){const S={key:n.key,type:"selector_family"},f=o.families.get(n.key);if(f)o.logger.error("\u2757","selector_family",n.key,`Overwriting an existing ${Gn(f)} "${f.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const T=new s,F=Object.assign((k)=>{const A=l(k),$={key:n.key,subKey:A},O=`${n.key}(${A})`,w=m(o),G=JS(w,{key:O,get:n.get(k),set:n.set(k)},$);return T.next({type:"state_creation",token:G}),G},S,{internalRoles:t,subject:T,install:(k)=>MS(k,n),default:(k)=>{return n.get(k)({get:(...$)=>Go(o,...$),find:($,O)=>Ro(o,$,O),seek:($,O)=>Eo(o,$,O),json:($)=>ho(o,$)})}});return o.families.set(n.key,F),S}function QF(o,n,t=ko.STORE){const S=MS(t,{key:`${o.key}:JSON`,get:(T)=>({seek:M,get:F})=>{const k=M(o,T);if(k)return n.toJson(F(k));const A=l(T),$=t.molecules.get(A);if($){const w=zn($,o,t);return n.toJson(F(w))}if(t.config.lifespan==="immortal")throw new Error(`No molecule found for key "${A}"`);const O=xn(t,o,T);return n.toJson(F(O))},set:(T)=>({seek:M,set:F},k)=>{const A=M(o,T);if(A)F(A,n.fromJson(k));else{const $=l(T),O=t.molecules.get($);if(O){const w=zn(O,o,t);F(w,n.fromJson(k))}else{if(t.config.lifespan==="immortal")throw new Error(`No molecule found for key "${$}"`);F(xn(t,o,T),n.fromJson(k))}}}},["mutable","json"]);return u(o,t).subject.subscribe(`store=${t.config.name}::json-selector-family`,(T)=>{if(T.token.family)Eo(t,S,Uo(T.token.family.subKey))}),S}var Uo=(o)=>JSON.parse(o),l=(o)=>JSON.stringify(o),rK=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var DF=(o,n)=>{const t=m(n);if(t.operation.open)return t.operation.prev.get(o.key);return t.valueMap.get(o.key)};var WT=(o,n)=>{const t=m(n);return HF(o,n).map((f)=>{const T=t.atoms.get(f);if(T===void 0)throw new Error(`Atom "${f}", a dependency of selector "${o.key}", not found in store "${n.config.name}".`);return T.subject.subscribe(`${o.type}:${o.key}`,(M)=>{n.logger.info("\uD83D\uDCE2",o.type,o.key,"root",f,"went",M.oldValue,"->",M.newValue);const F=DF(o,t),k=en(o,t);n.logger.info("\u2728",o.type,o.key,"went",F,"->",k),o.subject.next({newValue:k,oldValue:F})})})};function kn(o,n,t,S){function f(O){if(S.operation.open){const w=S.on.operationClose.subscribe(`state subscription ${t}`,()=>{w(),n(O)})}else n(O)}const T=u(o,S);S.logger.info("\uD83D\uDC40",T.type,T.key,`Adding subscription "${t}"`);const M=T.type==="selector"||T.type==="readonly_selector";let F=null,k=f;if(M)F=WT(T,S),k=(O)=>{if(F)F.length=0,F.push(...WT(T,S));f(O)};const A=T.subject.subscribe(t,k);return()=>{if(S.logger.info("\uD83D\uDE48",T.type,T.key,`Removing subscription "${t}"`),A(),F)for(let O of F)O()}}var OT=(o,n,t,S)=>{const f=u(o,S);S.logger.info("\uD83D\uDC40","timeline",o.key,`Adding subscription "${t}"`);const T=f.subject.subscribe(t,n);return()=>{S.logger.info("\uD83D\uDE48","timeline",o.key,`Removing subscription "${t}" from timeline`),T()}};class un{Update;initializeState(o,n){const t=`*${o.key}`;n.atoms.delete(t),n.valueMap.delete(t);const S=o.family?{key:`*${o.family.key}`,subKey:o.family.subKey}:void 0,f=nn(n,{key:t,default:null},S);if(n.parent?.valueMap.has(t)){const T=n.parent.valueMap.get(t);n.valueMap.set(t,T)}return f}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(o,n,t){const S=`tracker:${t.config.name}:${Fo(t)?t.transactionMeta.update.key:"main"}:${o.key}`,f=Go(t,o);this.unsubscribeFromInnerValue=f.subscribe(S,(T)=>{Co(t,n,T)}),this.unsubscribeFromState=kn(o,(T)=>{if(T.newValue!==T.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=T.newValue.subscribe(S,(M)=>{Co(t,n,M)})},S,t)}updateCore(o,n,t){const S=`tracker:${t.config.name}:${Fo(t)?t.transactionMeta.update.key:"main"}:${o.key}`;kn(n,({newValue:f,oldValue:T})=>{const M=t.timelineTopics.getRelatedKey(n.key);if(M){if(t.timelines.get(M)?.timeTraveling){const A=OT({key:M,type:"timeline"},($)=>{A(),Co(t,o,(O)=>{if($==="redo"&&f)O.do(f);else if($==="undo"&&T)O.undo(T);return O})},S,t);return}}const F=t.on.operationClose.subscribe(S,()=>{F();const k=Go(t,o),A=f===null?-1:k.getUpdateNumber(f),$=A-k.cacheUpdateNumber;if(f&&$===1)Co(t,o,(O)=>(O.do(f),O));else t.logger.info("\u274C","mutable_atom",o.key,`could not be updated. Expected update number ${k.cacheUpdateNumber+1}, but got ${A}`)})},S,t)}mutableState;latestUpdateState;dispose;constructor(o,n){this.mutableState=o;const t=m(n);this.latestUpdateState=this.initializeState(o,t),this.observeCore(o,this.latestUpdateState,t),this.updateCore(o,this.latestUpdateState,t),t.trackers.set(o.key,this),this.dispose=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),t.trackers.delete(o.key)}}}function yS(o,n,t){o.logger.info("\uD83D\uDD28","atom",n.key,`creating in store "${o.config.name}"`);const S=m(o),f=S.atoms.get(n.key);if(f&&f.type==="mutable_atom")return o.logger.error("\u274C","atom",n.key,"Tried to create atom, but it already exists in the store."),Po(f);const T=new s,M={...n,type:"mutable_atom",install:(A)=>{return A.logger.info("\uD83D\uDEE0\uFE0F","atom",n.key,`installing in store "${A.config.name}"`),yS(A,n,t)},subject:T};if(t)M.family=t;const F=n.default();S.atoms.set(M.key,M),Tf(n.key,o),Rn(n.key,F,T,S);const k=Po(M);if(n.effects){let A=0;const $=[];for(let O of n.effects){const w=O({setSelf:(G)=>{Co(o,k,G)},onSet:(G)=>kn(k,G,`effect[${A}]`,o)});if(w)$.push(w);++A}M.cleanup=()=>{for(let O of $)O()}}if(new un(k,o),!t)gM(k,n,o);return k}class _T{Update;latestUpdateAtoms;mutableAtoms;constructor(o,n){const t=jn(n,{key:`*${o.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=u(t,n),this.mutableAtoms=o,this.mutableAtoms.subject.subscribe(`store=${n.config.name}::tracker-atom-family`,(S)=>{if(S.token.family){const f=Uo(S.token.family.subKey);Eo(n,this.latestUpdateAtoms,f),new un(S.token,n)}}),this.latestUpdateAtoms.subject.subscribe(`store=${n.config.name}::tracker-atom-family`,(S)=>{if(S.token.family){const f=Uo(S.token.family.subKey),T=Eo(n,this.mutableAtoms,f);if(T)new un(T,n)}})}}function SS(o,n,t){const S={key:n.key,type:"mutable_atom_family"},f=o.families.get(n.key);if(f)o.logger.error("\u2757","mutable_atom_family",n.key,`Overwriting an existing ${Gn(f)} "${f.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const T=new s,F=Object.assign((k)=>{const A=l(k),$={key:n.key,subKey:A},O=`${n.key}(${A})`,w=m(o),G={key:O,default:()=>n.default(k),toJson:n.toJson,fromJson:n.fromJson,mutable:!0};if(n.effects)G.effects=n.effects(k);const r=yS(w,G,$);return T.next({type:"state_creation",token:r}),r},S,{subject:T,install:(k)=>SS(k,n),toJson:n.toJson,fromJson:n.fromJson,internalRoles:t});return o.families.set(n.key,F),QF(F,n,o),new _T(F,o),S}var MT=(o,n)=>{const t=m(n),S=`${o.key}:JSON`;return t.families.get(S)};var ho=(o,n)=>{if(n.family){const S=m(o),T={key:`${n.family.key}:JSON`,type:"selector_family"},M=u(T,S),F=JSON.parse(n.family.subKey);return Ro(o,M,F)}return{type:"selector",key:`${n.key}:JSON`}};var dn=(o)=>{const t={type:"atom",key:`*${o.key}`};if(o.family)t.family={key:`*${o.family.key}`,subKey:o.family.subKey};return t};function MF(o){return typeof o==="object"&&o!==null&&"do"in o&&"undo"in o&&"subscribe"in o}function kS(o,n,t){const S=n.valueMap.get(o.key),f=t.valueMap.get(o.key);if(S===f){if(S===void 0)return typeof o.default==="function"?o.default():o.default;n.logger.info("\uD83D\uDCC3","atom",o.key,"copying");const T=o.toJson(S),M=o.fromJson(T);return t.valueMap.set(o.key,M),new un(o,n),M}return f}function Rn(o,n,t,S){const f=S.valueMap.get(o);if(f instanceof tS)f.use(n);if(n instanceof Promise){const T=new tS(n);return S.valueMap.set(o,T),T.then((M)=>{Rn(o,M,t,S),t.next({newValue:M,oldValue:T})}).catch((M)=>{S.logger.error("\uD83D\uDCA5","state",o,"rejected:",M)}),T}return S.valueMap.set(o,n),n}var sM=(o,n)=>{let t=n.valueMap.get(o.key);if(o.type==="mutable_atom"&&Fo(n)){const{parent:S}=n;t=kS(o,S,n)}return t},fF=(o,n)=>{const t=n.valueMap.get(o);if(t instanceof tS){const S=t,f=n.selectors.get(o)??n.readonlySelectors.get(o);if(f)S.use(f.get());return}if(n.operation.open)n.operation.prev.set(o,t);n.valueMap.delete(o),n.logger.info("\uD83D\uDDD1","state",o,"evicted")};var kF=(o,n)=>{return m(n).atomsThatAreDefault.has(o)},Tf=(o,n)=>{const t=m(n);t.atomsThatAreDefault=new Set(t.atomsThatAreDefault).add(o)},AF=(o,n)=>{const t=m(n);t.atomsThatAreDefault=new Set(m(n).atomsThatAreDefault),t.atomsThatAreDefault.delete(o)};function nn(o,n,t){o.logger.info("\uD83D\uDD28","atom",n.key,`creating in store "${o.config.name}"`);const S=m(o),f=S.atoms.get(n.key);if(f&&f.type==="atom")return o.logger.error("\u274C","atom",n.key,"Tried to create atom, but it already exists in the store."),Po(f);const T=new s,M={...n,type:"atom",install:(A)=>{return A.logger.info("\uD83D\uDEE0\uFE0F","atom",n.key,`installing in store "${A.config.name}"`),nn(A,n,t)},subject:T};if(t)M.family=t;let F=n.default;if(n.default instanceof Function)F=n.default();S.atoms.set(M.key,M),Tf(n.key,o),Rn(n.key,F,T,S);const k=Po(M);if(n.effects){let A=0;const $=[];for(let O of n.effects){const w=O({setSelf:(G)=>{Co(o,k,G)},onSet:(G)=>kn(k,G,`effect[${A}]`,o)});if(w)$.push(w);++A}M.cleanup=()=>{for(let O of $)O()}}return k}function dM(o,n){if("mutable"in n){const f=yS(o,n,void 0);return o.on.atomCreation.next(f),f}const S=nn(o,n,void 0);return o.on.atomCreation.next(S),S}function yT(o,n){const t=m(n),{key:S}=o,f=u(o,t);if(!f.family)n.logger.error("\u274C","atom",S,"Standalone atoms cannot be disposed.");else{f.cleanup?.();const T=n.valueMap.get(f.key);u({key:f.family.key,type:"atom_family"},n).subject.next({type:"state_disposal",token:o,value:T});const F=t.molecules.get(f.family.subKey);if(F)F.tokens.delete(S);if(t.atoms.delete(S),t.valueMap.delete(S),t.selectorAtoms.delete(S),t.atomsThatAreDefault.delete(S),n.timelineTopics.delete(S),o.type==="mutable_atom"){const k=dn(o);yT(k,n),n.trackers.delete(S)}if(n.logger.info("\uD83D\uDD25","atom",S,"deleted"),Fo(t)&&t.transactionMeta.phase==="building")t.transactionMeta.update.updates.push({type:"state_disposal",token:o});else n.on.atomDisposal.next(o)}}var wT=(o)=>{const n=nn(o,{key:"\uD83D\uDD0D Atom Token Index (Internal)",default:()=>{const t=new Map;for(let[S,f]of o.atoms)if(!S.includes("\uD83D\uDD0D")){const T=Po(f);if(f.family){let M=t.get(f.family.key);if(!M||!("familyMembers"in M))M={key:f.family.key,familyMembers:new Map},t.set(f.family.key,M);M.familyMembers.set(f.family.subKey,T)}else t.set(S,T)}return t},effects:[({setSelf:t})=>{o.on.atomCreation.subscribe("introspection",(S)=>{if(S.key.includes("\uD83D\uDD0D"))return;t((f)=>{if(S.family){const{key:T,subKey:M}=S.family;let F=f.get(T);if(F===void 0||!("familyMembers"in F))F={key:T,familyMembers:new Map},f.set(T,F);F.familyMembers.set(M,S)}else f.set(S.key,S);return f})}),o.on.atomDisposal.subscribe("introspection",(S)=>{t((f)=>{if(S.family){const{key:T,subKey:M}=S.family,F=f.get(T);if(F&&"familyMembers"in F){if(F.familyMembers.delete(M),F.familyMembers.size===0)f.delete(T)}}else f.delete(S.key);return f})})}]},void 0);return En(o,{key:"\uD83D\uDD0D Atom Token Index",get:({get:t})=>t(n)})};var KT=(o)=>{const n=nn(o,{key:"\uD83D\uDD0D Selector Token Index (Internal)",default:()=>{const t=new Map;for(let S of[o.readonlySelectors,o.selectors])for(let[f,T]of S)if(!f.includes("\uD83D\uDD0D")){const M=Po(T);if(T.family){let F=t.get(T.family.key);if(!F||!("familyMembers"in F))F={key:T.family.key,familyMembers:new Map},t.set(T.family.key,F);F.familyMembers.set(T.family.subKey,M)}else t.set(f,M)}return t},effects:[({setSelf:t})=>{o.on.selectorCreation.subscribe("introspection",(S)=>{if(S.key.includes("\uD83D\uDD0D"))return;t((f)=>{if(S.family){const{key:T,subKey:M}=S.family;let F=f.get(T);if(F===void 0||!("familyMembers"in F))F={key:T,familyMembers:new Map},f.set(T,F);F.familyMembers.set(M,S)}else f.set(S.key,S);return f})}),o.on.selectorDisposal.subscribe("introspection",(S)=>{t((f)=>{if(S.family){const{key:T,subKey:M}=S.family,F=f.get(T);if(F&&"familyMembers"in F){if(F.familyMembers.delete(M),F.familyMembers.size===0)f.delete(T)}}else f.delete(S.key);return f})})}]},void 0);return En(o,{key:"\uD83D\uDD0D Selector Token Index",get:({get:t})=>t(n)})};function YT(o){if(!o)return!1;return Object.getPrototypeOf(o)===Object.prototype}class Mf{supported;constructor(o){this.supported=o}refine(o){for(let[n,t]of Object.entries(this.supported))try{if(t(o)===!0&&t!==Boolean)return{type:n,data:o}}catch(S){try{if(o instanceof t)return{type:n,data:o}}catch(f){}}return null}}var XT=new Mf({number:(o)=>typeof o==="number",string:(o)=>typeof o==="string",boolean:(o)=>typeof o==="boolean",null:(o)=>o===null}),ET=new Mf({object:YT,array:(o)=>Array.isArray(o)}),_y=new Mf({...XT.supported,...ET.supported}),Ut=(o)=>{if(o===void 0)return"undefined";const n=_y.refine(o);if(n)return n.type;return Object.getPrototypeOf(o).constructor.name};class UF{o;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(o=ko.STORE){this.store=o;this.atomIndex=wT(this.store),this.selectorIndex=KT(this.store),this.unsubscribeFromAtomCreation=this.store.on.atomCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:n})=>{this.statesCreatedAt.set(n,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromAtomDisposal=this.store.on.atomDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:n})=>{this.statesCreatedAt.delete(n)}),this.unsubscribeFromSelectorCreation=this.store.on.selectorCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:n})=>{this.statesCreatedAt.set(n,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromSelectorDisposal=this.store.on.selectorDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:n})=>{this.statesCreatedAt.delete(n)})}static DEFAULT_LIST_RESOURCES_PARAM={atomFamilies:!0,selectorFamilies:!0};listResources(o=UF.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");const n=sf(this.atomIndex),t=sf(this.selectorIndex),S=[...n.values()].filter((F)=>("familyMembers"in F)),f=[...t.values()].filter((F)=>("familyMembers"in F)),T=performance.now(),M=[];if(o.atomFamilies)for(let F of S){const k=F.familyMembers.values();for(let A of k){const O=this.statesCreatedAt.get(A.key)??this.auditorCreatedAt,w=T-O;M.push([A,w])}}if(o.selectorFamilies)for(let F of f){const k=F.familyMembers.values();for(let A of k){const O=this.statesCreatedAt.get(A.key)??this.auditorCreatedAt,w=T-O;M.push([A,w])}}return M}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}}var GT=(o,n)=>{const t=(S,f)=>{const M=((k,A)=>{const $=n(k,A);if($)return $;return null})(S,f);if(M?.jobComplete??M?.pathComplete)return M;const F=Array.isArray(f)?f.map((k,A)=>[A,k]):YT(f)?Object.entries(f):[];for(let[k,A]of F){const $=t([...S,k],A);if($?.jobComplete)return $}return{}};t([],o)};function wy(o,n){return{summary:`${o<n?"+":"-"}${Math.abs(o-n)} (${o} \u2192 ${n})`}}function Ky(o,n){return{summary:`${o.length<n.length?"+":"-"}${Math.abs(o.length-n.length)} ("${o}" \u2192 "${n}")`}}function Xy(o,n){return{summary:`${o} \u2192 ${n}`}}function VF(o,n,t){let S="";const f=[],T=[],M=[];return GT(o,(F,k)=>{let A;for(A of F){const $=n[A];if($===void 0)T.push([A,JSON.stringify(k)]);else{const O=t(k,$);if(O.summary!=="No Change")M.push([A,O])}}}),GT(n,(F,k)=>{let A;for(A of F)if(o[A]===void 0)f.push([A,JSON.stringify(k)])}),S=`\uFF5E${M.length} \uFF0B${f.length} \uFF0D${T.length}`,{summary:S,added:f,removed:T,changed:M}}function Yy(o,n,t){return VF(o,n,t)}class rF{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(o,n,t){this.leafRefinery=o,this.treeRefinery=n,this.leafDiffers={},this.treeDiffers={};for(let S of Object.keys(o.supported)){const f=t[S];this.leafDiffers[S]=f}for(let S of Object.keys(n.supported)){const f=t[S];this.treeDiffers[S]=f}}diff(o,n){if(o===n)return{summary:"No Change"};const t=this.leafRefinery.refine(o)??this.treeRefinery.refine(o),S=this.leafRefinery.refine(n)??this.treeRefinery.refine(n);if(t!==null&&S!==null){if(t.type===S.type){if(t.type in this.leafDiffers)return this.leafDiffers[t.type](t.data,S.data);if(t.type in this.treeDiffers)return this.treeDiffers[t.type](t.data,S.data,(F,k)=>this.diff(F,k))}}const f=Ut(o),T=Ut(n);if(f===T)return{summary:`${f} \u2192 ${T}`};return{summary:`Type change: ${f} \u2192 ${T}`}}}var iX=new rF(XT,ET,{number:wy,string:Ky,boolean:Xy,null:()=>({summary:"No Change"}),object:VF,array:Yy});class Vt{o;listeners;globalListeners;handleEvent(o,...n){for(let S of this.globalListeners)S(o,...n);const t=this.listeners.get(o);if(t)for(let S of t)S(...n)}id="no_id_retrieved";constructor(o){this.emit=o;this.listeners=new Map,this.globalListeners=new Set}on(o,n){const t=this.listeners.get(o);if(t)t.add(n);else this.listeners.set(o,new Set([n]));return this}onAny(o){return this.globalListeners.add(o),this}off(o,n){const t=this.listeners.get(o);if(t)if(n)t.delete(n);else this.listeners.delete(o);return this}offAny(o){return this.globalListeners.delete(o),this}}class zT extends Vt{o;n;t;incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";handleLog(o){if(Array.isArray(o)){const[n,...t]=o;switch(n){case"i":this.logger.info(this.id,this.key,...t);break;case"w":this.logger.warn(this.id,this.key,...t);break;case"e":this.logger.error(this.id,this.key,...t);break}}}constructor(o,n,t=console){super((S,...f)=>{const T=JSON.stringify([S,...f])+"\x03",M=(F)=>{if(F.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",M)};return this.process.stdin.once("error",M),this.process.stdin.write(T),this});this.process=o;this.key=n;this.logger=t;if(this.process=o,this.process.stdout.on("data",(S)=>{const f=S.toString();if(f==="\u2728")return;this.unprocessedEvents.push(...f.split("\x03"));const T=this.unprocessedEvents.shift();this.incompleteData+=T??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let M=Uo(this.incompleteData);this.handleEvent(...M);while(this.unprocessedEvents.length>0){const F=this.unprocessedEvents.shift();if(F){if(this.unprocessedEvents.length===0)this.incompleteData=F;M=Uo(F),this.handleEvent(...M)}}this.incompleteData=""}catch(M){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error(M)}}),this.process.stderr.on("data",(S)=>{const f=S.toString();this.unprocessedLogs.push(...f.split("\x03"));const T=this.unprocessedLogs.shift();this.incompleteLog+=T??"";try{let M=Uo(this.incompleteLog);this.handleLog(M);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)M=Uo(this.incompleteLog),this.handleLog(M)}catch(M){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error(M),console.error("\u274C\u274C\u274C\uFE0F")}}),o.pid)this.id=o.pid.toString()}}class CF extends Vt{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(o){super((...n)=>{return this.out.next(n),this});this.id=o,this.in=new s,this.out=new s,this.in.subscribe("socket",(n)=>{this.handleEvent(...n)})}dispose(){for(let o of this.disposalFunctions)o()}}class HT extends Vt{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...o){this.process.stderr.write(l(o.map((n)=>n instanceof Bo?`{ ${n.toJSON().members.join(" | ")} }`:n))+"\x03")}logger={info:(...o)=>{this.log("i",...o)},warn:(...o)=>{this.log("w",...o)},error:(...o)=>{this.log("e",...o)}};constructor(){super((o,...n)=>{const t=JSON.stringify([o,...n]);return this.process.stdout.write(t+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(o)=>{const n=o.toString();this.unprocessedEvents.push(...n.split("\x03"));const t=this.unprocessedEvents.shift();this.incompleteData+=t??"";try{const S=Uo(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",S),this.handleEvent(...S);while(this.unprocessedEvents.length>0){const f=this.unprocessedEvents.shift();if(f){if(this.unprocessedEvents.length===0)this.incompleteData=f;const T=Uo(f);this.handleEvent(...T)}}this.incompleteData=""}catch(S){if(S instanceof Error)this.logger.error("\u2757",S.message,S.cause,S.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(o)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${o}`)}),process.on("end",()=>{this.logger.info("\uD83D\uDD25",this.id,"ended"),process.exit(0)}),process.on("SIGTERM",()=>{this.logger.error("\uD83D\uDD25",this.id,"terminated"),process.exit(0)}),process.on("SIGINT",()=>{this.logger.error("\uD83D\uDD25",this.id,"interrupted"),process.exit(0)}),process.pid)this.id=process.pid?.toString();this.on("user-joins",(o)=>{this.logger.info("\uD83D\uDC64","user",o,"joined");const n=new CF(`user:${o}`);this.relays.set(o,n),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let t of this.relayServices){const S=t(n);if(S)n.disposalFunctions.push(S)}this.on(`user:${o}`,(...t)=>{n.in.next(t)}),n.out.subscribe("socket",(t)=>{this.emit(...t)})}),this.on("user-leaves",(o)=>{const n=this.relays.get(o);if(this.off(`relay:${o}`),n)n.dispose(),this.relays.delete(o)}),process.stdout.write("\u2728")}relay(o){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(o)}}class LF extends Map{set(o,n){if(this.has(o))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:o,value:n}),this;return super.set(o,n)}clear(){throw new Error("Cannot clear an InvariantMap")}}class mT{o;type="continuity";globals=[];actions=[];perspectives=[];constructor(o){this.key=o}static existing=new LF;static create(o,n){const t=new mT(o),{type:S,globals:f,actions:T,perspectives:M}=n(t),F={type:S,key:o,globals:f,actions:T,perspectives:M};return mT.existing.set(o,F),F}add(...o){switch(o[0].type){case"atom":case"mutable_atom":this.globals.push(...o);break;case"transaction":this.actions.push(...o);break;case"atom_family":{const[t,S]=o;this.perspectives.push({type:"realtime_perspective",resourceAtoms:t,viewAtoms:S})}break}return this}}var K8=mt({key:"usersInRoomIndex",mutable:!0,default:()=>new Bo,toJson:(o)=>o.toJSON(),fromJson:(o)=>Bo.fromJSON(o)}),QT=mt({key:"roomIndex",default:()=>new Bo,mutable:!0,toJson:(o)=>o.toJSON(),fromJson:(o)=>Bo.fromJSON(o)}),Ey={enteredAtEpoch:0},RS=dS({key:"usersInRooms",between:["room","user"],cardinality:"1:n"},Ey),X8=ZS({key:"usersInMyRoomView",get:(o)=>({find:n})=>{const t=OF(RS);return[n(t,o)]}});import{spawn as Gy}from"child_process";var DT=kt({key:"roomArguments",default:["echo",["Hello World!"]]}),IF=ZS({key:"room",get:(o)=>async({get:n,find:t})=>{const S=t(DT,o),f=n(S),[T,M]=f,F=await new Promise((k)=>{const A=Gy(T,M,{env:process.env}),$=(O)=>{if(O.toString()==="\u2728")A.stdout.off("data",$),k(A)};A.stdout.on("data",$)});return new zT(F,o)}});var I8=FS({key:"createRoom",do:({get:o,set:n,find:t},S,f,T)=>{const M=T?[f,T]:[f],F=t(DT,S);n(F,M),n(QT,($)=>$.add(S));const k=t(IF,S);return o(k)}}),j8=FS({key:"joinRoom",do:(o,n,t,S)=>{const f={enteredAtEpoch:S};return uS(RS,(T)=>{T.set({room:n,user:t},f)},o.env().store),f}}),B8=FS({key:"leaveRoom",do:(o,n,t)=>{uS(RS,(S)=>{S.delete({room:n,user:t})},o.env().store)}}),c8=FS({key:"destroyRoom",do:(o,n)=>{uS(RS,(t)=>{t.delete({room:n})},o.env().store),o.set(QT,(t)=>(t.delete(n),t))}});var h8=kt({key:"transactionRedactor",default:{occlude:(o)=>o}}),zy=kt({key:"unacknowledgedUpdates",default:()=>[]});var Hy=kt({key:"sockets",default:null}),p8=mt({key:"socketsIndex",mutable:!0,default:()=>new Bo,toJson:(o)=>o.toJSON(),fromJson:(o)=>Bo.fromJSON(o)}),Z8=mt({key:"usersIndex",mutable:!0,default:()=>new Bo,toJson:(o)=>o.toJSON(),fromJson:(o)=>Bo.fromJSON(o)}),my=dS({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1"});var{file:yJ,serve:r0}=globalThis.Bun;function X(o,n){if(!o||typeof o!=="object")return!1;if(o instanceof n)return!0;if(!Object.prototype.hasOwnProperty.call(n,y))throw new Error(`Class "${n.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 t=Object.getPrototypeOf(o).constructor;if(t)while(t){if(y in t&&t[y]===n[y])return!0;t=Object.getPrototypeOf(t)}return!1}var y=Symbol.for("drizzle:entityKind"),Q5=Symbol.for("drizzle:hasOwnEntityKind");class Ko{constructor(o,n){this.table=o,this.config=n,this.name=n.name,this.keyAsName=n.keyAsName,this.notNull=n.notNull,this.default=n.default,this.defaultFn=n.defaultFn,this.onUpdateFn=n.onUpdateFn,this.hasDefault=n.hasDefault,this.primary=n.primaryKey,this.isUnique=n.isUnique,this.uniqueName=n.uniqueName,this.uniqueType=n.uniqueType,this.dataType=n.dataType,this.columnType=n.columnType,this.generated=n.generated,this.generatedIdentity=n.generatedIdentity}static[y]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(o){return o}mapToDriverValue(o){return o}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class UT{static[y]="ColumnBuilder";config;constructor(o,n,t){this.config={name:o,keyAsName:o==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:n,columnType:t,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(o){return this.config.default=o,this.config.hasDefault=!0,this}$defaultFn(o){return this.config.defaultFn=o,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(o){return this.config.onUpdateFn=o,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(o){if(this.config.name!=="")return;this.config.name=o}}var Hn=Symbol.for("drizzle:Name");class VT{static[y]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(o,n){if(this.reference=()=>{const{name:t,columns:S,foreignColumns:f}=o();return{name:t,columns:S,foreignTable:f[0].table,foreignColumns:f}},n)this._onUpdate=n.onUpdate,this._onDelete=n.onDelete}onUpdate(o){return this._onUpdate=o===void 0?"no action":o,this}onDelete(o){return this._onDelete=o===void 0?"no action":o,this}build(o){return new jF(o,this)}}class jF{constructor(o,n){this.table=o,this.reference=n.reference,this.onUpdate=n._onUpdate,this.onDelete=n._onDelete}static[y]="PgForeignKey";reference;onUpdate;onDelete;getName(){const{name:o,columns:n,foreignColumns:t}=this.reference(),S=n.map((M)=>M.name),f=t.map((M)=>M.name),T=[this.table[Hn],...S,t[0].table[Hn],...f];return o??`${T.join("_")}_fk`}}function Ff(o,...n){return o(...n)}function BF(o,n){return`${o[Hn]}_${n.join("_")}_unique`}function cF(o,n,t){for(let S=n;S<o.length;S++){const f=o[S];if(f==="\\"){S++;continue}if(f==='"')return[o.slice(n,S).replace(/\\/g,""),S+1];if(t)continue;if(f===","||f==="}")return[o.slice(n,S).replace(/\\/g,""),S]}return[o.slice(n).replace(/\\/g,""),o.length]}function bF(o,n=0){const t=[];let S=n,f=!1;while(S<o.length){const T=o[S];if(T===","){if(f||S===n)t.push("");f=!0,S++;continue}if(f=!1,T==="\\"){S+=2;continue}if(T==='"'){const[k,A]=cF(o,S+1,!0);t.push(k),S=A;continue}if(T==="}")return[t,S+1];if(T==="{"){const[k,A]=bF(o,S+1);t.push(k),S=A;continue}const[M,F]=cF(o,S,!1);t.push(M),S=F}return[t,S]}function NF(o){const[n]=bF(o,1);return n}function rT(o){return`{${o.map((n)=>{if(Array.isArray(n))return rT(n);if(typeof n==="string")return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`;return`${n}`}).join(",")}}`}class c extends UT{foreignKeyConfigs=[];static[y]="PgColumnBuilder";array(o){return new xF(this.config.name,this,o)}references(o,n={}){return this.foreignKeyConfigs.push({ref:o,actions:n}),this}unique(o,n){return this.config.isUnique=!0,this.config.uniqueName=o,this.config.uniqueType=n?.nulls,this}generatedAlwaysAs(o){return this.config.generated={as:o,type:"always",mode:"stored"},this}buildForeignKeys(o,n){return this.foreignKeyConfigs.map(({ref:t,actions:S})=>{return Ff((f,T)=>{const M=new VT(()=>{const F=f();return{columns:[o],foreignColumns:[F]}});if(T.onUpdate)M.onUpdate(T.onUpdate);if(T.onDelete)M.onDelete(T.onDelete);return M.build(n)},t,S)})}buildExtraConfigColumn(o){return new hF(o,this.config)}}class U extends Ko{constructor(o,n){if(!n.uniqueName)n.uniqueName=BF(o,[n.name]);super(o,n);this.table=o}static[y]="PgColumn"}class hF extends U{static[y]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(o){return this.indexConfig.opClass=o,this}}class OS{static[y]="IndexedColumn";constructor(o,n,t,S){this.name=o,this.keyAsName=n,this.type=t,this.indexConfig=S}name;keyAsName;type;indexConfig}class xF extends c{static[y]="PgArrayBuilder";constructor(o,n,t){super(o,"array","PgArray");this.config.baseBuilder=n,this.config.size=t}build(o){const n=this.config.baseBuilder.build(o);return new CT(o,this.config,n)}}class CT extends U{constructor(o,n,t,S){super(o,n);this.baseColumn=t,this.range=S,this.size=n.size}size;static[y]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(o){if(typeof o==="string")o=NF(o);return o.map((n)=>this.baseColumn.mapFromDriverValue(n))}mapToDriverValue(o,n=!1){const t=o.map((S)=>S===null?null:X(this.baseColumn,CT)?this.baseColumn.mapToDriverValue(S,!0):this.baseColumn.mapToDriverValue(S));if(n)return t;return rT(t)}}function iF(o){return!!o&&typeof o==="function"&< in o&&o[LT]===!0}function kf(o,n){return Qy(o,n,void 0)}function Qy(o,n,t){const S=Object.assign((f)=>new vF(f??"",S),{enumName:o,enumValues:n,schema:t,[LT]:!0});return S}var LT=Symbol.for("drizzle:isPgEnum");class vF extends c{static[y]="PgEnumColumnBuilder";constructor(o,n){super(o,"string","PgEnumColumn");this.config.enum=n}build(o){return new qF(o,this.config)}}class qF extends U{static[y]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(o,n){super(o,n);this.enum=n.enum}getSQLType(){return this.enum.enumName}}class xo{static[y]="Subquery";constructor(o,n,t,S=!1){this._={brand:"Subquery",sql:o,selectedFields:n,alias:t,isWith:S}}}class WS extends xo{static[y]="WithSubquery"}var pF="0.35.1";var IT,jT,Oo={startActiveSpan(o,n){if(!IT)return n();if(!jT)jT=IT.trace.getTracer("drizzle-orm",pF);return Ff((t,S)=>S.startActiveSpan(o,(f)=>{try{return n(f)}catch(T){throw f.setStatus({code:t.SpanStatusCode.ERROR,message:T instanceof Error?T.message:"Unknown error"}),T}finally{f.end()}}),IT,jT)}};var mo=Symbol.for("drizzle:ViewBaseConfig");function Wn(o){return o[Hn]}function $t(o){return`${o[Af]??"public"}.${o[Hn]}`}var Af=Symbol.for("drizzle:Schema"),ZF=Symbol.for("drizzle:Columns"),PF=Symbol.for("drizzle:ExtraConfigColumns"),BT=Symbol.for("drizzle:OriginalName"),cT=Symbol.for("drizzle:BaseName"),gF=Symbol.for("drizzle:IsAlias"),lF=Symbol.for("drizzle:ExtraConfigBuilder"),Dy=Symbol.for("drizzle:IsDrizzleTable");class j{static[y]="Table";static Symbol={Name:Hn,Schema:Af,OriginalName:BT,Columns:ZF,ExtraConfigColumns:PF,BaseName:cT,IsAlias:gF,ExtraConfigBuilder:lF};[Hn];[BT];[Af];[ZF];[PF];[cT];[gF]=!1;[Dy]=!0;[lF]=void 0;constructor(o,n,t){this[Hn]=this[BT]=o,this[Af]=n,this[cT]=t}}function bT(o){return o!==null&&o!==void 0&&typeof o.getSQL==="function"}function Uy(o){const n={sql:"",params:[]};for(let t of o)if(n.sql+=t.sql,n.params.push(...t.params),t.typings?.length){if(!n.typings)n.typings=[];n.typings.push(...t.typings)}return n}function eF(o){return typeof o==="object"&&o!==null&&"mapToDriverValue"in o&&typeof o.mapToDriverValue==="function"}function R(o,...n){const t=[];if(n.length>0||o.length>0&&o[0]!=="")t.push(new co(o[0]));for(let[S,f]of n.entries())t.push(f,new co(o[S+1]));return new b(t)}function NT(o,n){return o.map((t)=>{if(X(t,an)){if(!(t.name in n))throw new Error(`No value for placeholder "${t.name}" was provided`);return n[t.name]}if(X(t,An)&&X(t.value,an)){if(!(t.value.name in n))throw new Error(`No value for placeholder "${t.value.name}" was provided`);return t.encoder.mapToDriverValue(n[t.value.name])}return t})}class co{static[y]="StringChunk";value;constructor(o){this.value=Array.isArray(o)?o:[o]}getSQL(){return new b([this])}}class b{constructor(o){this.queryChunks=o}static[y]="SQL";decoder=dF;shouldInlineParams=!1;append(o){return this.queryChunks.push(...o.queryChunks),this}toQuery(o){return Oo.startActiveSpan("drizzle.buildSQL",(n)=>{const t=this.buildQueryFromSourceParams(this.queryChunks,o);return n?.setAttributes({"drizzle.query.text":t.sql,"drizzle.query.params":JSON.stringify(t.params)}),t})}buildQueryFromSourceParams(o,n){const t=Object.assign({},n,{inlineParams:n.inlineParams||this.shouldInlineParams,paramStartIndex:n.paramStartIndex||{value:0}}),{casing:S,escapeName:f,escapeParam:T,prepareTyping:M,inlineParams:F,paramStartIndex:k}=t;return Uy(o.map((A)=>{if(X(A,co))return{sql:A.value.join(""),params:[]};if(X(A,$f))return{sql:f(A.value),params:[]};if(A===void 0)return{sql:"",params:[]};if(Array.isArray(A)){const $=[new co("(")];for(let[O,w]of A.entries())if($.push(w),O<A.length-1)$.push(new co(", "));return $.push(new co(")")),this.buildQueryFromSourceParams($,t)}if(X(A,b))return this.buildQueryFromSourceParams(A.queryChunks,{...t,inlineParams:F||A.shouldInlineParams});if(X(A,j)){const $=A[j.Symbol.Schema],O=A[j.Symbol.Name];return{sql:$===void 0?f(O):f($)+"."+f(O),params:[]}}if(X(A,Ko)){const $=S.getColumnCasing(A);if(n.invokeSource==="indexes")return{sql:f($),params:[]};return{sql:f(A.table[j.Symbol.Name])+"."+f($),params:[]}}if(X(A,Sn)){const $=A[mo].schema,O=A[mo].name;return{sql:$===void 0?f(O):f($)+"."+f(O),params:[]}}if(X(A,An)){if(X(A.value,an))return{sql:T(k.value++,A),params:[A],typings:["none"]};const $=A.value===null?null:A.encoder.mapToDriverValue(A.value);if(X($,b))return this.buildQueryFromSourceParams([$],t);if(F)return{sql:this.mapInlineParam($,t),params:[]};let O=["none"];if(M)O=[M(A.encoder)];return{sql:T(k.value++,$),params:[$],typings:O}}if(X(A,an))return{sql:T(k.value++,A),params:[A],typings:["none"]};if(X(A,b.Aliased)&&A.fieldAlias!==void 0)return{sql:f(A.fieldAlias),params:[]};if(X(A,xo)){if(A._.isWith)return{sql:f(A._.alias),params:[]};return this.buildQueryFromSourceParams([new co("("),A._.sql,new co(") "),new $f(A._.alias)],t)}if(iF(A)){if(A.schema)return{sql:f(A.schema)+"."+f(A.enumName),params:[]};return{sql:f(A.enumName),params:[]}}if(bT(A)){if(A.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([A.getSQL()],t);return this.buildQueryFromSourceParams([new co("("),A.getSQL(),new co(")")],t)}if(F)return{sql:this.mapInlineParam(A,t),params:[]};return{sql:T(k.value++,A),params:[A],typings:["none"]}}))}mapInlineParam(o,{escapeString:n}){if(o===null)return"null";if(typeof o==="number"||typeof o==="boolean")return o.toString();if(typeof o==="string")return n(o);if(typeof o==="object"){const t=o.toString();if(t==="[object Object]")return n(JSON.stringify(o));return n(t)}throw new Error("Unexpected param value: "+o)}getSQL(){return this}as(o){if(o===void 0)return this;return new b.Aliased(this,o)}mapWith(o){return this.decoder=typeof o==="function"?{mapFromDriverValue:o}:o,this}inlineParams(){return this.shouldInlineParams=!0,this}if(o){return o?this:void 0}}class $f{constructor(o){this.value=o}static[y]="Name";brand;getSQL(){return new b([this])}}var dF={mapFromDriverValue:(o)=>o},uF={mapToDriverValue:(o)=>o},OY={...dF,...uF};class An{constructor(o,n=uF){this.value=o,this.encoder=n}static[y]="Param";brand;getSQL(){return new b([this])}}((o)=>{function n(){return new b([])}o.empty=n;function t(k){return new b(k)}o.fromList=t;function S(k){return new b([new co(k)])}o.raw=S;function f(k,A){const $=[];for(let[O,w]of k.entries()){if(O>0&&A!==void 0)$.push(A);$.push(w)}return new b($)}o.join=f;function T(k){return new $f(k)}o.identifier=T;function M(k){return new an(k)}o.placeholder=M;function F(k,A){return new An(k,A)}o.param=F})(R||(R={}));((o)=>{class n{constructor(t,S){this.sql=t,this.fieldAlias=S}static[y]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new n(this.sql,this.fieldAlias)}}o.Aliased=n})(b||(b={}));class an{constructor(o){this.name=o}static[y]="Placeholder";getSQL(){return new b([this])}}class Sn{static[y]="View";[mo];constructor({name:o,schema:n,selectedFields:t,query:S}){this[mo]={name:o,originalName:o,schema:n,selectedFields:t,query:S,isExisting:!S,isAlias:!1}}getSQL(){return new b([this])}}Ko.prototype.getSQL=function(){return new b([this])};j.prototype.getSQL=function(){return new b([this])};xo.prototype.getSQL=function(){return new b([this])};function Jf(o,n){return new Proxy(o,new _S(n,!1))}function Bn(o,n){return new Proxy(o,new rt(new Proxy(o.table,new _S(n,!1))))}function hT(o,n){return new b.Aliased(wS(o.sql,n),o.fieldAlias)}function wS(o,n){return R.join(o.queryChunks.map((t)=>{if(X(t,Ko))return Bn(t,n);if(X(t,b))return wS(t,n);if(X(t,b.Aliased))return hT(t,n);return t}))}class rt{constructor(o){this.table=o}static[y]="ColumnAliasProxyHandler";get(o,n){if(n==="table")return this.table;return o[n]}}class _S{constructor(o,n){this.alias=o,this.replaceOriginalName=n}static[y]="TableAliasProxyHandler";get(o,n){if(n===j.Symbol.IsAlias)return!0;if(n===j.Symbol.Name)return this.alias;if(this.replaceOriginalName&&n===j.Symbol.OriginalName)return this.alias;if(n===mo)return{...o[mo],name:this.alias,isAlias:!0};if(n===j.Symbol.Columns){const S=o[j.Symbol.Columns];if(!S)return S;const f={};return Object.keys(S).map((T)=>{f[T]=new Proxy(S[T],new rt(new Proxy(o,this)))}),f}const t=o[n];if(X(t,Ko))return new Proxy(t,new rt(new Proxy(o,this)));return t}}class yf extends Error{static[y]="DrizzleError";constructor({message:o,cause:n}){super(o);this.name="DrizzleError",this.cause=n}}class xT extends yf{static[y]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}function fn(o,n){if(eF(n)&&!bT(o)&&!X(o,An)&&!X(o,an)&&!X(o,Ko)&&!X(o,j)&&!X(o,Sn))return new An(o,n);return o}function KS(...o){const n=o.filter((t)=>t!==void 0);if(n.length===0)return;if(n.length===1)return new b(n);return new b([new co("("),R.join(n,new co(" and ")),new co(")")])}function sF(...o){const n=o.filter((t)=>t!==void 0);if(n.length===0)return;if(n.length===1)return new b(n);return new b([new co("("),R.join(n,new co(" or ")),new co(")")])}function ok(o){return R`not ${o}`}function Tk(o,n){if(Array.isArray(n)){if(n.length===0)return R`false`;return R`${o} in ${n.map((t)=>fn(t,o))}`}return R`${o} in ${fn(n,o)}`}function Mk(o,n){if(Array.isArray(n)){if(n.length===0)return R`true`;return R`${o} not in ${n.map((t)=>fn(t,o))}`}return R`${o} not in ${fn(n,o)}`}function Fk(o){return R`${o} is null`}function kk(o){return R`${o} is not null`}function Ak(o){return R`exists ${o}`}function $k(o){return R`not exists ${o}`}function Jk(o,n,t){return R`${o} between ${fn(n,o)} and ${fn(t,o)}`}function yk(o,n,t){return R`${o} not between ${fn(n,o)} and ${fn(t,o)}`}function Rk(o,n){return R`${o} like ${n}`}function Ok(o,n){return R`${o} not like ${n}`}function Wk(o,n){return R`${o} ilike ${n}`}function _k(o,n){return R`${o} not ilike ${n}`}var Ct=(o,n)=>{return R`${o} = ${fn(n,o)}`},aF=(o,n)=>{return R`${o} <> ${fn(n,o)}`},nk=(o,n)=>{return R`${o} > ${fn(n,o)}`},tk=(o,n)=>{return R`${o} >= ${fn(n,o)}`},Sk=(o,n)=>{return R`${o} < ${fn(n,o)}`},fk=(o,n)=>{return R`${o} <= ${fn(n,o)}`};function wk(o){return R`${o} asc`}function Kk(o){return R`${o} desc`}class Xk{static[y]="ConsoleLogWriter";write(o){console.log(o)}}class iT{static[y]="DefaultLogger";writer;constructor(o){this.writer=o?.writer??new Xk}logQuery(o,n){const t=n.map((f)=>{try{return JSON.stringify(f)}catch{return String(f)}}),S=t.length?` -- params: [${t.join(", ")}]`:"";this.writer.write(`Query: ${o}${S}`)}}class vT{static[y]="NoopLogger";logQuery(){}}class ao{static[y]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(o){return this.then(void 0,o)}finally(o){return this.then((n)=>{return o?.(),n},(n)=>{throw o?.(),n})}then(o,n){return this.execute().then(o,n)}}function Yk(o,n,t){const S={},f=o.reduce((T,{path:M,field:F},k)=>{let A;if(X(F,Ko))A=F;else if(X(F,b))A=F.decoder;else A=F.sql.decoder;let $=T;for(let[O,w]of M.entries())if(O<M.length-1){if(!(w in $))$[w]={};$=$[w]}else{const G=n[k],r=$[w]=G===null?null:A.mapFromDriverValue(G);if(t&&X(F,Ko)&&M.length===2){const H=M[0];if(!(H in S))S[H]=r===null?Wn(F.table):!1;else if(typeof S[H]==="string"&&S[H]!==Wn(F.table))S[H]=!1}}return T},{});if(t&&Object.keys(S).length>0){for(let[T,M]of Object.entries(S))if(typeof M==="string"&&!t[M])f[T]=null}return f}function _n(o,n){return Object.entries(o).reduce((t,[S,f])=>{if(typeof S!=="string")return t;const T=n?[...n,S]:[S];if(X(f,Ko)||X(f,b)||X(f,b.Aliased))t.push({path:T,field:f});else if(X(f,j))t.push(..._n(f[j.Symbol.Columns],T));else t.push(..._n(f,T));return t},[])}function qT(o,n){const t=Object.keys(o),S=Object.keys(n);if(t.length!==S.length)return!1;for(let[f,T]of t.entries())if(T!==S[f])return!1;return!0}function Rf(o,n){const t=Object.entries(n).filter(([,S])=>S!==void 0).map(([S,f])=>{if(X(f,b))return[S,f];else return[S,new An(f,o[j.Symbol.Columns][S])]});if(t.length===0)throw new Error("No values to set");return Object.fromEntries(t)}function Ek(o,n){for(let t of n)for(let S of Object.getOwnPropertyNames(t.prototype)){if(S==="constructor")continue;Object.defineProperty(o.prototype,S,Object.getOwnPropertyDescriptor(t.prototype,S)||Object.create(null))}}function Gk(o){return o[j.Symbol.Columns]}function pT(o){return X(o,xo)?o._.alias:X(o,Sn)?o[mo].name:X(o,b)?void 0:o[j.Symbol.IsAlias]?o[j.Symbol.Name]:o[j.Symbol.BaseName]}function Mo(o,n){return{name:typeof o==="string"&&o.length>0?o:"",config:typeof o==="object"?o:n}}class sn extends c{static[y]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(o){if(o){const{name:n,...t}=o;this.config.generatedIdentity={type:"always",sequenceName:n,sequenceOptions:t}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(o){if(o){const{name:n,...t}=o;this.config.generatedIdentity={type:"byDefault",sequenceName:n,sequenceOptions:t}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}function Dk(o,n){const{name:t,config:S}=Mo(o,n);if(S.mode==="number")return new zk(t);return new mk(t)}class zk extends sn{static[y]="PgBigInt53Builder";constructor(o){super(o,"number","PgBigInt53")}build(o){return new Hk(o,this.config)}}class Hk extends U{static[y]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}}class mk extends sn{static[y]="PgBigInt64Builder";constructor(o){super(o,"bigint","PgBigInt64")}build(o){return new Qk(o,this.config)}}class Qk extends U{static[y]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(o){return BigInt(o)}}function Lk(o,n){const{name:t,config:S}=Mo(o,n);if(S.mode==="number")return new Uk(t);return new rk(t)}class Uk extends c{static[y]="PgBigSerial53Builder";constructor(o){super(o,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new Vk(o,this.config)}}class Vk extends U{static[y]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}}class rk extends c{static[y]="PgBigSerial64Builder";constructor(o){super(o,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(o){return new Ck(o,this.config)}}class Ck extends U{static[y]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(o){return BigInt(o)}}function XS(o){return new Ik(o??"")}class Ik extends c{static[y]="PgBooleanBuilder";constructor(o){super(o,"boolean","PgBoolean")}build(o){return new jk(o,this.config)}}class jk extends U{static[y]="PgBoolean";getSQLType(){return"boolean"}}function bk(o,n={}){const{name:t,config:S}=Mo(o,n);return new Bk(t,S)}class Bk extends c{static[y]="PgCharBuilder";constructor(o,n){super(o,"string","PgChar");this.config.length=n.length,this.config.enumValues=n.enum}build(o){return new ck(o,this.config)}}class ck extends U{static[y]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function xk(o){return new Nk(o??"")}class Nk extends c{static[y]="PgCidrBuilder";constructor(o){super(o,"string","PgCidr")}build(o){return new hk(o,this.config)}}class hk extends U{static[y]="PgCidr";getSQLType(){return"cidr"}}function qk(o){return(n,t)=>{const{name:S,config:f}=Mo(n,t);return new ik(S,f,o)}}class ik extends c{static[y]="PgCustomColumnBuilder";constructor(o,n,t){super(o,"custom","PgCustomColumn");this.config.fieldConfig=n,this.config.customTypeParams=t}build(o){return new vk(o,this.config)}}class vk extends U{static[y]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(o,n){super(o,n);this.sqlName=n.customTypeParams.dataType(n.fieldConfig),this.mapTo=n.customTypeParams.toDriver,this.mapFrom=n.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(o){return typeof this.mapFrom==="function"?this.mapFrom(o):o}mapToDriverValue(o){return typeof this.mapTo==="function"?this.mapTo(o):o}}class qn extends c{static[y]="PgDateColumnBaseBuilder";defaultNow(){return this.default(R`now()`)}}function Pk(o,n){const{name:t,config:S}=Mo(o,n);if(S?.mode==="date")return new pk(t);return new Zk(t)}class pk extends qn{static[y]="PgDateBuilder";constructor(o){super(o,"date","PgDate")}build(o){return new Of(o,this.config)}}class Of extends U{static[y]="PgDate";getSQLType(){return"date"}mapFromDriverValue(o){return new Date(o)}mapToDriverValue(o){return o.toISOString()}}class Zk extends qn{static[y]="PgDateStringBuilder";constructor(o){super(o,"string","PgDateString")}build(o){return new Wf(o,this.config)}}class Wf extends U{static[y]="PgDateString";getSQLType(){return"date"}}function ek(o){return new gk(o??"")}class gk extends c{static[y]="PgDoublePrecisionBuilder";constructor(o){super(o,"number","PgDoublePrecision")}build(o){return new lk(o,this.config)}}class lk extends U{static[y]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseFloat(o);return o}}function ak(o){return new dk(o??"")}class dk extends c{static[y]="PgInetBuilder";constructor(o){super(o,"string","PgInet")}build(o){return new uk(o,this.config)}}class uk extends U{static[y]="PgInet";getSQLType(){return"inet"}}function _f(o){return new sk(o??"")}class sk extends sn{static[y]="PgIntegerBuilder";constructor(o){super(o,"number","PgInteger")}build(o){return new oA(o,this.config)}}class oA extends U{static[y]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseInt(o);return o}}function SA(o,n={}){const{name:t,config:S}=Mo(o,n);return new nA(t,S)}class nA extends c{static[y]="PgIntervalBuilder";constructor(o,n){super(o,"string","PgInterval");this.config.intervalConfig=n}build(o){return new tA(o,this.config)}}class tA extends U{static[y]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){const o=this.fields?` ${this.fields}`:"",n=this.precision?`(${this.precision})`:"";return`interval${o}${n}`}}function TA(o){return new fA(o??"")}class fA extends c{static[y]="PgJsonBuilder";constructor(o){super(o,"json","PgJson")}build(o){return new wf(o,this.config)}}class wf extends U{static[y]="PgJson";constructor(o,n){super(o,n)}getSQLType(){return"json"}mapToDriverValue(o){return JSON.stringify(o)}mapFromDriverValue(o){if(typeof o==="string")try{return JSON.parse(o)}catch{return o}return o}}function FA(o){return new MA(o??"")}class MA extends c{static[y]="PgJsonbBuilder";constructor(o){super(o,"json","PgJsonb")}build(o){return new Kf(o,this.config)}}class Kf extends U{static[y]="PgJsonb";constructor(o,n){super(o,n)}getSQLType(){return"jsonb"}mapToDriverValue(o){return JSON.stringify(o)}mapFromDriverValue(o){if(typeof o==="string")try{return JSON.parse(o)}catch{return o}return o}}function yA(o,n){const{name:t,config:S}=Mo(o,n);if(!S?.mode||S.mode==="tuple")return new kA(t);return new $A(t)}class kA extends c{static[y]="PgLineBuilder";constructor(o){super(o,"array","PgLine")}build(o){return new AA(o,this.config)}}class AA extends U{static[y]="PgLine";getSQLType(){return"line"}mapFromDriverValue(o){const[n,t,S]=o.slice(1,-1).split(",");return[Number.parseFloat(n),Number.parseFloat(t),Number.parseFloat(S)]}mapToDriverValue(o){return`{${o[0]},${o[1]},${o[2]}}`}}class $A extends c{static[y]="PgLineABCBuilder";constructor(o){super(o,"json","PgLineABC")}build(o){return new JA(o,this.config)}}class JA extends U{static[y]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(o){const[n,t,S]=o.slice(1,-1).split(",");return{a:Number.parseFloat(n),b:Number.parseFloat(t),c:Number.parseFloat(S)}}mapToDriverValue(o){return`{${o.a},${o.b},${o.c}}`}}function WA(o){return new RA(o??"")}class RA extends c{static[y]="PgMacaddrBuilder";constructor(o){super(o,"string","PgMacaddr")}build(o){return new OA(o,this.config)}}class OA extends U{static[y]="PgMacaddr";getSQLType(){return"macaddr"}}function KA(o){return new _A(o??"")}class _A extends c{static[y]="PgMacaddr8Builder";constructor(o){super(o,"string","PgMacaddr8")}build(o){return new wA(o,this.config)}}class wA extends U{static[y]="PgMacaddr8";getSQLType(){return"macaddr8"}}function YA(o,n){const{name:t,config:S}=Mo(o,n);return new XA(t,S?.precision,S?.scale)}class XA extends c{static[y]="PgNumericBuilder";constructor(o,n,t){super(o,"string","PgNumeric");this.config.precision=n,this.config.scale=t}build(o){return new Xf(o,this.config)}}class Xf extends U{static[y]="PgNumeric";precision;scale;constructor(o,n){super(o,n);this.precision=n.precision,this.scale=n.scale}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 mA(o,n){const{name:t,config:S}=Mo(o,n);if(!S?.mode||S.mode==="tuple")return new EA(t);return new zA(t)}class EA extends c{static[y]="PgPointTupleBuilder";constructor(o){super(o,"array","PgPointTuple")}build(o){return new GA(o,this.config)}}class GA extends U{static[y]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(o){if(typeof o==="string"){const[n,t]=o.slice(1,-1).split(",");return[Number.parseFloat(n),Number.parseFloat(t)]}return[o.x,o.y]}mapToDriverValue(o){return`(${o[0]},${o[1]})`}}class zA extends c{static[y]="PgPointObjectBuilder";constructor(o){super(o,"json","PgPointObject")}build(o){return new HA(o,this.config)}}class HA extends U{static[y]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(o){if(typeof o==="string"){const[n,t]=o.slice(1,-1).split(",");return{x:Number.parseFloat(n),y:Number.parseFloat(t)}}return o}mapToDriverValue(o){return`(${o.x},${o.y})`}}function Vy(o){const n=[];for(let t=0;t<o.length;t+=2)n.push(Number.parseInt(o.slice(t,t+2),16));return new Uint8Array(n)}function QA(o,n){const t=new ArrayBuffer(8),S=new DataView(t);for(let f=0;f<8;f++)S.setUint8(f,o[n+f]);return S.getFloat64(0,!0)}function ZT(o){const n=Vy(o);let t=0;const S=n[t];t+=1;const f=new DataView(n.buffer),T=f.getUint32(t,S===1);t+=4;let M;if(T&536870912)M=f.getUint32(t,S===1),t+=4;if((T&65535)===1){const F=QA(n,t);t+=8;const k=QA(n,t);return t+=8,[F,k]}throw new Error("Unsupported geometry type")}function CA(o,n){const{name:t,config:S}=Mo(o,n);if(!S?.mode||S.mode==="tuple")return new DA(t);return new VA(t)}class DA extends c{static[y]="PgGeometryBuilder";constructor(o){super(o,"array","PgGeometry")}build(o){return new UA(o,this.config)}}class UA extends U{static[y]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(o){return ZT(o)}mapToDriverValue(o){return`point(${o[0]} ${o[1]})`}}class VA extends c{static[y]="PgGeometryObjectBuilder";constructor(o){super(o,"json","PgGeometryObject")}build(o){return new rA(o,this.config)}}class rA extends U{static[y]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(o){const n=ZT(o);return{x:n[0],y:n[1]}}mapToDriverValue(o){return`point(${o.x} ${o.y})`}}function jA(o){return new LA(o??"")}class LA extends c{static[y]="PgRealBuilder";constructor(o,n){super(o,"number","PgReal");this.config.length=n}build(o){return new IA(o,this.config)}}class IA extends U{static[y]="PgReal";constructor(o,n){super(o,n)}getSQLType(){return"real"}mapFromDriverValue=(o)=>{if(typeof o==="string")return Number.parseFloat(o);return o}}function bA(o){return new BA(o??"")}class BA extends c{static[y]="PgSerialBuilder";constructor(o){super(o,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new cA(o,this.config)}}class cA extends U{static[y]="PgSerial";getSQLType(){return"serial"}}function xA(o){return new NA(o??"")}class NA extends sn{static[y]="PgSmallIntBuilder";constructor(o){super(o,"number","PgSmallInt")}build(o){return new hA(o,this.config)}}class hA extends U{static[y]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(o)=>{if(typeof o==="string")return Number(o);return o}}function qA(o){return new iA(o??"")}class iA extends c{static[y]="PgSmallSerialBuilder";constructor(o){super(o,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new vA(o,this.config)}}class vA extends U{static[y]="PgSmallSerial";getSQLType(){return"smallserial"}}function PA(o,n={}){const{name:t,config:S}=Mo(o,n);return new pA(t,S)}class pA extends c{static[y]="PgTextBuilder";constructor(o,n){super(o,"string","PgText");this.config.enumValues=n.enum}build(o){return new ZA(o,this.config)}}class ZA extends U{static[y]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function lA(o,n={}){const{name:t,config:S}=Mo(o,n);return new gA(t,S.withTimezone??!1,S.precision)}class gA extends qn{constructor(o,n,t){super(o,"string","PgTime");this.withTimezone=n,this.precision=t,this.config.withTimezone=n,this.config.precision=t}static[y]="PgTimeBuilder";build(o){return new Yf(o,this.config)}}class Yf extends U{static[y]="PgTime";withTimezone;precision;constructor(o,n){super(o,n);this.withTimezone=n.withTimezone,this.precision=n.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function mn(o,n={}){const{name:t,config:S}=Mo(o,n);if(S?.mode==="string")return new dA(t,S.withTimezone??!1,S.precision);return new eA(t,S?.withTimezone??!1,S?.precision)}class eA extends qn{static[y]="PgTimestampBuilder";constructor(o,n,t){super(o,"date","PgTimestamp");this.config.withTimezone=n,this.config.precision=t}build(o){return new Ef(o,this.config)}}class Ef extends U{static[y]="PgTimestamp";withTimezone;precision;constructor(o,n){super(o,n);this.withTimezone=n.withTimezone,this.precision=n.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(o)=>{return new Date(this.withTimezone?o:o+"+0000")};mapToDriverValue=(o)=>{return o.toISOString()}}class dA extends qn{static[y]="PgTimestampStringBuilder";constructor(o,n,t){super(o,"string","PgTimestampString");this.config.withTimezone=n,this.config.precision=t}build(o){return new Gf(o,this.config)}}class Gf extends U{static[y]="PgTimestampString";withTimezone;precision;constructor(o,n){super(o,n);this.withTimezone=n.withTimezone,this.precision=n.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function $n(o){return new uA(o??"")}class uA extends c{static[y]="PgUUIDBuilder";constructor(o){super(o,"string","PgUUID")}defaultRandom(){return this.default(R`gen_random_uuid()`)}build(o){return new zf(o,this.config)}}class zf extends U{static[y]="PgUUID";getSQLType(){return"uuid"}}function io(o,n={}){const{name:t,config:S}=Mo(o,n);return new aA(t,S)}class aA extends c{static[y]="PgVarcharBuilder";constructor(o,n){super(o,"string","PgVarchar");this.config.length=n.length,this.config.enumValues=n.enum}build(o){return new sA(o,this.config)}}class sA extends U{static[y]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function t$(o,n){const{name:t,config:S}=Mo(o,n);return new o$(t,S)}class o$ extends c{static[y]="PgBinaryVectorBuilder";constructor(o,n){super(o,"string","PgBinaryVector");this.config.dimensions=n.dimensions}build(o){return new n$(o,this.config)}}class n$ extends U{static[y]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function T$(o,n){const{name:t,config:S}=Mo(o,n);return new S$(t,S)}class S$ extends c{static[y]="PgHalfVectorBuilder";constructor(o,n){super(o,"array","PgHalfVector");this.config.dimensions=n.dimensions}build(o){return new f$(o,this.config)}}class f$ extends U{static[y]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(o){return JSON.stringify(o)}mapFromDriverValue(o){return o.slice(1,-1).split(",").map((n)=>Number.parseFloat(n))}}function k$(o,n){const{name:t,config:S}=Mo(o,n);return new M$(t,S)}class M$ extends c{static[y]="PgSparseVectorBuilder";constructor(o,n){super(o,"string","PgSparseVector");this.config.dimensions=n.dimensions}build(o){return new F$(o,this.config)}}class F$ extends U{static[y]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function J$(o,n){const{name:t,config:S}=Mo(o,n);return new A$(t,S)}class A$ extends c{static[y]="PgVectorBuilder";constructor(o,n){super(o,"array","PgVector");this.config.dimensions=n.dimensions}build(o){return new $$(o,this.config)}}class $$ extends U{static[y]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(o){return JSON.stringify(o)}mapFromDriverValue(o){return o.slice(1,-1).split(",").map((n)=>Number.parseFloat(n))}}function y$(){return{bigint:Dk,bigserial:Lk,boolean:XS,char:bk,cidr:xk,customType:qk,date:Pk,doublePrecision:ek,inet:ak,integer:_f,interval:SA,json:TA,jsonb:FA,line:yA,macaddr:WA,macaddr8:KA,numeric:YA,point:mA,geometry:CA,real:jA,serial:bA,smallint:xA,smallserial:qA,text:PA,time:lA,timestamp:mn,uuid:$n,varchar:io,bit:t$,halfvec:T$,sparsevec:k$,vector:J$}}function ry(o,n,t,S,f=o){const T=new Qn(o,S,f),M=typeof n==="function"?n(y$()):n,F=Object.fromEntries(Object.entries(M).map(([$,O])=>{const w=O;w.setName($);const G=w.build(T);return T[PT].push(...w.buildForeignKeys(G,T)),[$,G]})),k=Object.fromEntries(Object.entries(M).map(([$,O])=>{const w=O;w.setName($);const G=w.buildExtraConfigColumn(T);return[$,G]})),A=Object.assign(T,F);if(A[j.Symbol.Columns]=F,A[j.Symbol.ExtraConfigColumns]=k,t)A[Qn.Symbol.ExtraConfigBuilder]=t;return A}var PT=Symbol.for("drizzle:PgInlineForeignKeys");class Qn extends j{static[y]="PgTable";static Symbol=Object.assign({},j.Symbol,{InlineForeignKeys:PT});[PT]=[];[j.Symbol.ExtraConfigBuilder]=void 0}var ot=(o,n,t)=>{return ry(o,n,t,void 0)};function R$(...o){if(o[0].columns)return new YS(o[0].columns,o[0].name);return new YS(o)}class YS{static[y]="PgPrimaryKeyBuilder";columns;name;constructor(o,n){this.columns=o,this.name=n}build(o){return new O$(o,this.columns,this.name)}}class O${constructor(o,n,t){this.table=o,this.columns=n,this.name=t}static[y]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[Qn.Symbol.Name]}_${this.columns.map((o)=>o.name).join("_")}_pk`}}function _$(){return{and:KS,between:Jk,eq:Ct,exists:Ak,gt:nk,gte:tk,ilike:Wk,inArray:Tk,isNull:Fk,isNotNull:kk,like:Rk,lt:Sk,lte:fk,ne:aF,not:ok,notBetween:yk,notExists:$k,notLike:Ok,notIlike:_k,notInArray:Mk,or:sF,sql:R}}function w$(){return{sql:R,asc:wk,desc:Kk}}function K$(o,n){if(Object.keys(o).length===1&&"default"in o&&!X(o.default,j))o=o.default;const t={},S={},f={};for(let[T,M]of Object.entries(o))if(X(M,j)){const F=$t(M),k=S[F];t[F]=T,f[T]={tsName:T,dbName:M[j.Symbol.Name],schema:M[j.Symbol.Schema],columns:M[j.Symbol.Columns],relations:k?.relations??{},primaryKey:k?.primaryKey??[]};for(let $ of Object.values(M[j.Symbol.Columns]))if($.primary)f[T].primaryKey.push($);const A=M[j.Symbol.ExtraConfigBuilder]?.(M[j.Symbol.ExtraConfigColumns]);if(A){for(let $ of Object.values(A))if(X($,YS))f[T].primaryKey.push(...$.columns)}}else if(X(M,W$)){const F=$t(M.table),k=t[F],A=M.config(n(M.table));let $;for(let[O,w]of Object.entries(A))if(k){const G=f[k];if(G.relations[O]=w,$)G.primaryKey.push(...$)}else{if(!(F in S))S[F]={relations:{},primaryKey:$};S[F].relations[O]=w}}return{tables:f,tableNamesMap:t}}function Cy(o){return function n(t,S){return new nt(o,t,S,S?.fields.reduce((f,T)=>f&&T.notNull,!0)??!1)}}function Ly(o){return function n(t,S){return new ES(o,t,S)}}function X$(o,n,t){if(X(t,nt)&&t.config)return{fields:t.config.fields,references:t.config.references};const S=n[$t(t.referencedTable)];if(!S)throw new Error(`Table "${t.referencedTable[j.Symbol.Name]}" not found in schema`);const f=o[S];if(!f)throw new Error(`Table "${S}" not found in schema`);const T=t.sourceTable,M=n[$t(T)];if(!M)throw new Error(`Table "${T[j.Symbol.Name]}" not found in schema`);const F=[];for(let k of Object.values(f.relations))if(t.relationName&&t!==k&&k.relationName===t.relationName||!t.relationName&&k.referencedTable===t.sourceTable)F.push(k);if(F.length>1)throw t.relationName?new Error(`There are multiple relations with name "${t.relationName}" in table "${S}"`):new Error(`There are multiple relations between "${S}" and "${t.sourceTable[j.Symbol.Name]}". Please specify relation name`);if(F[0]&&X(F[0],nt)&&F[0].config)return{fields:F[0].config.references,references:F[0].config.fields};throw new Error(`There is not enough information to infer relation "${M}.${t.fieldName}"`)}function Y$(o){return{one:Cy(o),many:Ly(o)}}function Hf(o,n,t,S,f=(T)=>T){const T={};for(let[M,F]of S.entries())if(F.isJson){const k=n.relations[F.tsKey],A=t[M],$=typeof A==="string"?JSON.parse(A):A;T[F.tsKey]=X(k,nt)?$&&Hf(o,o[F.relationTableTsKey],$,F.selection,f):$.map((O)=>Hf(o,o[F.relationTableTsKey],O,F.selection,f))}else{const k=f(t[M]),A=F.field;let $;if(X(A,Ko))$=A;else if(X(A,b))$=A.decoder;else $=A.sql.decoder;T[F.tsKey]=k===null?null:$.mapFromDriverValue(k)}return T}class gT{constructor(o,n,t){this.sourceTable=o,this.referencedTable=n,this.relationName=t,this.referencedTableName=n[j.Symbol.Name]}static[y]="Relation";referencedTableName;fieldName}class W${constructor(o,n){this.table=o,this.config=n}static[y]="Relations"}class nt extends gT{constructor(o,n,t,S){super(o,n,t?.relationName);this.config=t,this.isNullable=S}static[y]="One";withFieldName(o){const n=new nt(this.sourceTable,this.referencedTable,this.config,this.isNullable);return n.fieldName=o,n}}class ES extends gT{constructor(o,n,t){super(o,n,t?.relationName);this.config=t}static[y]="Many";withFieldName(o){const n=new ES(this.sourceTable,this.referencedTable,this.config);return n.fieldName=o,n}}import Q0 from"path";import tR from"os";import SR from"fs";function Iy(o){if(mf.has(o))return mf.get(o);const n=Error.stackTraceLimit;return Error.stackTraceLimit=4,mf.set(o,new Error),Error.stackTraceLimit=n,mf.get(o)}var mf=new Map,lT=new Map,eT=Symbol("OriginError"),Lt={};class wn extends Promise{constructor(o,n,t,S,f={}){let T,M;super((F,k)=>{T=F,M=k});this.tagged=Array.isArray(o.raw),this.strings=o,this.args=n,this.handler=t,this.canceller=S,this.options=f,this.state=null,this.statement=null,this.resolve=(F)=>(this.active=!1,T(F)),this.reject=(F)=>(this.active=!1,M(F)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[eT]=this.handler.debug?new Error:this.tagged&&Iy(this.strings)}get origin(){return(this.handler.debug?this[eT].stack:this.tagged&&lT.has(this.strings)?lT.get(this.strings):lT.set(this.strings,this[eT].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(o=1,n){if(this.options.simple=!1,typeof o==="function")n=o,o=1;if(this.cursorRows=o,typeof n==="function")return this.cursorFn=n,this;let t;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};t&&t();const S=new Promise((f,T)=>{this.cursorFn=(M)=>{return f({value:M,done:!1}),new Promise((F)=>t=F)},this.resolve=()=>(this.active=!1,f({done:!0})),this.reject=(M)=>(this.active=!1,T(M))});return this.execute(),S},return(){return t&&t(Lt),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw new Error(".stream has been renamed to .forEach")}forEach(o){return this.forEachFn=o,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}}function E$(o,n,t){const{host:S,port:f}=t||n,T=Object.assign(new Error("write "+o+" "+(n.path||S+":"+f)),{code:o,errno:o,address:n.path||S},n.path?{}:{port:f});return Error.captureStackTrace(T,E$),T}function G$(o){const n=new It(o);return Error.captureStackTrace(n,G$),n}function z$(o,n){const t=Object.assign(new Error(o+": "+n),{code:o});return Error.captureStackTrace(t,z$),t}function H$(o){const n=Object.assign(new Error(o+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:o});return Error.captureStackTrace(n,H$),n}class It extends Error{constructor(o){super(o.message);this.name=this.constructor.name,Object.assign(this,o)}}var Lo={connection:E$,postgres:G$,generic:z$,notSupported:H$};function rf(o,n,t,S){let f=o instanceof cn?o.value:o;if(f===void 0){if(o instanceof cn?o.value=S.transform.undefined:f=o=S.transform.undefined,f===void 0)throw Lo.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+t.push(o instanceof cn?(n.push(o.value),o.array?o.array[o.type||Df(o.value)]||o.type||U$(o.value):o.type):(n.push(o),Df(o)))}function sT(o,n,t,S,f,T){for(let M=1;M<o.strings.length;M++)n+=oM(n,t,S,f,T)+o.strings[M],t=o.args[M];return n}function oM(o,n,t,S,f){return n instanceof Vf?n.build(o,t,S,f):n instanceof wn?aT(n,t,S,f):n instanceof mS?n.value:n&&n[0]instanceof wn?n.reduce((T,M)=>T+" "+aT(M,t,S,f),""):rf(n,t,S,f)}function aT(o,n,t,S){return o.fragment=!0,sT(o,o.strings[0],o.args[0],n,t,S)}function D$(o,n,t,S,f){return o.map((T)=>"("+S.map((M)=>oM("values",T[M],n,t,f)).join(",")+")").join(",")}function m$(o,n,t,S,f){const T=Array.isArray(o[0]),M=n.length?n.flat():Object.keys(T?o[0]:o);return D$(T?o:[o],t,S,M,f)}function Qf(o,n,t,S,f){if(typeof o==="string"&&(o=[o].concat(n)),Array.isArray(o))return nM(o,f);let T;return(n.length?n.flat():Object.keys(o)).map((F)=>{return T=o[F],(T instanceof wn?aT(T,t,S,f):T instanceof mS?T.value:rf(T,t,S,f))+" as "+Cf(f.transform.column.to?f.transform.column.to(F):F)}).join(",")}function dT(){throw Lo.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}function U$(o){if(Array.isArray(o))return U$(o[0]);return typeof o==="string"?1009:0}function r$(o){return Object.keys(o).reduce((n,t)=>{if(o[t].from&&[].concat(o[t].from).forEach((S)=>n.parsers[S]=o[t].parse),o[t].serialize)n.serializers[o[t].to]=o[t].serialize,o[t].from&&[].concat(o[t].from).forEach((S)=>n.serializers[S]=o[t].serialize);return n},{parsers:{},serializers:{}})}function nM(o,{transform:{column:n}}){return o.map((t)=>Cf(n.to?n.to(t):t)).join(",")}function xy(o){return o.replace(Ny,"\\\\").replace(hy,'\\"')}function I$(o,n,t,S){const f=[],T=S===1020?";":",";for(;o.i<n.length;o.i++){if(o.char=n[o.i],o.quoted)if(o.char==="\\")o.str+=n[++o.i];else if(o.char==='"')f.push(t?t(o.str):o.str),o.str="",o.quoted=n[o.i+1]==='"',o.last=o.i+2;else o.str+=o.char;else if(o.char==='"')o.quoted=!0;else if(o.char==="{")o.last=++o.i,f.push(I$(o,n,t,S));else if(o.char==="}"){o.quoted=!1,o.last<o.i&&f.push(t?t(n.slice(o.last,o.i)):n.slice(o.last,o.i)),o.last=o.i+1;break}else if(o.char===T&&o.p!=="}"&&o.p!=='"')f.push(t?t(n.slice(o.last,o.i)):n.slice(o.last,o.i)),o.last=o.i+1;o.p=o.char}return o.last<o.i&&f.push(t?t(n.slice(o.last,o.i+1)):n.slice(o.last,o.i+1)),f}function tM(o){return function n(t,S){return typeof t==="object"&&t!==null&&(S.type===114||S.type===3802)?Array.isArray(t)?t.map((f)=>n(f,S)):Object.entries(t).reduce((f,[T,M])=>Object.assign(f,{[o(T)]:n(M,S)}),{}):t}}var jy={string:{to:25,from:null,serialize:(o)=>""+o},number:{to:0,from:[21,23,26,700,701],serialize:(o)=>""+o,parse:(o)=>+o},json:{to:114,from:[114,3802],serialize:(o)=>JSON.stringify(o),parse:(o)=>JSON.parse(o)},boolean:{to:16,from:16,serialize:(o)=>o===!0?"t":"f",parse:(o)=>o==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(o)=>(o instanceof Date?o:new Date(o)).toISOString(),parse:(o)=>new Date(o)},bytea:{to:17,from:17,serialize:(o)=>"\\x"+Buffer.from(o).toString("hex"),parse:(o)=>Buffer.from(o.slice(2),"hex")}};class Uf{then(){dT()}catch(){dT()}finally(){dT()}}class mS extends Uf{constructor(o){super();this.value=Cf(o)}}class cn extends Uf{constructor(o,n,t){super();this.value=o,this.type=n,this.array=t}}class Vf extends Uf{constructor(o,n){super();this.first=o,this.rest=n}build(o,n,t,S){const f=By.map(([T,M])=>({fn:M,i:o.search(T)})).sort((T,M)=>T.i-M.i).pop();return f.i===-1?nM(this.first,S):f.fn(this.first,this.rest,n,t,S)}}var Q$=r$(jy),By=Object.entries({values:m$,in:(...o)=>{const n=m$(...o);return n==="()"?"(null)":n},select:Qf,as:Qf,returning:Qf,"\\(":Qf,update(o,n,t,S,f){return(n.length?n.flat():Object.keys(o)).map((T)=>Cf(f.transform.column.to?f.transform.column.to(T):T)+"="+oM("values",o[T],t,S,f))},insert(o,n,t,S,f){const T=n.length?n.flat():Object.keys(Array.isArray(o)?o[0]:o);return"("+nM(T,f)+")values"+D$(Array.isArray(o)?o:[o],t,S,T,f)}}).map(([o,n])=>[new RegExp("((?:^|[\\s(])"+o+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),n]),cy=Q$.serializers,by=Q$.parsers;var V$=function(o){const n=r$(o||{});return{serializers:Object.assign({},cy,n.serializers),parsers:Object.assign({},by,n.parsers)}},Cf=function o(n){return'"'+n.replace(/"/g,'""').replace(/\./g,'"."')+'"'},Df=function o(n){return n instanceof cn?n.type:n instanceof Date?1184:n instanceof Uint8Array?17:n===!0||n===!1?16:typeof n==="bigint"?20:Array.isArray(n)?o(n[0]):0},Ny=/\\/g,hy=/"/g,C$=function o(n,t,S,f){if(Array.isArray(n)===!1)return n;if(!n.length)return"{}";const T=n[0],M=f===1020?";":",";if(Array.isArray(T)&&!T.type)return"{"+n.map((F)=>o(F,t,S,f)).join(M)+"}";return"{"+n.map((F)=>{if(F===void 0){if(F=S.transform.undefined,F===void 0)throw Lo.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return F===null?"null":'"'+xy(t?t(F.type?F.value:F):""+F)+'"'}).join(M)+"}"},uT={i:0,char:null,str:"",quoted:!1,last:0},L$=function o(n,t,S){return uT.i=uT.last=0,I$(uT,n,t,S)},Jt=(o)=>{let n=o[0];for(let t=1;t<o.length;t++)n+=o[t]==="_"?o[++t].toUpperCase():o[t];return n},yt=(o)=>{let n=o[0].toUpperCase();for(let t=1;t<o.length;t++)n+=o[t]==="_"?o[++t].toUpperCase():o[t];return n},Rt=(o)=>o.replace(/_/g,"-"),GS=(o)=>o.replace(/([A-Z])/g,"_$1").toLowerCase(),zS=(o)=>(o.slice(0,1)+o.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),HS=(o)=>o.replace(/-/g,"_");Jt.column={from:Jt};Jt.value={from:tM(Jt)};GS.column={to:GS};var SM={...Jt};SM.column.to=GS;yt.column={from:yt};yt.value={from:tM(yt)};zS.column={to:zS};var fM={...yt};fM.column.to=zS;Rt.column={from:Rt};Rt.value={from:tM(Rt)};HS.column={to:HS};var TM={...Rt};TM.column.to=HS;import j$ from"net";import py from"tls";import QS from"crypto";import MM from"stream";import{performance as B$}from"perf_hooks";class Ot 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}}function iy(o=[]){let n=o.slice(),t=0;return{get length(){return n.length-t},remove:(S)=>{const f=n.indexOf(S);return f===-1?null:(n.splice(f,1),S)},push:(S)=>(n.push(S),S),shift:()=>{const S=n[t++];if(t===n.length)t=0,n=[];else n[t-1]=void 0;return S}}}var Jn=iy;function Lf(o){if(go.length-yo.i<o){const n=go,t=n.length;go=Buffer.allocUnsafe(t+(t>>1)+o),n.copy(go)}}function qy(){return yo.i=0,yo}var go=Buffer.allocUnsafe(256),vy="BCcDdEFfHPpQSX".split("").reduce((o,n)=>{const t=n.charCodeAt(0);return o[n]=()=>{return go[0]=t,yo.i=5,yo},o},{}),yo=Object.assign(qy,vy,{N:String.fromCharCode(0),i:0,inc(o){return yo.i+=o,yo},str(o){const n=Buffer.byteLength(o);return Lf(n),yo.i+=go.write(o,yo.i,n,"utf8"),yo},i16(o){return Lf(2),go.writeUInt16BE(o,yo.i),yo.i+=2,yo},i32(o,n){if(n||n===0)return go.writeUInt32BE(o,n),yo;return Lf(4),go.writeUInt32BE(o,yo.i),yo.i+=4,yo},z(o){return Lf(o),go.fill(0,yo.i,yo.i+o),yo.i+=o,yo},raw(o){return go=Buffer.concat([go.subarray(0,yo.i),o]),yo.i=go.length,yo},end(o=1){go.writeUInt32BE(yo.i-o,o);const n=go.subarray(0,yo.i);return yo.i=0,go=Buffer.allocUnsafe(256),n}}),p=yo;function N$(o,n={},{onopen:t=jt,onend:S=jt,onclose:f=jt}={}){const{ssl:T,max:M,user:F,host:k,port:A,database:$,parsers:O,transform:w,onnotice:G,onnotify:r,onparameter:H,max_pipeline:D,keep_alive:I,backoff:v,target_session_attrs:N}=o,P=Jn(),Y=Zy++,K={pid:null,secret:null},Q=kM(df,o.idle_timeout),i=kM(df,o.max_lifetime),g=kM(XJ,o.connect_timeout);let _=null,h,C=new Ot,a=Buffer.alloc(0),So=o.fetch_types,to={},Wo={},Mn=Math.random().toString(36).slice(2),E=1,x=0,To=0,Jo=0,Io=0,fo=0,_o=0,ro=0,Ho=null,Xo=null,vo=!1,wo=null,Xn=null,qo=null,gn=null,jo=null,Yo=null,Yn=null,Ln=null,V=null,st=null;const po={queue:n.closed,idleTimer:Q,connect(J){qo=J||!0,iM()},terminate:nS,execute:oS,cancel:WJ,end:df,count:0,id:Y};return n.closed&&n.closed.push(po),po;async function OJ(){let J;try{J=o.socket?await Promise.resolve(o.socket(o)):new j$.Socket}catch(W){Gt(W);return}return J.on("error",Gt),J.on("close",vM),J.on("drain",hM),J}async function WJ({pid:J,secret:W},Z,$o){try{h=p().i32(16).i32(80877102).i32(J).i32(W).end(16),await xM(),_.once("error",$o),_.once("close",Z)}catch(Do){$o(Do)}}function oS(J){if(vo)return pS(J,Lo.connection("CONNECTION_DESTROYED",o));if(J.cancelled)return;try{return J.state=K,V?P.push(J):(V=J,V.active=!0),KJ(J),No(_J(J))&&!J.describeFirst&&!J.cursorFn&&P.length<D&&(!J.options.onexecute||J.options.onexecute(po))}catch(W){return P.length===0&&No(tt),In(W),!0}}function _J(J){if(J.parameters.length>=65534)throw Lo.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return J.options.simple?p().Q().str(J.statement.string+p.N).end():J.describeFirst?Buffer.concat([cM(J),c$]):J.prepare?J.prepared?qS(J):Buffer.concat([cM(J),qS(J)]):wJ(J)}function cM(J){return Buffer.concat([pM(J.statement.string,J.parameters,J.statement.types,J.statement.name),Sy("S",J.statement.name)])}function qS(J){return Buffer.concat([ty(J.parameters,J.statement.types,J.statement.name,J.cursorName),J.cursorFn?ZM("",J.cursorRows):gy])}function wJ(J){return Buffer.concat([pM(J.statement.string,J.parameters,J.statement.types),ly,qS(J)])}function KJ(J){const W=[],Z=[],$o=sT(J,J.strings[0],J.args[0],W,Z,o);!J.tagged&&J.args.forEach((Do)=>rf(Do,W,Z,o)),J.prepare=o.prepare&&("prepare"in J.options?J.options.prepare:!0),J.string=$o,J.signature=J.prepare&&Z+$o,J.onlyDescribe&&delete Wo[J.signature],J.parameters=J.parameters||W,J.prepared=J.prepare&&J.signature in Wo,J.describeFirst=J.onlyDescribe||W.length&&!J.prepared,J.statement=J.prepared?Wo[J.signature]:{string:$o,types:Z,name:J.prepare?Mn+E++:""},typeof o.debug==="function"&&o.debug(Y,$o,W,Z)}function No(J,W){if(Yo=Yo?Buffer.concat([Yo,J]):Buffer.from(J),W||Yo.length>=1024)return bM(W);return Xo===null&&(Xo=setImmediate(bM)),!0}function bM(J){const W=_.write(Yo,J);return Xo!==null&&clearImmediate(Xo),Yo=Xo=null,W}function XJ(){In(Lo.connection("CONNECT_TIMEOUT",o,_)),_.destroy()}async function NM(){if(No(Py),!await new Promise((W)=>_.once("data",(Z)=>W(Z[0]===83)))&&T==="prefer")return Et();_.removeAllListeners(),_=py.connect({socket:_,servername:j$.isIP(_.host)?void 0:_.host,...T==="require"||T==="allow"||T==="prefer"?{rejectUnauthorized:!1}:T==="verify-full"?{}:typeof T==="object"?T:{}}),_.on("secureConnect",Et),_.on("error",Gt),_.on("close",vM),_.on("drain",hM)}function hM(){!V&&t(po)}function ef(J){if(wo){if(wo.push(J),To-=J.length,To>=0)return}a=wo?Buffer.concat(wo,fo-To):a.length===0?J:Buffer.concat([a,J],a.length+J.length);while(a.length>4){if(fo=a.readUInt32BE(1),fo>=a.length){To=fo-a.length,wo=[a];break}try{YJ(a.subarray(0,fo+1))}catch(W){V&&(V.cursorFn||V.describeFirst)&&No(tt),In(W)}a=a.subarray(fo+1),To=0,wo=null}}async function xM(){if(vo=!1,to={},_||(_=await OJ()),!_)return;if(g.start(),o.socket)return T?NM():Et();if(_.on("connect",T?NM:Et),o.path)return _.connect(o.path);_.ssl=T,_.connect(A[Jo],k[Jo]),_.host=k[Jo],_.port=A[Jo],Jo=(Jo+1)%A.length}function iM(){setTimeout(xM,x?x+_o-B$.now():0)}function Et(){try{Wo={},So=o.fetch_types,Mn=Math.random().toString(36).slice(2),E=1,i.start(),_.on("data",ef),I&&_.setKeepAlive&&_.setKeepAlive(!0,1000*I);const J=Ty();No(J)}catch(J){Gt(J)}}function Gt(J){if(po.queue===n.connecting&&o.host[Io+1])return;In(J);while(P.length)pS(P.shift(),J)}function In(J){jo&&(jo.destroy(J),jo=null),V&&pS(V,J),qo&&(pS(qo,J),qo=null)}function pS(J,W){Object.defineProperties(W,{stack:{value:W.stack+J.origin.replace(/.*\n/,"\n"),enumerable:o.debug},query:{value:J.string,enumerable:o.debug},parameters:{value:J.parameters,enumerable:o.debug},args:{value:J.args,enumerable:o.debug},types:{value:J.statement&&J.statement.types,enumerable:o.debug}}),J.reject(W)}function df(){return gn||(!po.reserved&&S(po),!po.reserved&&!qo&&!V&&P.length===0?(nS(),new Promise((J)=>_&&_.readyState!=="closed"?_.once("close",J):J())):gn=new Promise((J)=>Yn=J))}function nS(){if(vo=!0,jo||V||qo||P.length)Gt(Lo.connection("CONNECTION_DESTROYED",o));if(clearImmediate(Xo),_)_.removeListener("data",ef),_.removeListener("connect",Et),_.readyState==="open"&&_.end(p().X().end());Yn&&(Yn(),gn=Yn=null)}async function vM(J){if(a=Buffer.alloc(0),To=0,wo=null,clearImmediate(Xo),_.removeListener("data",ef),_.removeListener("connect",Et),Q.cancel(),i.cancel(),g.cancel(),_.removeAllListeners(),_=null,qo)return iM();!J&&(V||P.length)&&Gt(Lo.connection("CONNECTION_CLOSED",o,_)),x=B$.now(),J&&o.shared.retries++,_o=(typeof v==="function"?v(o.shared.retries):v)*1000,f(po,Lo.connection("CONNECTION_CLOSED",o,_))}function YJ(J,W=J[0]){(W===68?EJ:W===100?lJ:W===65?vJ:W===83?GJ:W===90?zJ:W===67?HJ:W===50?qM:W===49?mJ:W===116?QJ:W===84?DJ:W===82?UJ:W===110?jJ:W===75?BJ:W===69?xJ:W===115?qJ:W===51?pJ:W===71?ZJ:W===78?dJ:W===72?PJ:W===99?eJ:W===73?uJ:W===86?aJ:W===118?sJ:W===87?gJ:oy)(J)}function EJ(J){let W=7,Z,$o,Do;const Zo=V.isRaw?new Array(V.statement.columns.length):{};for(let eo=0;eo<V.statement.columns.length;eo++)$o=V.statement.columns[eo],Z=J.readInt32BE(W),W+=4,Do=Z===-1?null:V.isRaw===!0?J.subarray(W,W+=Z):$o.parser===void 0?J.toString("utf8",W,W+=Z):$o.parser.array===!0?$o.parser(J.toString("utf8",W+1,W+=Z)):$o.parser(J.toString("utf8",W,W+=Z)),V.isRaw?Zo[eo]=V.isRaw===!0?Do:w.value.from?w.value.from(Do,$o):Do:Zo[$o.name]=w.value.from?w.value.from(Do,$o):Do;V.forEachFn?V.forEachFn(w.row.from?w.row.from(Zo):Zo,C):C[ro++]=w.row.from?w.row.from(Zo):Zo}function GJ(J){const[W,Z]=J.toString("utf8",5,J.length-1).split(p.N);if(to[W]=Z,o.parameters[W]!==Z)o.parameters[W]=Z,H&&H(W,Z)}function zJ(J){if(V&&V.options.simple&&V.resolve(Xn||C),V=Xn=null,C=new Ot,g.cancel(),qo){if(N){if(!to.in_hot_standby||!to.default_transaction_read_only)return hJ();else if(NJ(N,to))return nS()}if(So)return qo===!0&&(qo=null),cJ();qo!==!0&&oS(qo),o.shared.retries=Io=0,qo=null;return}while(P.length&&(V=P.shift())&&(V.active=!0,V.cancelled))N$(o).cancel(V.state,V.cancelled.resolve,V.cancelled.reject);if(V)return;po.reserved?!po.reserved.release&&J[5]===73?gn?nS():(po.reserved=null,t(po)):po.reserved():gn?nS():t(po)}function HJ(J){ro=0;for(let W=J.length-1;W>0;W--){if(J[W]===32&&J[W+1]<58&&C.count===null)C.count=+J.toString("utf8",W+1,J.length-1);if(J[W-1]>=65){C.command=J.toString("utf8",5,W),C.state=K;break}}if(st&&(st(),st=null),C.command==="BEGIN"&&M!==1&&!po.reserved)return In(Lo.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(V.options.simple)return qM();if(V.cursorFn)C.count&&V.cursorFn(C),No(tt);V.resolve(C)}function mJ(){V.parsing=!1}function qM(){!C.statement&&(C.statement=V.statement),C.columns=V.statement.columns}function QJ(J){const W=J.readUInt16BE(5);for(let Z=0;Z<W;++Z)!V.statement.types[Z]&&(V.statement.types[Z]=J.readUInt32BE(7+Z*4));V.prepare&&(Wo[V.signature]=V.statement),V.describeFirst&&!V.onlyDescribe&&(No(qS(V)),V.describeFirst=!1)}function DJ(J){if(C.command)Xn=Xn||[C],Xn.push(C=new Ot),C.count=null,V.statement.columns=null;const W=J.readUInt16BE(5);let Z=7,$o;V.statement.columns=Array(W);for(let Do=0;Do<W;++Do){$o=Z;while(J[Z++]!==0);const Zo=J.readUInt32BE(Z),eo=J.readUInt16BE(Z+4),ln=J.readUInt32BE(Z+6);V.statement.columns[Do]={name:w.column.from?w.column.from(J.toString("utf8",$o,Z-1)):J.toString("utf8",$o,Z-1),parser:O[ln],table:Zo,number:eo,type:ln},Z+=18}if(C.statement=V.statement,V.onlyDescribe)return V.resolve(V.statement),No(tt)}async function UJ(J,W=J.readUInt32BE(5)){(W===3?VJ:W===5?rJ:W===10?CJ:W===11?LJ:W===12?IJ:W!==0?ny:jt)(J,W)}async function VJ(){const J=await uf();No(p().p().str(J).z(1).end())}async function rJ(J){const W="md5"+await b$(Buffer.concat([Buffer.from(await b$(await uf()+F)),J.subarray(9)]));No(p().p().str(W).z(1).end())}async function CJ(){Ln=(await QS.randomBytes(18)).toString("base64"),p().p().str("SCRAM-SHA-256"+p.N);const J=p.i;No(p.inc(4).str("n,,n=*,r="+Ln).i32(p.i-J-4,J).end())}async function LJ(J){const W=J.toString("utf8",9).split(",").reduce((eo,ln)=>(eo[ln[0]]=ln.slice(2),eo),{}),Z=await QS.pbkdf2Sync(await uf(),Buffer.from(W.s,"base64"),parseInt(W.i),32,"sha256"),$o=await If(Z,"Client Key"),Do="n=*,r="+Ln+",r="+W.r+",s="+W.s+",i="+W.i+",c=biws,r="+W.r;Ho=(await If(await If(Z,"Server Key"),Do)).toString("base64");const Zo="c=biws,r="+W.r+",p="+ay($o,Buffer.from(await If(await uy($o),Do))).toString("base64");No(p().p().str(Zo).end())}function IJ(J){if(J.toString("utf8",9).split(p.N,1)[0].slice(2)===Ho)return;In(Lo.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),_.destroy()}function uf(){return Promise.resolve(typeof o.pass==="function"?o.pass():o.pass)}function jJ(){if(C.statement=V.statement,C.statement.columns=[],V.onlyDescribe)return V.resolve(V.statement),No(tt)}function BJ(J){K.pid=J.readUInt32BE(5),K.secret=J.readUInt32BE(9)}async function cJ(){So=!1,(await new wn([`
|
|
3
|
+
var Oy=Object.create;var{getPrototypeOf:Wy,defineProperty:oT,getOwnPropertyNames:_y}=Object;var wy=Object.prototype.hasOwnProperty;var h0=(o,n,t)=>{t=o!=null?Oy(Wy(o)):{};const S=n||!o||!o.__esModule?oT(t,"default",{value:o,enumerable:!0}):t;for(let f of _y(o))if(!wy.call(S,f))oT(S,f,{get:()=>o[f],enumerable:!0});return S};var x0=(o,n)=>()=>(n||o((n={exports:{}}).exports,n),n.exports);var Ky=(o,n)=>{for(var t in n)oT(o,t,{get:n[t],enumerable:!0,configurable:!0,set:(S)=>n[t]=()=>S})};import{join as B0,normalize as c0,resolve as EJ}from"path";function zt(o=Math.random){return o().toString(36).slice(2)}class tS extends Promise{fate;resolve;reject;done=!1;constructor(o){let n,t;super((S,f)=>{n=S,t=f});this.resolve=n,this.reject=t,this.use(o instanceof Promise?o:new Promise(o))}pass(o,n){if(o===this.fate)this.resolve(n),this.done=!0}fail(o,n){if(o===this.fate)this.reject(n),this.done=!0}use(o){if(o instanceof Promise){const n=o;this.fate=n,n.then((t)=>{this.pass(n,t)},(t)=>{this.fail(n,t)})}else this.resolve(o),this.fate=void 0}}function uM(o){return Object.entries(o)}var aM=(o,n,t=Mo.STORE)=>{return En(t,{key:`${o.key}:JSON`,get:({get:S})=>n.toJson(S(o)),set:({set:S},f)=>{S(o,n.fromJson(f))}})};function D(o){while(o.child!==null)o=o.child;return o}function sM(o){while(o.parent!==null)o=o.parent;return o}class s{Subscriber;subscribers=new Map;subscribe(o,n){return this.subscribers.set(o,n),()=>{this.unsubscribe(o)}}unsubscribe(o){this.subscribers.delete(o)}next(o){const n=this.subscribers.values();for(let t of n)t(o)}}class nT extends s{state;constructor(o){super();this.state=o}next(o){this.state=o,super.next(o)}}function jn(o,n,t){const S={key:n.key,type:"atom_family"},f=o.families.get(n.key);if(f)o.logger.error("\u2757","atom_family",n.key,`Overwriting an existing ${Gn(f)} "${f.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const T=new s,F=Object.assign((k)=>{const A=e(k),$={key:n.key,subKey:A},O=`${n.key}(${A})`,K=D(o),G=n.default,I={key:O,default:G instanceof Function?G(k):G};if(n.effects)I.effects=n.effects(k);const H=tn(K,I,$);return T.next({type:"state_creation",token:H}),H},S,{subject:T,install:(k)=>jn(k,n),internalRoles:t});return o.families.set(n.key,F),o.defaults.set(n.key,n.default),S}function oF(o,n){if("mutable"in n)return SS(o,n);return jn(o,n)}function hn(o,n,t){const S={key:n.key,type:"readonly_selector_family"},f=o.families.get(n.key);if(f)o.logger.error("\u2757","readonly_selector_family",n.key,`Overwriting an existing ${Gn(f)} "${f.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const T=new s,F=Object.assign((k)=>{const A=e(k),$={key:n.key,subKey:A},O=`${n.key}(${A})`,K=D(o),G=fS(K,{key:O,get:n.get(k)},$);return T.next({type:"state_creation",token:G}),G},S,{internalRoles:t,subject:T,install:(k)=>hn(k,n),default:(k)=>{return n.get(k)({get:(...$)=>$o(o,...$),find:($,O)=>Jo(o,$,O),seek:($,O)=>Go(o,$,O),json:($)=>Lo(o,$)})}});return o.families.set(n.key,F),S}function TS(o,n){if("set"in n)return MS(o,n);return hn(o,n)}function Ht(o,n){const t=e(n),S=`${o.key}(${t})`,f=Xy[o.type],T={key:S,type:f};if(f==="molecule")Object.assign(T,{key:n,family:o});else Object.assign(T,{family:{key:o.key,subKey:t}});return Object.assign(T,{counterfeit:!0}),T}var Xy={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function Po(o){const n={key:o.key,type:o.type};if("family"in o)n.family=o.family;return n}function mt(o){return nF(Mo.STORE,o)}function At(o){return oF(Mo.STORE,o)}function tT(...o){if(o.length===2)return $o(Mo.STORE,...o);return $o(Mo.STORE,...o)}var ST=(o)=>(n,t,S,f,...T)=>{console[o](`${n} ${t} "${S}" ${f}`,...T)},Yy={error:ST("error"),info:ST("info"),warn:ST("warn")};class fT{o;n;t;constructor(o,n,t=Yy){this.logLevel=o;this.filter=n;this.logger=t}error=(...o)=>{if((this.filter?.(...o)??!0)&&this.logLevel!==null)this.logger.error(...o)};info=(...o)=>{if((this.filter?.(...o)??!0)&&this.logLevel==="info")this.logger.info(...o)};warn=(...o)=>{if((this.filter?.(...o)??!0)&&this.logLevel!=="error"&&this.logLevel!==null)this.logger.warn(...o)}}function ZS(o){return TS(Mo.STORE,o)}function FS(o){return TT(o,Mo.STORE)}class kn{a;b;cardinality;relations=new Map;contents=new Map;isContent;makeContentKey=(o,n)=>`${o}:${n}`;warn;getRelatedKeys(o){return this.relations.get(o)}addRelation(o,n){let t=this.relations.get(o),S=this.relations.get(n);if(t)t.add(n);else t=new Set([n]),this.relations.set(o,t);if(S)S.add(o);else S=new Set([o]),this.relations.set(n,S)}deleteRelation(o,n){const t=this.relations.get(o);if(t){if(t.delete(n),t.size===0)this.relations.delete(o);const S=this.relations.get(n);if(S){if(S.delete(o),S.size===0)this.relations.delete(n)}}}replaceRelationsUnsafely(o,n){this.relations.set(o,new Set(n));for(let t of n){const S=new Set([o]);this.relations.set(t,S)}}replaceRelationsSafely(o,n){const t=this.relations.get(o);if(t)for(let S of t){const f=this.relations.get(S);if(f){if(f.size===1)this.relations.delete(S);else f.delete(o);this.contents.delete(this.makeContentKey(o,S))}}this.relations.set(o,new Set(n));for(let S of n){let f=this.relations.get(S);if(f)f.add(o);else f=new Set([o]),this.relations.set(S,f)}}getContentInternal(o){return this.contents.get(o)}setContent(o,n){this.contents.set(o,n)}deleteContent(o){this.contents.delete(o)}constructor(o,n){if(this.a=o.between[0],this.b=o.between[1],this.cardinality=o.cardinality,!n?.externalStore)this.relations=new Map(o.relations?.map(([t,S])=>[t,new Set(S)])),this.contents=new Map(o.contents);if(this.isContent=n?.isContent??null,n?.makeContentKey)this.makeContentKey=n.makeContentKey;if(n?.externalStore){const t=n.externalStore;if(this.has=(S,f)=>t.has(S,f),this.addRelation=(S,f)=>{t.addRelation(S,f)},this.deleteRelation=(S,f)=>{t.deleteRelation(S,f)},this.replaceRelationsSafely=(S,f)=>{t.replaceRelationsSafely(S,f)},this.replaceRelationsUnsafely=(S,f)=>{t.replaceRelationsUnsafely(S,f)},this.getRelatedKeys=(S)=>t.getRelatedKeys(S),t.getContent)this.getContentInternal=(S)=>{return t.getContent(S)},this.setContent=(S,f)=>{t.setContent(S,f)},this.deleteContent=(S)=>{t.deleteContent(S)};for(let[S,f]of o.relations??[])for(let T of f)this.addRelation(S,T);for(let[S,f]of o.contents??[])this.setContent(S,f)}if(n?.warn)this.warn=n.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([o,n])=>[o,[...n]]),contents:[...this.contents.entries()]}}set(o,...n){const t=typeof n[0]==="string"?n[0]:o[this.b],S=n[1]??typeof n[0]==="string"?void 0:n[0];switch(o=typeof o==="string"?o:o[this.a],this.cardinality){case"1:1":{const f=this.getRelatedKey(o);if(f&&f!==t)this.delete(f,o)}case"1:n":{const f=this.getRelatedKey(t);if(f&&f!==o)this.delete(f,t)}}if(S){const f=this.makeContentKey(o,t);this.setContent(f,S)}return this.addRelation(o,t),this}delete(o,n){n=typeof n==="string"?n:o[this.b];const t=typeof o==="string"?o:o[this.a];if(t===void 0&&typeof n==="string"){const S=this.getRelatedKeys(n);if(S)for(let f of S)this.delete(f,n)}if(typeof t==="string"&&n===void 0){const S=this.getRelatedKeys(t);if(S)for(let f of S)this.delete(t,f)}if(typeof t==="string"&&typeof n==="string"){this.deleteRelation(t,n);const S=this.makeContentKey(t,n);this.deleteContent(S)}return this}getRelatedKey(o){const n=this.getRelatedKeys(o);if(n){if(n.size>1)this.warn?.(`${n.size} related keys were found for key "${o}": (${[...n].map((t)=>`"${t}"`).join(", ")}). Only one related key was expected.`);for(let t of n)return t}}replaceRelations(o,n,t){const S=!Array.isArray(n),f=S?Object.keys(n):n;if(t?.reckless)this.replaceRelationsUnsafely(o,f);else this.replaceRelationsSafely(o,f);if(S)for(let T of f){const M=this.makeContentKey(o,T),F=n[T];this.setContent(M,F)}return this}getContent(o,n){const t=this.makeContentKey(o,n);return this.getContentInternal(t)}getRelationEntries(o){const n=o[this.a],t=o[this.b];if(n!==void 0&&t===void 0){const S=this.getRelatedKeys(n);if(S)return[...S].map((f)=>{return[f,this.getContent(n,f)??null]})}if(n===void 0&&t!==void 0){const S=this.getRelatedKeys(t);if(S)return[...S].map((f)=>{return[f,this.getContent(f,t)??null]})}return[]}has(o,n){if(n)return this.getRelatedKeys(o)?.has(n)??!1;return this.relations.has(o)}}function Vo(o){return"epoch"in o.transactionMeta}function ko(o){return"phase"in o.transactionMeta}var SF=(o)=>{const n=D(o);if(!ko(n)){o.logger.warn("\uD83D\uDC1E","transaction","???","abortTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}o.logger.info("\uD83E\uDE82","transaction",n.transactionMeta.update.key,"Aborting transaction"),n.parent.child=null};function Gn(o){return o.type.split("_").map(Ey).join(" ")}var Ey=(o)=>o[0].toUpperCase()+o.slice(1);class Sn extends Error{constructor(...o){const n=o[0],t=o.length===2?o[1]:o[2];if(o.length===2)super(`${Gn(n)} ${e(n.key)} not found in store "${t.config.name}".`);else{const S=o[1];super(`${Gn(n)} "${n.key}" member ${e(S)} not found in store "${t.config.name}".`)}}}function dn(o,n,t){return(...S)=>{const f=u(o,t);if(f)return f.run(S,n);throw new Sn(o,t)}}var PS=(o)=>(n)=>o instanceof Function?o(n):o;var un=(o,n)=>{if(n.valueMap.has(o.key))return n.logger.info("\uD83D\uDCD6",o.type,o.key,"reading cached value"),fF(o,n);if(o.type==="selector"||o.type==="readonly_selector")return n.logger.info("\uD83E\uDDEE",o.type,o.key,"computing value"),o.get();const t=o.default instanceof Function?o.default():o.default;return n.logger.info("\uD83D\uDC81","atom",o.key,"could not find cached value; using default",t),o.default instanceof Function?o.default():o.default};var TF=(o,n)=>{if(o.operation.open){const t=performance.now();return o.logger.info("\u2757",n.type,n.key,`deferring setState at T-${t} until setState for "${o.operation.token.key}" is done`),t}o.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:n},o.logger.info("\u2B55",n.type,n.key,`operation start in store "${o.config.name}"${!ko(o)?"":` ${o.transactionMeta.phase} "${o.transactionMeta.update.key}"`}`)},MF=(o)=>{if(o.operation.open)o.logger.info("\uD83D\uDD34",o.operation.token.type,o.operation.token.key,`operation done in store "${o.config.name}"`);o.operation={open:!1},o.on.operationClose.next(o.operation)},FF=(o,n)=>{if(!o.operation.open)return o.logger.error("\uD83D\uDC1E","unknown",n,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return o.operation.done.has(n)},Qt=(o,n)=>{if(!o.operation.open){o.logger.error("\uD83D\uDC1E","unknown",n,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}o.operation.done.add(n)};var kF=(o,n,t)=>{switch(o.type){case"mutable_atom":t.logger.info("\uD83D\uDCE2",o.type,o.key,"is now (",n.newValue,") subscribers:",o.subject.subscribers);break;default:t.logger.info("\uD83D\uDCE2",o.type,o.key,"went (",n.oldValue,"->",n.newValue,") subscribers:",o.subject.subscribers)}o.subject.next(n)};var MT=(o,n)=>{const t=D(n),S=t.selectorAtoms.getRelatedKeys(o.key);if(t.logger.info("\uD83E\uDDF9",o.type,o.key,S?`evicting ${S.size} states downstream:`:"no downstream states",S??"to evict"),S){if(t.operation.open)t.logger.info("\uD83E\uDDF9",o.type,o.key,`[ ${[...t.operation.done].join(", ")} ] already done`);for(let f of S){if(FF(t,f))continue;AF(f,t),Qt(t,f)}}};function Gy(o,n){if(JF(n.newValue))return!1;if(o.includes("\uD83D\uDD0D"))return!1;return!0}var $F=(o,n,t)=>{const{key:S}=o,f=D(t);if(!ko(f)||f.transactionMeta.phase!=="building"){t.logger.error("\uD83D\uDC1E","atom",S,"stowUpdate called outside of a transaction. This is probably a bug.");return}if(!Gy(S,n))return;const M={type:"atom_update",key:S,...n};if(o.family)M.family=o.family;f.transactionMeta.update.updates.push(M),t.logger.info("\uD83D\uDCC1","atom",S,"stowed (",n.oldValue,"->",n.newValue,")")};var yF=(o,n,t)=>{const S=un(o,t);let f=S;if(o.type==="mutable_atom"&&ko(t)){const{parent:M}=t;f=kS(o,M,t)}if(f=PS(n)(f),t.logger.info("\uD83D\uDCDD","atom",o.key,"set to",f),f=Rn(o.key,f,o.subject,t),RF(o.key,t))OF(o.key,t);Qt(t,o.key),MT(o,t);const T={oldValue:S,newValue:f};if(Vo(t))kF(o,T,t);else if(t.parent){if(t.on.transactionApplying.state===null)$F(o,T,t);else if(o.key.startsWith("*")){const M=o.key.slice(1),F=t.atoms.get(M);let k=t.valueMap.get(M);if(F.type==="mutable_atom"&&ko(t)){const{parent:$}=t;k=kS(F,$,t)}if(k.do(T.newValue)===null)MT(F,t)}}};var gS=(o,n,t)=>{switch(o.type){case"atom":case"mutable_atom":yF(o,n,t);break;case"selector":o.set(n);break}};function lS(o,n){if(n.family){const t=o.families.get(n.family.key);if(t)return t}}function Uo(o,...n){let t,S,f,T;if(n.length===2){if(t=n[0],T=n[1],S=lS(o,t)??null,S)f=t.family?co(t.family.subKey):null,t=Jo(o,S,f)}else S=n[0],f=n[1],T=n[2],t=Jo(o,S,f);if("counterfeit"in t){const k=o.disposalTraces.buffer.find((A)=>A?.key===t.key);o.logger.error("\u274C",t.type,t.key,`could not be set because it was not found in the store "${o.config.name}".`,k?`This state was previously disposed:\n${k.trace}`:"No previous disposal trace was found.");return}const M=TF(o,t);if(M){const k=o.on.operationClose.subscribe(`waiting to set "${t.key}" at T-${M}`,()=>{k(),o.logger.info("\uD83D\uDFE2",t.type,t.key,`resuming deferred setState from T-${M}`),Uo(o,t,T)});return}const F=u(t,o);gS(F,T,o),MF(o)}function eS(o,n,t){const{key:S,newValue:f,oldValue:T}=n,M=o==="newValue"?f:T,F={key:S,type:"atom"};if(n.family)Object.assign(F,{family:n.family});Uo(t,F,M)}function FT(o,n,t){const S=e(t);try{const f=[];let T;if(n==="root")f.push(o.molecules.get('"root"')),T="all";else if(n[0][0]===WF){T="any";const $=e(n),O=o.molecules.get($);if(!O)throw new Error(`Molecule ${$} not found in store "${o.config.name}"`);f.push(O)}else if(t[0][0]===WF){T="all";for(let O of n){const K=e(O),G=o.molecules.get(K);if(!G)throw new Error(`Molecule ${K} not found in store "${o.config.name}"`);f.push(G)}}else{T="any";const O=e(n),K=o.molecules.get(O);if(!K)throw new Error(`Molecule ${O} not found in store "${o.config.name}"`);f.push(K)}const M=new Dt(f,t);M._dependsOn=T,o.molecules.set(S,M);for(let $ of f)$.below.set(M.stringKey,M);const F={type:"molecule_creation",subType:"modern",key:M.key,provenance:n},k=D(o);if(ko(k)&&k.transactionMeta.phase==="building")k.transactionMeta.update.updates.push(F);else k.on.moleculeCreationStart.next(F)}catch(f){if(f instanceof Error)o.logger.error("\u274C","molecule",S,"allocation failed:",f.message)}return t}function AS(o,n){const t=e(n),S=o.molecules.get(t);if(!S)throw new Error(`Molecule ${t} not found in store "${o.config.name}"`);for(let A of S.joins.values())A.relations.delete(S.key),A.molecules.delete(S.stringKey);let f;if(S.above.size===1)f=S.above.values().next().value.key;else f=[...S.above.values()].map(({key:A})=>A);const T=[];for(let A of S.tokens.values()){const $=A.family;T.push([$.key,o.valueMap.get(A.key)])}for(let A of S.tokens.values())uo(o,A);for(let A of S.below.values())if(A.dependsOn==="all")AS(o,A.key);else if(A.above.delete(S.stringKey),A.above.size===0)AS(o,A.key);S.below.clear();const M={type:"molecule_disposal",subType:"modern",key:S.key,values:T,provenance:f},F=D(o);if(ko(F)&&F.transactionMeta.phase==="building")F.transactionMeta.update.updates.push(M);else F.on.moleculeDisposal.next(M);F.molecules.delete(S.stringKey);for(let A of S.above.values())A.below.delete(S.stringKey)}var QW=Symbol("provenance"),WF="T$";function _F(o,n){const t=new s,S={type:"molecule_family",key:n.key,dependsOn:n.dependsOn??"all"},f={...S,subject:t,new:n.new};return o.moleculeFamilies.set(n.key,f),S}function zn(o,n,t){const S=xn(t,n,o.key);o.tokens.set(S.key,S);const f=ko(t)&&t.transactionMeta.phase==="building",T=t.moleculeInProgress===o.key;if(!f&&!T)o.subject.next({type:"state_creation",token:S});return S}class bo extends Set{mode="record";subject=new s;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(o,n=0){super(o);if(o instanceof bo)this.parent=o,this.cacheUpdateNumber=o.cacheUpdateNumber;if(n)this.cacheLimit=n,this.cache=new Array(n),this.subscribe("auto cache",(t)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=t})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(o){const n=new bo(o.members,o.cacheLimit);return n.cache=o.cache,n.cacheIdx=o.cacheIdx,n.cacheUpdateNumber=o.cacheUpdateNumber,n}add(o){const n=super.add(o);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${e(o)}`);return n}clear(){const o=this.mode==="record"?[...this]:null;if(super.clear(),o)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(o)}`)}delete(o){const n=super.delete(o);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${e(o)}`);return n}parent;child=null;transactionUpdates=null;transaction(o){this.mode="transaction",this.transactionUpdates=[],this.child=new bo(this);const n=this.child._subscribe("transaction",(t)=>{this.transactionUpdates?.push(t)});try{if(o(this.child)){for(let S of this.transactionUpdates)this.doStep(S);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(t){throw console.error("Failed to apply transaction to SetRTX:",t),t}finally{n(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(o,n){return this.subject.subscribe(o,n)}subscribe(o,n){return this.subject.subscribe(o,(t)=>{n(`${this.cacheUpdateNumber}=${t}`)})}emit(o){this.subject.next(o)}doStep(o){const n=o.indexOf(":"),t=o.substring(0,n),S=o.substring(n+1);switch(t){case"add":this.add(JSON.parse(S));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(S));break;case"tx":for(let f of S.split(";"))this.doStep(f)}}getUpdateNumber(o){const n=o.indexOf("=");return Number(o.substring(0,n))}do(o){const n=o.indexOf("="),t=Number(o.substring(0,n)),S=t-this.cacheUpdateNumber;if(S>0){if(S===1){this.mode="playback";const T=o.substring(n+1);return this.doStep(T),this.mode="record",this.cacheUpdateNumber=t,null}return this.cacheUpdateNumber+1}if(Math.abs(S)<this.cacheLimit){const T=this.cacheIdx+S;if(this.cache[T]===o)return null;this.mode="playback";let F=!1;while(!F){this.cacheIdx%=this.cacheLimit;const A=this.cache[this.cacheIdx];if(this.cacheIdx--,!A)return"OUT_OF_RANGE";this.undo(A),F=this.cacheIdx===T-1}const k=o.substring(n+1);return this.doStep(k),this.mode="record",this.cacheUpdateNumber=t,null}return"OUT_OF_RANGE"}undoStep(o){const n=o.indexOf(":"),t=o.substring(0,n),S=o.substring(n+1);switch(t){case"add":this.delete(JSON.parse(S));break;case"del":this.add(JSON.parse(S));break;case"clear":{const f=JSON.parse(S);for(let T of f)this.add(T);break}case"tx":{const f=S.split(";");for(let T=f.length-1;T>=0;T--)this.undoStep(f[T])}}}undo(o){const n=o.indexOf("=");if(Number(o.substring(0,n))===this.cacheUpdateNumber){this.mode="playback";const S=o.substring(n+1);return this.undoStep(S),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function zo(o){return o[0].toUpperCase()+o.slice(1)}function dS(o,n,t=Mo.STORE){return kT(t).set(o.key,new $T(o,n,t)),{key:o.key,type:"join",a:o.between[0],b:o.between[1],cardinality:o.cardinality}}function kT(o){if("joins"in o&&o.joins instanceof Map)return o.joins;const n=new Map;return o.joins=n,n}function $S(o,n){const t=kT(n);let S=t.get(o.key);if(S===void 0){if(S=kT(Mo.STORE).get(o.key)?.in(n),S===void 0)throw new Error(`Join "${o.key}" not found in store "${n.config.name}"`);t.set(o.key,S)}return S}function uS(o,n,t){const S=$S(o,t);let f;switch(o.cardinality){case"1:1":{const T=`${o.a}KeyOf${zo(o.b)}`,M=`${o.b}KeyOf${zo(o.a)}`;f={get[T](){const k=S.states[T];return S.retrieve(k,n)},get[M](){const k=S.states[M];return S.retrieve(k,n)}};const F=`${o.a}EntryOf${zo(o.b)}`;if(F in S.states){const k=`${o.b}EntryOf${zo(o.a)}`;Object.assign(f,{get[F](){const A=S.states[F];return S.retrieve(A,n)},get[k](){const A=S.states[k];return S.retrieve(A,n)}})}break}case"1:n":{const T=`${o.a}KeyOf${zo(o.b)}`,M=`${o.b}KeysOf${zo(o.a)}`;f={get[T](){const k=S.states[T];return S.retrieve(k,n)},get[M](){const k=S.states[M];return S.retrieve(k,n)}};const F=`${o.a}EntryOf${zo(o.b)}`;if(F in S.states){const k=`${o.b}EntriesOf${zo(o.a)}`;Object.assign(f,{get[F](){const A=S.states[F];return S.retrieve(A,n)},get[k](){const A=S.states[k];return S.retrieve(A,n)}})}break}case"n:n":{const T=`${o.a}KeysOf${zo(o.b)}`,M=`${o.b}KeysOf${zo(o.a)}`;f={get[T](){const k=S.states[T];return S.retrieve(k,n)},get[M](){const k=S.states[M];return S.retrieve(k,n)}};const F=`${o.a}EntriesOf${zo(o.b)}`;if(F in S.states){const k=`${o.b}EntriesOf${zo(o.a)}`;Object.assign(f,{get[F](){const A=S.states[F];return S.retrieve(A,n)},get[k](){const A=S.states[k];return S.retrieve(A,n)}})}}}return f}function wF(o,n){return uS(o,n,Mo.STORE)}function aS(o,n,t){const S=$S(o,t),f=D(t);if(ko(f)){const{toolkit:T}=f.transactionMeta;S.transact(T,({relations:M})=>{n(M)})}else n(S.relations)}function zy(o,n){return $S(o,n).core.findRelatedKeysState}function KF(o){return zy(o,Mo.STORE)}class $T{options;defaultContent;toolkit;retrieve;molecules=new Map;relations;states;core;transact(o,n){const t=this.toolkit;this.toolkit=o,n(this),this.toolkit=t}store;alternates;[Symbol.dispose](){this.alternates.delete(this.store.config.name)}in(o){const n=o.config.name,t=this.alternates.get(n);if(t)return t;const S=new $T(this.options,this.defaultContent,o);return this.alternates.set(n,S),S.alternates=this.alternates,S}constructor(o,n,t=Mo.STORE){this.store=t,this.options=o,this.defaultContent=n,this.alternates=new Map,this.alternates.set(t.config.name,this),this.store.miscResources.set(`join:${o.key}`,this),this.retrieve=(X,w)=>{const z=this.toolkit.seek(X,w);if(z)return z;const B=this.molecules.get(e(w));if(B){const N=u(X,t);return zn(B,N,t)}if(t.config.lifespan==="immortal")throw new Sn(X,w,t);return xn(t,X,w)},this.toolkit={get:(...X)=>$o(t,...X),set:(...X)=>{Uo(t,...X)},find:this.retrieve,seek:(...X)=>Go(t,...X),json:(X)=>Lo(t,X),dispose:(...X)=>{uo(t,...X)}};const S=o.between[0],f=o.between[1],T=SS(t,{key:`${o.key}/relatedKeys`,default:()=>new bo,mutable:!0,fromJson:(X)=>bo.fromJSON(X),toJson:(X)=>X.toJSON()},["join","relations"]);this.core={findRelatedKeysState:T};const M=({get:X},w)=>X(this.retrieve(T,w)),F=(X,w,z)=>{const{set:B}=X,N=this.retrieve(T,w),_=this.retrieve(T,z);B(N,(c)=>c.add(z)),B(_,(c)=>c.add(w))},k=(X,w,z)=>{const{set:B}=X,N=this.retrieve(T,w),_=this.retrieve(T,z);let c,U;B(N,(l)=>{if(l.delete(z),l.size===0)c=`"${w}"`;return l}),B(_,(l)=>{if(l.delete(w),l.size===0)U=`"${z}"`;return l})},A=(X,w,z)=>{const{get:B,set:N}=X,_=this.retrieve(T,w),c=B(_);for(let U of c){if(z.includes(U))continue;const no=this.retrieve(T,U);N(no,(So)=>{return So.delete(w),So})}N(_,(U)=>{return U.transaction((l)=>{l.clear();for(let no of z){const So=M(X,no),_o=So.has(w);if(this.relations.cardinality==="1:n"){const Fn=[];for(let E of So){if(E===w)continue;const p=M(X,E);if(p.delete(no),p.size===0)Fn.push(E)}if(!_o&&So.size>0)So.clear();for(let E of Fn){const p=[no,E].sort(),To=`"${p[0]}:${p[1]}"`;this.molecules.delete(To)}}if(!_o)So.add(w);l.add(no)}return!0}),U})},$=(X,w,z)=>{const{set:B}=X,N=this.retrieve(T,w);B(N,(_)=>{return _.transaction((c)=>{for(let U of z)c.add(U);return!0}),_});for(let _ of z){const c=this.retrieve(T,_);B(c,(U)=>{return U.add(w),U})}return!0},O=(X,w,z)=>{const B=M(X,w);return z?B.has(z):B.size>0},K={getRelatedKeys:(X)=>M(this.toolkit,X),addRelation:(X,w)=>{F(this.toolkit,X,w)},deleteRelation:(X,w)=>{k(this.toolkit,X,w)},replaceRelationsSafely:(X,w)=>{A(this.toolkit,X,w)},replaceRelationsUnsafely:(X,w)=>{$(this.toolkit,X,w)},has:(X,w)=>O(this.toolkit,X,w)};let G,I,H;if(n){I=jn(t,{key:`${o.key}/content`,default:n},["join","content"]);const X={key:o.key,type:"join",a:o.between[0],b:o.between[1],cardinality:o.cardinality};H=_F(t,{key:`${o.key}/content-molecules`,new:class _{U;constructor(c,U){this.key=U}}});const w=({get:_},c)=>_(this.retrieve(I,c)),z=({set:_},c,U)=>{_(this.retrieve(I,c),U)},B=(_,c)=>{const U=t.molecules.get(`"${c}"`);if(U)this.toolkit.dispose(U),this.molecules.delete(`"${c}"`)};G=Object.assign(K,{getContent:(_)=>{return w(this.toolkit,_)},setContent:(_,c)=>{z(this.toolkit,_,c)},deleteContent:(_)=>{B(this.toolkit,_)}})}else G=K;const V=new kn(o,{externalStore:G,makeContentKey:(...X)=>{const w=X.sort(),z=`${w[0]}:${w[1]}`,[B,N]=w.map((_)=>this.molecules.get(e(_)));if(t.config.lifespan==="immortal"&&B&&N){const _=D(t),c=vn(_,[B,N],H,z);this.molecules.set(`"${z}"`,u(c,_))}return z}}),m=()=>hn(t,{key:`${o.key}/singleRelatedKey`,get:(X)=>({get:w})=>{const z=this.retrieve(T,X),B=w(z);for(let N of B)return N;return null}},["join","keys"]),j=()=>{return hn(t,{key:`${o.key}/multipleRelatedKeys`,get:(X)=>({get:w})=>{const z=AT(T,t),B=this.retrieve(z,X);return w(B).members}},["join","keys"])},r=()=>hn(t,{key:`${o.key}/singleRelatedEntry`,get:(X)=>({get:w})=>{const z=this.retrieve(T,X),B=w(z);for(let N of B){const _=V.makeContentKey(X,N),c=this.retrieve(I,_),U=w(c);return[N,U]}return null}},["join","entries"]),i=()=>hn(t,{key:`${o.key}/multipleRelatedEntries`,get:(X)=>({get:w})=>{const z=AT(T,t),B=this.retrieve(z,X);return w(B).members.map((_)=>{const c=V.makeContentKey(X,_),U=this.retrieve(I,c),l=w(U);return[_,l]})}},["join","entries"]);switch(o.cardinality){case"1:1":{const X=m(),w=`${S}KeyOf${zo(f)}`,z=`${f}KeyOf${zo(S)}`,B={[w]:X,[z]:X};let N;if(n){const _=r(),c=`${S}EntryOf${zo(f)}`,U=`${f}EntryOf${zo(S)}`,l={[c]:_,[U]:_};N=Object.assign(B,l)}else N=B;this.relations=V,this.states=N;break}case"1:n":{const X=m(),w=j(),z=`${S}KeyOf${zo(f)}`,B=`${f}KeysOf${zo(S)}`,N={[z]:X,[B]:w};let _;if(n){const c=r(),U=i(),l=`${S}EntryOf${zo(f)}`,no=`${f}EntriesOf${zo(S)}`,So={[l]:c,[no]:U};_=Object.assign(N,So)}else _=N;this.relations=V,this.states=_;break}default:{const X=j(),w=`${S}KeysOf${zo(f)}`,z=`${f}KeysOf${zo(S)}`,B={[w]:X,[z]:X};let N;if(n){const _=i(),c=`${S}EntriesOf${zo(f)}`,U=`${f}EntriesOf${zo(S)}`,l={[c]:_,[U]:_};N=Object.assign(B,l)}else N=B;this.relations=V,this.states=N}}}}function sS(o){return{store:o}}function $o(o,...n){let t,S,f;if(n.length===1){if(t=n[0],t.type!=="molecule"){if(S=lS(o,t)??null,S)f=t.family?co(t.family.subKey):null,t=Jo(o,S,f)}}else{S=n[0],f=n[1];let T;if(S.type==="molecule_family")T=Go(o,S,f)??Ht(S,f);else T=Jo(o,S,f);t=T}if("counterfeit"in t&&"family"in t){S=t.type==="molecule"?u(t.family,o):o.families.get(t.family.key);const T=t.type==="molecule"?t.key:t.family.subKey,M=o.disposalTraces.buffer.find((F)=>F?.key===t.key);switch(o.logger.error("\u274C",t.type,t.key,`could not be retrieved because it was not found in the store "${o.config.name}".`,M?`This state was previously disposed:\n${M.trace}`:"No previous disposal trace was found."),S.type){case"atom_family":case"mutable_atom_family":return o.defaults.get(S.key);case"selector_family":case"readonly_selector_family":{if(o.defaults.has(S.key))return o.defaults.get(t.family.key);const F=u(S,o).default(T);return o.defaults.set(S.key,F),F}case"molecule_family":throw new Sn(S,T,o)}}switch(t.type){case"atom":case"mutable_atom":case"selector":case"readonly_selector":return un(u(t,o),o);case"molecule":return u(t,o).instance}}class Dt{n;type="molecule";stringKey;family;_dependsOn;get dependsOn(){if(this.family)return this.family.dependsOn;return this._dependsOn}subject=new s;tokens=new Map;above=new Map;below=new Map;joins=new Map;instance;constructor(o,n,t){this.key=n;if(this.stringKey=e(n),t)this.family=t,this._dependsOn=t.dependsOn;if(o)for(let S of o)this.above.set(S.stringKey,S)}}function XF(o){return o[0].toUpperCase()+o.slice(1)}function vn(o,n,t,S,...f){const T=sM(o),M=D(o),F=e(S);M.moleculeInProgress=F;const k=Array.isArray(n)?n:[n],A=k.map((V)=>{if(V instanceof Dt)return V;const m=e(V.key),j=o.molecules.get(m);if(!j)throw new Error(`Molecule ${m} not found in store "${o.config.name}"`);return j}),$=new Dt(A,S,t);M.molecules.set(F,$);for(let V of A)V.below.set($.stringKey,$);const O={get:(...V)=>$o(D(T),...V),set:(...V)=>{Uo(D(T),...V)},seek:(V,m)=>Go(D(T),V,m),json:(V)=>Lo(D(T),V),run:(V,m=zt())=>dn(V,m,D(o)),make:(V,m,j,...r)=>vn(D(T),V,m,j,...r),dispose:(V)=>{uo(D(T),V)},env:()=>sS(D(T)),bond:(V,m)=>{if(V.type==="join"){const{as:j}=m,r=$S(V,T);r.molecules.set(F,$),$.joins.set(V.key,r);const i=K.subject.subscribe(`join:${V.key}-${F}`,(_)=>{if(_.type==="molecule_disposal"){if(e(_.token.key)===F)i(),r.molecules.delete(F)}});if(j===null)return;const X=V.a===j?V.b:V.a,w=wF(V,S),z=w[`${X}KeysOf${XF(j)}`],B=w[`${X}EntriesOf${XF(j)}`];let N={relatedKeys:z};if(B)N=Object.assign(N,{relatedEntries:B});return N}return zn($,u(V,T),D(T))},claim:(V,m)=>{const{exclusive:j}=m,r=D(o).molecules.get(e(V.key));if(r)if(j){for(let i of r.above.values())i.below.delete(r.stringKey);r.above.clear(),r.above.set($.stringKey,$),$.below.set(r.stringKey,r)}else r.above.set($.stringKey,$),$.below.set(r.stringKey,r)},spawn:(V,m,...j)=>vn(D(o),[$],u(V,o),m,...j)},K=u(t,o),G=K.new;$.instance=new G(O,S,...f);const I={type:"molecule",key:S,family:t},H={type:"molecule_creation",subType:"classic",token:I,family:t,context:k,params:f};if(Vo(M))K.subject.next(H);else if(ko(M)&&M.on.transactionApplying.state===null)M.transactionMeta.update.updates.push(H);return M.moleculeInProgress=null,I}function JT(o,n,t){switch(n){case"newValue":{YF(o,t);break}case"oldValue":{uo(t,o.token);break}}}function yT(o,n,t){switch(n){case"newValue":{uo(t,o.token);break}case"oldValue":{YF(o,t),t.valueMap.set(o.token.key,o.value);break}}}function YF(o,n){const{family:t}=o.token;if(t){const S=n.families.get(t.key);if(S)Jo(n,S,co(t.subKey))}}function RT(o,n,t){switch(n){case"newValue":switch(o.subType){case"classic":vn(t,o.context,o.family,o.token.key,...o.params);break;case"modern":FT(t,o.provenance,o.key);break}break;case"oldValue":switch(o.subType){case"classic":uo(t,o.token);break;case"modern":AS(t,o.key);break}break}}function OT(o,n,t){switch(n){case"newValue":switch(o.subType){case"classic":uo(t,o.token);break;case"modern":AS(t,o.key);break}break;case"oldValue":switch(o.subType){case"classic":{const S=vn(t,o.context,o.family,o.token.key);for(let[f,T]of o.values){const M=`${f}(${e(S.key)})`,F=u(S,t),k=F.tokens.has(M),A=t.families.get(f);if(A&&!k)zn(F,A,t);t.valueMap.set(M,T)}}break;case"modern":{FT(t,o.provenance,o.key);for(let[S,f]of o.values){const T=t.families.get(S);if(T){Jo(t,T,o.key);const M=`${S}(${e(o.key)})`;t.valueMap.set(M,f)}}}}break}}function of(o,n,t){const S=o==="newValue"?n.updates:[...n.updates].reverse();for(let f of S)switch(f.type){case"atom_update":case"selector_update":eS(o,f,t);break;case"state_creation":JT(f,o,t);break;case"state_disposal":yT(f,o,t);break;case"molecule_creation":RT(f,o,t);break;case"molecule_disposal":OT(f,o,t);break;case"transaction_update":of(o,f,t);break}}function EF(o,n,t){if(Vo(t)&&o)t.transactionMeta.epoch.set(o,n)}function GF(o,n,t){if(!Vo(t))return;const f=t.transactionMeta.actionContinuities.getRelatedKey(o);if(f!==void 0)t.transactionMeta.epoch.set(f,n)}var zF=(o,n)=>{const t=D(n),{parent:S}=t;if(S===null||!ko(t)||t.transactionMeta?.phase!=="building"){n.logger.warn("\uD83D\uDC1E","transaction","???","applyTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}t.transactionMeta.phase="applying",t.transactionMeta.update.output=o,S.child=null,S.on.transactionApplying.next(t.transactionMeta);const{updates:f}=t.transactionMeta.update;if(n.logger.info("\uD83D\uDEC4","transaction",t.transactionMeta.update.key,`Applying transaction with ${f.length} updates:`,f),of("newValue",t.transactionMeta.update,S),Vo(S))GF(t.transactionMeta.update.key,t.transactionMeta.update.epoch,S),u({key:t.transactionMeta.update.key,type:"transaction"},n)?.subject.next(t.transactionMeta.update),n.logger.info("\uD83D\uDEEC","transaction",t.transactionMeta.update.key,"Finished applying transaction.");else if(ko(S))S.transactionMeta.update.updates.push(t.transactionMeta.update);S.on.transactionApplying.next(null)};function HF(o,n,t){if(!Vo(t))return;const{epoch:f,actionContinuities:T}=t.transactionMeta;if(T.set(o,n),!f.has(o))f.set(o,-1)}class On extends Map{o;deleted=new Set;constructor(o){super();this.source=o}get(o){if(super.has(o))return super.get(o);if(!this.deleted.has(o)&&this.source.has(o))return this.source.get(o);return}set(o,n){return this.deleted.delete(o),super.set(o,n)}hasOwn(o){return super.has(o)}has(o){return!this.deleted.has(o)&&(super.has(o)||this.source.has(o))}delete(o){return this.deleted.add(o),super.delete(o)}}var mF=(o,n,t,S)=>{const f=D(t),T={parent:f,child:null,on:f.on,loggers:f.loggers,logger:f.logger,config:f.config,atoms:new On(f.atoms),atomsThatAreDefault:new Set(f.atomsThatAreDefault),families:new On(f.families),operation:{open:!1},readonlySelectors:new On(f.readonlySelectors),timelines:new On(f.timelines),timelineTopics:new kn(f.timelineTopics.toJSON()),trackers:new Map,transactions:new On(f.transactions),selectorAtoms:new kn(f.selectorAtoms.toJSON()),selectorGraph:new kn(f.selectorGraph.toJSON(),{makeContentKey:(...A)=>A.sort().join(":")}),selectors:new On(f.selectors),valueMap:new On(f.valueMap),defaults:f.defaults,disposalTraces:t.disposalTraces.copy(),molecules:new On(f.molecules),moleculeFamilies:new On(f.moleculeFamilies),moleculeInProgress:f.moleculeInProgress,miscResources:new On(f.miscResources)},M=QF(o,t),F={phase:"building",update:{type:"transaction_update",key:o,id:S,epoch:M===void 0?Number.NaN:M+1,updates:[],params:n,output:void 0},toolkit:{get:(...A)=>$o(k,...A),set:(...A)=>{Uo(k,...A)},run:(A,$=zt())=>dn(A,$,k),find:(A,$)=>Jo(k,A,$),seek:(A,$)=>Go(k,A,$),json:(A)=>Lo(k,A),make:(A,$,O,...K)=>vn(k,A,$,O,...K),dispose:(...A)=>{uo(k,...A)},env:()=>sS(k)}},k=Object.assign(T,{transactionMeta:F});return f.child=k,t.logger.info("\uD83D\uDEEB","transaction",o,"Building transaction with params:",n),k};function TT(o,n){const t={key:o.key,type:"transaction",run:(T,M)=>{const F=mF(o.key,T,n,M);try{const k=D(n),{toolkit:A}=F.transactionMeta,$=o.do(A,...T);return zF($,k),$}catch(k){throw SF(S),n.logger.warn("\uD83D\uDCA5","transaction",o.key,"caught:",k),k}},install:(T)=>TT(o,T),subject:new s},S=D(n);S.transactions.set(t.key,t);const f=Po(t);return n.on.transactionCreation.next(f),f}function QF(o,n){const t=Vo(n),S=t?n.transactionMeta.actionContinuities.getRelatedKey(o):void 0;return t&&S!==void 0?n.transactionMeta.epoch.get(S):void 0}class nf{_buffer;_index=0;constructor(o){let n;if(typeof o==="number")n=o;else n=o.length;this._buffer=Array.from({length:n})}get buffer(){return this._buffer}get index(){return this._index}add(o){this._buffer[this._index]=o,this._index=(this._index+1)%this._buffer.length}copy(){const o=new nf([...this._buffer]);return o._index=this._index,o}}class DF{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;selectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new kn({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new kn({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...o)=>o.sort().join(":")});trackers=new Map;families=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new kn({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new kn({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new nf(100);molecules=new Map;moleculeFamilies=new Map;moleculeInProgress=null;miscResources=new Map;on={atomCreation:new s,atomDisposal:new s,selectorCreation:new s,selectorDisposal:new s,timelineCreation:new s,transactionCreation:new s,transactionApplying:new nT(null),operationClose:new s,moleculeCreationStart:new s,moleculeCreationDone:new s,moleculeDisposal:new s};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new fT("warn",(o,n,t)=>!t.includes("\uD83D\uDD0D"))];logger={error:(...o)=>{for(let n of this.loggers)n.error(...o)},info:(...o)=>{for(let n of this.loggers)n.info(...o)},warn:(...o)=>{for(let n of this.loggers)n.warn(...o)}};constructor(o,n=null){if(this.config={...n?.config,...o},n!==null){if(this.valueMap=new Map(n?.valueMap),this.operation={...n?.operation},Vo(n))this.transactionMeta={epoch:new Map(n?.transactionMeta.epoch),actionContinuities:new kn(n?.transactionMeta.actionContinuities.toJSON())};for(let[,S]of n.families){if(S.internalRoles?.includes("mutable")||S.internalRoles?.includes("join"))continue;S.install(this)}const t=new Set;for(let[,S]of n.atoms){if(t.has(S.key))continue;if(S.install(this),S.type==="mutable_atom"){const f=Lo(n,S),T=qn(S);t.add(f.key),t.add(T.key)}}for(let[,S]of n.readonlySelectors)S.install(this);for(let[,S]of n.selectors){if(t.has(S.key))continue;S.install(this)}for(let[,S]of n.transactions)S.install(this);for(let[,S]of n.timelines)S.install(this)}}}var Mo={get STORE(){if(!globalThis.ATOM_IO_IMPLICIT_STORE)globalThis.ATOM_IO_IMPLICIT_STORE=new DF({name:"IMPLICIT_STORE",lifespan:"ephemeral"});return globalThis.ATOM_IO_IMPLICIT_STORE}};function u(o,n){let t,S=n;while(S!==null){switch(o.type){case"atom":case"mutable_atom":t=S.atoms.get(o.key);break;case"selector":t=S.selectors.get(o.key);break;case"readonly_selector":t=S.readonlySelectors.get(o.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":t=S.families.get(o.key);break;case"timeline":t=S.timelines.get(o.key);break;case"transaction":t=S.transactions.get(o.key);break;case"molecule":t=S.molecules.get(e(o.key));break;case"molecule_family":t=S.moleculeFamilies.get(o.key);break}if(t)return t;S=S.child}throw new Sn(o,n)}function tf(o,n){let t;t=u(o,n);const{family:S}=o;for(let M of t.joins.values())M.relations.delete(t.key),M.molecules.delete(t.stringKey);const f=[];for(let M of t.above.values())f.push(Po(M));const T=[];for(let M of t.tokens.values()){const F=M.family;T.push([F.key,n.valueMap.get(M.key)])}if(S){const M=u(S,n),F={type:"molecule_disposal",subType:"classic",token:o,family:S,context:f,values:T};if(o.family)F.family=o.family;for(let A of t.tokens.values())uo(n,A);for(let A of t.below.values())if(A.dependsOn==="all")tf(A,n);else if(A.above.delete(t.stringKey),A.above.size===0)tf(A,n);if(t.below.clear(),ko(n)&&n.transactionMeta.phase==="building")n.transactionMeta.update.updates.push(F);else M.subject.next(F);n.molecules.delete(t.stringKey)}for(let M of t.above.values())M.below.delete(t.stringKey)}function xn(o,n,t){const S=o.families.get(n.key);if(S===void 0)throw new Sn(n,o);const f=S(t),T=D(o);if(f.family&&T.moleculeInProgress===null){if(Vo(T))switch(f.type){case"atom":case"mutable_atom":o.on.atomCreation.next(f);break;case"selector":case"readonly_selector":o.on.selectorCreation.next(f);break}else if(ko(T)&&T.on.transactionApplying.state===null)T.transactionMeta.update.updates.push({type:"state_creation",token:f})}return f}function Go(o,n,t){const S=e(t),f=`${n.key}(${S})`,T=D(o);let M;switch(n.type){case"atom_family":case"mutable_atom_family":M=T.atoms.get(f);break;case"selector_family":M=T.selectors.get(f);break;case"readonly_selector_family":M=T.readonlySelectors.get(f);break;case"molecule_family":M=T.molecules.get(e(t))}if(M)return Po(M);return M}function Jo(o,n,t){let S=Go(o,n,t);if(S)return S;const f=o.molecules.get(e(t));if(f)return zn(f,n,o);if(o.config.lifespan==="immortal"){const T=Ht(n,t);return o.logger.error("\u274C",T.type,T.key,`was not found in store "${o.config.name}"; returned a counterfeit token.`),T}return S=xn(o,n,t),S}function uo(o,...n){let t,S;if(n.length===1)t=n[0],S=t.key;else{const T=n[0],M=n[1];t=T.type==="molecule_family"?Go(o,T,M)??Ht(T,M):Jo(o,T,M)}try{u(t,o)}catch(T){const M=o.disposalTraces.buffer.find((F)=>F?.key===t.key);o.logger.error("\u274C",t.type,t.key,`could not be disposed because it was not found in the store "${o.config.name}".`,M?`\n This state was most recently disposed\n${M.trace}`:"No previous disposal trace was found.");return}switch(t.type){case"atom":case"mutable_atom":WT(t,o);break;case"selector":case"readonly_selector":UF(t,o);break;case"molecule":tf(t,o);break}const{stack:f}=new Error;if(f){const T=f?.split("\n")?.slice(3)?.join("\n");o.disposalTraces.add({key:t.key,trace:T})}}var Sf=(o,n)=>D(n).atoms.has(o),Hy=(o,n)=>D(n).selectors.has(o),my=(o,n)=>D(n).readonlySelectors.has(o),VF=(o,n)=>Sf(o,n)||Hy(o,n)||my(o,n);var ff=(o,n)=>{return D(n).selectorGraph.getRelationEntries({downstreamSelectorKey:o}).filter(([S,{source:f}])=>f!==o).map(([S,{source:f}])=>f).filter((S)=>VF(S,n))};var _T=(o,n,t)=>{const S=[],f=ff(o,t);while(f.length>0){const T=f.shift();if(n.has(T))continue;if(n.add(T),!Sf(T,t))f.push(...ff(T,t));else if(!S.includes(T))S.push(T)}return S},rF=(o,n)=>{const t=o.key,S=ff(t,n),f=new Set;return S.flatMap((T)=>Sf(T,n)?T:_T(T,f,n))};var CF=(o,n,t,S)=>{const f=D(S);if(n.type==="atom"||n.type==="mutable_atom")f.selectorAtoms.set({selectorKey:o,atomKey:n.key}),S.logger.info("\uD83D\uDD0D","selector",o,`discovers root atom "${n.key}"`);else{const T=_T(n.key,t,S);S.logger.info("\uD83D\uDD0D","selector",o,`discovers root atoms: [ ${T.map((M)=>`"${M}"`).join(", ")} ]`);for(let M of T)f.selectorAtoms=f.selectorAtoms.set({selectorKey:o,atomKey:M})}t.add(n.key)};var Tf=(o,n,t)=>({get:(...S)=>{const f=D(t);let T;if(S.length===2){const[k,A]=S;switch(k.type){case"molecule_family":return $o(t,k,A);default:if(t.config.lifespan==="ephemeral")T=Jo(t,k,A);else{const $=Go(t,k,A);if($)T=$;else throw new Sn(k,A,t)}}}else[T]=S;if(T.type==="molecule")return $o(t,T);const M=u(T,t),F=un(M,t);return t.logger.info("\uD83D\uDD0C","selector",o,`registers dependency ( "${T.key}" =`,F,")"),f.selectorGraph.set({upstreamSelectorKey:T.key,downstreamSelectorKey:o},{source:T.key}),CF(o,T,n,t),F},set:(...S)=>{let f,T;if(S.length===2)f=S[0],T=S[1];else{const k=S[0],A=S[1];T=S[2];const $=t.config.lifespan==="ephemeral"?Jo(t,k,A):Go(t,k,A);if(!$)throw new Sn(k,A,t);f=$}const M=D(t),F=u(f,M);gS(F,T,M)},find:(S,f)=>Jo(t,S,f),seek:(S,f)=>Go(t,S,f),json:(S)=>Lo(t,S)});var fS=(o,n,t)=>{const S=D(o),f=new s,T=new Set,{get:M,find:F,seek:k,json:A}=Tf(n.key,T,S),$=()=>{const I=n.get({get:M,find:F,seek:k,json:A});return Rn(n.key,I,f,D(o)),T.clear(),I},O={...n,subject:f,install:(I)=>fS(I,n,t),get:$,type:"readonly_selector",...t&&{family:t}};S.readonlySelectors.set(n.key,O);const K=$();o.logger.info("\u2728",O.type,O.key,"=",K);const G={key:n.key,type:"readonly_selector"};if(t)G.family=t;return G};var JS=(o,n,t)=>{const S=D(o),f=new s,T=new Set,M=Tf(n.key,T,S),{find:F,get:k,seek:A,json:$}=M,O={find:F,get:k,seek:A,json:$},K=(m=n.get,j=D(o))=>{const r=m(O);return Rn(n.key,r,f,j),T.clear(),r},I={...n,subject:f,install:(m)=>JS(m,n,t),get:K,set:(m)=>{const j=D(o),r=K(n.get,j),i=PS(m)(r);if(o.logger.info("\uD83D\uDCDD","selector",n.key,"set (",r,"->",i,")"),Rn(n.key,i,f,j),Qt(j,n.key),Vo(j))f.next({newValue:i,oldValue:r});n.set(M,i)},type:"selector",...t&&{family:t}};S.selectors.set(n.key,I);const H=K();o.logger.info("\u2728",I.type,I.key,"=",H);const V={key:n.key,type:"selector"};if(t)V.family=t;return V};function En(o,n){if("set"in n){const f=JS(o,n,void 0);return o.on.selectorCreation.next(f),f}const S=fS(o,n,void 0);return o.on.selectorCreation.next(S),S}function UF(o,n){const t=D(n),{key:S}=o,f=u(o,t);if(!f.family)n.logger.error("\u274C","selector",S,"Standalone selectors cannot be disposed.");else{const T=t.molecules.get(f.family.subKey);if(T)T.tokens.delete(S);switch(o.type){case"selector":t.selectors.delete(S),u({key:f.family.key,type:"selector_family"},n).subject.next({type:"state_disposal",token:o});break;case"readonly_selector":t.readonlySelectors.delete(S),u({key:f.family.key,type:"readonly_selector_family"},n).subject.next({type:"state_disposal",token:o});break}if(t.valueMap.delete(S),t.selectorAtoms.delete(S),t.selectorGraph.delete(S),n.logger.info("\uD83D\uDD25",o.type,S,"deleted"),ko(t)&&t.transactionMeta.phase==="building")t.transactionMeta.update.updates.push({type:"state_disposal",token:o});else n.on.selectorDisposal.next(o)}}function MS(o,n,t){const S={key:n.key,type:"selector_family"},f=o.families.get(n.key);if(f)o.logger.error("\u2757","selector_family",n.key,`Overwriting an existing ${Gn(f)} "${f.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const T=new s,F=Object.assign((k)=>{const A=e(k),$={key:n.key,subKey:A},O=`${n.key}(${A})`,K=D(o),G=JS(K,{key:O,get:n.get(k),set:n.set(k)},$);return T.next({type:"state_creation",token:G}),G},S,{internalRoles:t,subject:T,install:(k)=>MS(k,n),default:(k)=>{return n.get(k)({get:(...$)=>$o(o,...$),find:($,O)=>Jo(o,$,O),seek:($,O)=>Go(o,$,O),json:($)=>Lo(o,$)})}});return o.families.set(n.key,F),S}function LF(o,n,t=Mo.STORE){const S=MS(t,{key:`${o.key}:JSON`,get:(T)=>({seek:M,get:F})=>{const k=M(o,T);if(k)return n.toJson(F(k));const A=e(T),$=t.molecules.get(A);if($){const K=zn($,o,t);return n.toJson(F(K))}if(t.config.lifespan==="immortal")throw new Error(`No molecule found for key "${A}"`);const O=xn(t,o,T);return n.toJson(F(O))},set:(T)=>({seek:M,set:F},k)=>{const A=M(o,T);if(A)F(A,n.fromJson(k));else{const $=e(T),O=t.molecules.get($);if(O){const K=zn(O,o,t);F(K,n.fromJson(k))}else{if(t.config.lifespan==="immortal")throw new Error(`No molecule found for key "${$}"`);F(xn(t,o,T),n.fromJson(k))}}}},["mutable","json"]);return u(o,t).subject.subscribe(`store=${t.config.name}::json-selector-family`,(T)=>{if(T.token.family)Go(t,S,co(T.token.family.subKey))}),S}var co=(o)=>JSON.parse(o),e=(o)=>JSON.stringify(o),hK=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var IF=(o,n)=>{const t=D(n);if(t.operation.open)return t.operation.prev.get(o.key);return t.valueMap.get(o.key)};var XT=(o,n)=>{const t=D(n);return rF(o,n).map((f)=>{const T=t.atoms.get(f);if(T===void 0)throw new Error(`Atom "${f}", a dependency of selector "${o.key}", not found in store "${n.config.name}".`);return T.subject.subscribe(`${o.type}:${o.key}`,(M)=>{n.logger.info("\uD83D\uDCE2",o.type,o.key,"root",f,"went",M.oldValue,"->",M.newValue);const F=IF(o,t),k=un(o,t);n.logger.info("\u2728",o.type,o.key,"went",F,"->",k),o.subject.next({newValue:k,oldValue:F})})})};function ao(o,n,t,S){function f(O){if(S.operation.open){const K=S.on.operationClose.subscribe(`state subscription ${t}`,()=>{K(),n(O)})}else n(O)}const T=u(o,S);S.logger.info("\uD83D\uDC40",T.type,T.key,`Adding subscription "${t}"`);const M=T.type==="selector"||T.type==="readonly_selector";let F=null,k=f;if(M)F=XT(T,S),k=(O)=>{if(F)F.length=0,F.push(...XT(T,S));f(O)};const A=T.subject.subscribe(t,k);return()=>{if(S.logger.info("\uD83D\uDE48",T.type,T.key,`Removing subscription "${t}"`),A(),F)for(let O of F)O()}}var wT=(o,n,t,S)=>{const f=u(o,S);S.logger.info("\uD83D\uDC40","timeline",o.key,`Adding subscription "${t}"`);const T=f.subject.subscribe(t,n);return()=>{S.logger.info("\uD83D\uDE48","timeline",o.key,`Removing subscription "${t}" from timeline`),T()}};var KT=(o,n,t,S)=>{const f=u(o,S);S.logger.info("\uD83D\uDC40","transaction",o.key,`Adding subscription "${t}"`);const T=f.subject.subscribe(t,n);return()=>{S.logger.info("\uD83D\uDE48","transaction",o.key,`Removing subscription "${t}"`),T()}};class an{Update;initializeState(o,n){const t=`*${o.key}`;n.atoms.delete(t),n.valueMap.delete(t);const S=o.family?{key:`*${o.family.key}`,subKey:o.family.subKey}:void 0,f=tn(n,{key:t,default:null},S);if(n.parent?.valueMap.has(t)){const T=n.parent.valueMap.get(t);n.valueMap.set(t,T)}return f}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(o,n,t){const S=`tracker:${t.config.name}:${ko(t)?t.transactionMeta.update.key:"main"}:${o.key}`,f=$o(t,o);this.unsubscribeFromInnerValue=f.subscribe(S,(T)=>{Uo(t,n,T)}),this.unsubscribeFromState=ao(o,(T)=>{if(T.newValue!==T.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=T.newValue.subscribe(S,(M)=>{Uo(t,n,M)})},S,t)}updateCore(o,n,t){const S=`tracker:${t.config.name}:${ko(t)?t.transactionMeta.update.key:"main"}:${o.key}`;ao(n,({newValue:f,oldValue:T})=>{const M=t.timelineTopics.getRelatedKey(n.key);if(M){if(t.timelines.get(M)?.timeTraveling){const A=wT({key:M,type:"timeline"},($)=>{A(),Uo(t,o,(O)=>{if($==="redo"&&f)O.do(f);else if($==="undo"&&T)O.undo(T);return O})},S,t);return}}const F=t.on.operationClose.subscribe(S,()=>{F();const k=$o(t,o),A=f===null?-1:k.getUpdateNumber(f),$=A-k.cacheUpdateNumber;if(f&&$===1)Uo(t,o,(O)=>(O.do(f),O));else t.logger.info("\u274C","mutable_atom",o.key,`could not be updated. Expected update number ${k.cacheUpdateNumber+1}, but got ${A}`)})},S,t)}mutableState;latestUpdateState;dispose;constructor(o,n){this.mutableState=o;const t=D(n);this.latestUpdateState=this.initializeState(o,t),this.observeCore(o,this.latestUpdateState,t),this.updateCore(o,this.latestUpdateState,t),t.trackers.set(o.key,this),this.dispose=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),t.trackers.delete(o.key)}}}function yS(o,n,t){o.logger.info("\uD83D\uDD28","atom",n.key,`creating in store "${o.config.name}"`);const S=D(o),f=S.atoms.get(n.key);if(f&&f.type==="mutable_atom")return o.logger.error("\u274C","atom",n.key,"Tried to create atom, but it already exists in the store."),Po(f);const T=new s,M={...n,type:"mutable_atom",install:(A)=>{return A.logger.info("\uD83D\uDEE0\uFE0F","atom",n.key,`installing in store "${A.config.name}"`),yS(A,n,t)},subject:T};if(t)M.family=t;const F=n.default();S.atoms.set(M.key,M),Mf(n.key,o),Rn(n.key,F,T,S);const k=Po(M);if(n.effects){let A=0;const $=[];for(let O of n.effects){const K=O({setSelf:(G)=>{Uo(o,k,G)},onSet:(G)=>ao(k,G,`effect[${A}]`,o)});if(K)$.push(K);++A}M.cleanup=()=>{for(let O of $)O()}}if(new an(k,o),!t)aM(k,n,o);return k}class YT{Update;latestUpdateAtoms;mutableAtoms;constructor(o,n){const t=jn(n,{key:`*${o.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=u(t,n),this.mutableAtoms=o,this.mutableAtoms.subject.subscribe(`store=${n.config.name}::tracker-atom-family`,(S)=>{if(S.token.family){const f=co(S.token.family.subKey);Go(n,this.latestUpdateAtoms,f),new an(S.token,n)}}),this.latestUpdateAtoms.subject.subscribe(`store=${n.config.name}::tracker-atom-family`,(S)=>{if(S.token.family){const f=co(S.token.family.subKey),T=Go(n,this.mutableAtoms,f);if(T)new an(T,n)}})}}function SS(o,n,t){const S={key:n.key,type:"mutable_atom_family"},f=o.families.get(n.key);if(f)o.logger.error("\u2757","mutable_atom_family",n.key,`Overwriting an existing ${Gn(f)} "${f.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const T=new s,F=Object.assign((k)=>{const A=e(k),$={key:n.key,subKey:A},O=`${n.key}(${A})`,K=D(o),G={key:O,default:()=>n.default(k),toJson:n.toJson,fromJson:n.fromJson,mutable:!0};if(n.effects)G.effects=n.effects(k);const I=yS(K,G,$);return T.next({type:"state_creation",token:I}),I},S,{subject:T,install:(k)=>SS(k,n),toJson:n.toJson,fromJson:n.fromJson,internalRoles:t});return o.families.set(n.key,F),LF(F,n,o),new YT(F,o),S}var AT=(o,n)=>{const t=D(n),S=`${o.key}:JSON`;return t.families.get(S)};var Lo=(o,n)=>{if(n.family){const S=D(o),T={key:`${n.family.key}:JSON`,type:"selector_family"},M=u(T,S),F=JSON.parse(n.family.subKey);return Jo(o,M,F)}return{type:"selector",key:`${n.key}:JSON`}};var qn=(o)=>{const t={type:"atom",key:`*${o.key}`};if(o.family)t.family={key:`*${o.family.key}`,subKey:o.family.subKey};return t};function JF(o){return typeof o==="object"&&o!==null&&"do"in o&&"undo"in o&&"subscribe"in o}function kS(o,n,t){const S=n.valueMap.get(o.key),f=t.valueMap.get(o.key);if(S===f){if(S===void 0)return typeof o.default==="function"?o.default():o.default;n.logger.info("\uD83D\uDCC3","atom",o.key,"copying");const T=o.toJson(S),M=o.fromJson(T);return t.valueMap.set(o.key,M),new an(o,n),M}return f}function Rn(o,n,t,S){const f=S.valueMap.get(o);if(f instanceof tS)f.use(n);if(n instanceof Promise){const T=new tS(n);return S.valueMap.set(o,T),T.then((M)=>{Rn(o,M,t,S),t.next({newValue:M,oldValue:T})}).catch((M)=>{S.logger.error("\uD83D\uDCA5","state",o,"rejected:",M)}),T}return S.valueMap.set(o,n),n}var fF=(o,n)=>{let t=n.valueMap.get(o.key);if(o.type==="mutable_atom"&&ko(n)){const{parent:S}=n;t=kS(o,S,n)}return t},AF=(o,n)=>{const t=n.valueMap.get(o);if(t instanceof tS){const S=t,f=n.selectors.get(o)??n.readonlySelectors.get(o);if(f)S.use(f.get());return}if(n.operation.open)n.operation.prev.set(o,t);n.valueMap.delete(o),n.logger.info("\uD83D\uDDD1","state",o,"evicted")};var RF=(o,n)=>{return D(n).atomsThatAreDefault.has(o)},Mf=(o,n)=>{const t=D(n);t.atomsThatAreDefault=new Set(t.atomsThatAreDefault).add(o)},OF=(o,n)=>{const t=D(n);t.atomsThatAreDefault=new Set(D(n).atomsThatAreDefault),t.atomsThatAreDefault.delete(o)};function tn(o,n,t){o.logger.info("\uD83D\uDD28","atom",n.key,`creating in store "${o.config.name}"`);const S=D(o),f=S.atoms.get(n.key);if(f&&f.type==="atom")return o.logger.error("\u274C","atom",n.key,"Tried to create atom, but it already exists in the store."),Po(f);const T=new s,M={...n,type:"atom",install:(A)=>{return A.logger.info("\uD83D\uDEE0\uFE0F","atom",n.key,`installing in store "${A.config.name}"`),tn(A,n,t)},subject:T};if(t)M.family=t;let F=n.default;if(n.default instanceof Function)F=n.default();S.atoms.set(M.key,M),Mf(n.key,o),Rn(n.key,F,T,S);const k=Po(M);if(n.effects){let A=0;const $=[];for(let O of n.effects){const K=O({setSelf:(G)=>{Uo(o,k,G)},onSet:(G)=>ao(k,G,`effect[${A}]`,o)});if(K)$.push(K);++A}M.cleanup=()=>{for(let O of $)O()}}return k}function nF(o,n){if("mutable"in n){const f=yS(o,n,void 0);return o.on.atomCreation.next(f),f}const S=tn(o,n,void 0);return o.on.atomCreation.next(S),S}function WT(o,n){const t=D(n),{key:S}=o,f=u(o,t);if(!f.family)n.logger.error("\u274C","atom",S,"Standalone atoms cannot be disposed.");else{f.cleanup?.();const T=n.valueMap.get(f.key);u({key:f.family.key,type:"atom_family"},n).subject.next({type:"state_disposal",token:o,value:T});const F=t.molecules.get(f.family.subKey);if(F)F.tokens.delete(S);if(t.atoms.delete(S),t.valueMap.delete(S),t.selectorAtoms.delete(S),t.atomsThatAreDefault.delete(S),n.timelineTopics.delete(S),o.type==="mutable_atom"){const k=qn(o);WT(k,n),n.trackers.delete(S)}if(n.logger.info("\uD83D\uDD25","atom",S,"deleted"),ko(t)&&t.transactionMeta.phase==="building")t.transactionMeta.update.updates.push({type:"state_disposal",token:o});else n.on.atomDisposal.next(o)}}var ET=(o)=>{const n=tn(o,{key:"\uD83D\uDD0D Atom Token Index (Internal)",default:()=>{const t=new Map;for(let[S,f]of o.atoms)if(!S.includes("\uD83D\uDD0D")){const T=Po(f);if(f.family){let M=t.get(f.family.key);if(!M||!("familyMembers"in M))M={key:f.family.key,familyMembers:new Map},t.set(f.family.key,M);M.familyMembers.set(f.family.subKey,T)}else t.set(S,T)}return t},effects:[({setSelf:t})=>{o.on.atomCreation.subscribe("introspection",(S)=>{if(S.key.includes("\uD83D\uDD0D"))return;t((f)=>{if(S.family){const{key:T,subKey:M}=S.family;let F=f.get(T);if(F===void 0||!("familyMembers"in F))F={key:T,familyMembers:new Map},f.set(T,F);F.familyMembers.set(M,S)}else f.set(S.key,S);return f})}),o.on.atomDisposal.subscribe("introspection",(S)=>{t((f)=>{if(S.family){const{key:T,subKey:M}=S.family,F=f.get(T);if(F&&"familyMembers"in F){if(F.familyMembers.delete(M),F.familyMembers.size===0)f.delete(T)}}else f.delete(S.key);return f})})}]},void 0);return En(o,{key:"\uD83D\uDD0D Atom Token Index",get:({get:t})=>t(n)})};var GT=(o)=>{const n=tn(o,{key:"\uD83D\uDD0D Selector Token Index (Internal)",default:()=>{const t=new Map;for(let S of[o.readonlySelectors,o.selectors])for(let[f,T]of S)if(!f.includes("\uD83D\uDD0D")){const M=Po(T);if(T.family){let F=t.get(T.family.key);if(!F||!("familyMembers"in F))F={key:T.family.key,familyMembers:new Map},t.set(T.family.key,F);F.familyMembers.set(T.family.subKey,M)}else t.set(f,M)}return t},effects:[({setSelf:t})=>{o.on.selectorCreation.subscribe("introspection",(S)=>{if(S.key.includes("\uD83D\uDD0D"))return;t((f)=>{if(S.family){const{key:T,subKey:M}=S.family;let F=f.get(T);if(F===void 0||!("familyMembers"in F))F={key:T,familyMembers:new Map},f.set(T,F);F.familyMembers.set(M,S)}else f.set(S.key,S);return f})}),o.on.selectorDisposal.subscribe("introspection",(S)=>{t((f)=>{if(S.family){const{key:T,subKey:M}=S.family,F=f.get(T);if(F&&"familyMembers"in F){if(F.familyMembers.delete(M),F.familyMembers.size===0)f.delete(T)}}else f.delete(S.key);return f})})}]},void 0);return En(o,{key:"\uD83D\uDD0D Selector Token Index",get:({get:t})=>t(n)})};function HT(o){if(!o)return!1;return Object.getPrototypeOf(o)===Object.prototype}class Ff{supported;constructor(o){this.supported=o}refine(o){for(let[n,t]of Object.entries(this.supported))try{if(t(o)===!0&&t!==Boolean)return{type:n,data:o}}catch(S){try{if(o instanceof t)return{type:n,data:o}}catch(f){}}return null}}var zT=new Ff({number:(o)=>typeof o==="number",string:(o)=>typeof o==="string",boolean:(o)=>typeof o==="boolean",null:(o)=>o===null}),mT=new Ff({object:HT,array:(o)=>Array.isArray(o)}),Qy=new Ff({...zT.supported,...mT.supported}),Ut=(o)=>{if(o===void 0)return"undefined";const n=Qy.refine(o);if(n)return n.type;return Object.getPrototypeOf(o).constructor.name};class jF{o;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(o=Mo.STORE){this.store=o;this.atomIndex=ET(this.store),this.selectorIndex=GT(this.store),this.unsubscribeFromAtomCreation=this.store.on.atomCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:n})=>{this.statesCreatedAt.set(n,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromAtomDisposal=this.store.on.atomDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:n})=>{this.statesCreatedAt.delete(n)}),this.unsubscribeFromSelectorCreation=this.store.on.selectorCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:n})=>{this.statesCreatedAt.set(n,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromSelectorDisposal=this.store.on.selectorDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:n})=>{this.statesCreatedAt.delete(n)})}static DEFAULT_LIST_RESOURCES_PARAM={atomFamilies:!0,selectorFamilies:!0};listResources(o=jF.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");const n=tT(this.atomIndex),t=tT(this.selectorIndex),S=[...n.values()].filter((F)=>("familyMembers"in F)),f=[...t.values()].filter((F)=>("familyMembers"in F)),T=performance.now(),M=[];if(o.atomFamilies)for(let F of S){const k=F.familyMembers.values();for(let A of k){const O=this.statesCreatedAt.get(A.key)??this.auditorCreatedAt,K=T-O;M.push([A,K])}}if(o.selectorFamilies)for(let F of f){const k=F.familyMembers.values();for(let A of k){const O=this.statesCreatedAt.get(A.key)??this.auditorCreatedAt,K=T-O;M.push([A,K])}}return M}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}}var QT=(o,n)=>{const t=(S,f)=>{const M=((k,A)=>{const $=n(k,A);if($)return $;return null})(S,f);if(M?.jobComplete??M?.pathComplete)return M;const F=Array.isArray(f)?f.map((k,A)=>[A,k]):HT(f)?Object.entries(f):[];for(let[k,A]of F){const $=t([...S,k],A);if($?.jobComplete)return $}return{}};t([],o)};function Dy(o,n){return{summary:`${o<n?"+":"-"}${Math.abs(o-n)} (${o} \u2192 ${n})`}}function Uy(o,n){return{summary:`${o.length<n.length?"+":"-"}${Math.abs(o.length-n.length)} ("${o}" \u2192 "${n}")`}}function Vy(o,n){return{summary:`${o} \u2192 ${n}`}}function BF(o,n,t){let S="";const f=[],T=[],M=[];return QT(o,(F,k)=>{let A;for(A of F){const $=n[A];if($===void 0)T.push([A,JSON.stringify(k)]);else{const O=t(k,$);if(O.summary!=="No Change")M.push([A,O])}}}),QT(n,(F,k)=>{let A;for(A of F)if(o[A]===void 0)f.push([A,JSON.stringify(k)])}),S=`\uFF5E${M.length} \uFF0B${f.length} \uFF0D${T.length}`,{summary:S,added:f,removed:T,changed:M}}function ry(o,n,t){return BF(o,n,t)}class cF{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(o,n,t){this.leafRefinery=o,this.treeRefinery=n,this.leafDiffers={},this.treeDiffers={};for(let S of Object.keys(o.supported)){const f=t[S];this.leafDiffers[S]=f}for(let S of Object.keys(n.supported)){const f=t[S];this.treeDiffers[S]=f}}diff(o,n){if(o===n)return{summary:"No Change"};const t=this.leafRefinery.refine(o)??this.treeRefinery.refine(o),S=this.leafRefinery.refine(n)??this.treeRefinery.refine(n);if(t!==null&&S!==null){if(t.type===S.type){if(t.type in this.leafDiffers)return this.leafDiffers[t.type](t.data,S.data);if(t.type in this.treeDiffers)return this.treeDiffers[t.type](t.data,S.data,(F,k)=>this.diff(F,k))}}const f=Ut(o),T=Ut(n);if(f===T)return{summary:`${f} \u2192 ${T}`};return{summary:`Type change: ${f} \u2192 ${T}`}}}var dX=new cF(zT,mT,{number:Dy,string:Uy,boolean:Vy,null:()=>({summary:"No Change"}),object:BF,array:ry});class Vt{o;listeners;globalListeners;handleEvent(o,...n){for(let S of this.globalListeners)S(o,...n);const t=this.listeners.get(o);if(t)for(let S of t)S(...n)}id="no_id_retrieved";constructor(o){this.emit=o;this.listeners=new Map,this.globalListeners=new Set}on(o,n){const t=this.listeners.get(o);if(t)t.add(n);else this.listeners.set(o,new Set([n]));return this}onAny(o){return this.globalListeners.add(o),this}off(o,n){const t=this.listeners.get(o);if(t)if(n)t.delete(n);else this.listeners.delete(o);return this}offAny(o){return this.globalListeners.delete(o),this}}class DT extends Vt{o;n;t;incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";handleLog(o){if(Array.isArray(o)){const[n,...t]=o;switch(n){case"i":this.logger.info(this.id,this.key,...t);break;case"w":this.logger.warn(this.id,this.key,...t);break;case"e":this.logger.error(this.id,this.key,...t);break}}}constructor(o,n,t=console){super((S,...f)=>{const T=JSON.stringify([S,...f])+"\x03",M=(F)=>{if(F.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",M)};return this.process.stdin.once("error",M),this.process.stdin.write(T),this});this.process=o;this.key=n;this.logger=t;if(this.process=o,this.process.stdout.on("data",(S)=>{const f=S.toString();if(f==="\u2728")return;this.unprocessedEvents.push(...f.split("\x03"));const T=this.unprocessedEvents.shift();this.incompleteData+=T??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let M=co(this.incompleteData);this.handleEvent(...M);while(this.unprocessedEvents.length>0){const F=this.unprocessedEvents.shift();if(F){if(this.unprocessedEvents.length===0)this.incompleteData=F;M=co(F),this.handleEvent(...M)}}this.incompleteData=""}catch(M){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error(M)}}),this.process.stderr.on("data",(S)=>{const f=S.toString();this.unprocessedLogs.push(...f.split("\x03"));const T=this.unprocessedLogs.shift();this.incompleteLog+=T??"";try{let M=co(this.incompleteLog);this.handleLog(M);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)M=co(this.incompleteLog),this.handleLog(M)}catch(M){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error(M),console.error("\u274C\u274C\u274C\uFE0F")}}),o.pid)this.id=o.pid.toString()}}class bF extends Vt{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(o){super((...n)=>{return this.out.next(n),this});this.id=o,this.in=new s,this.out=new s,this.in.subscribe("socket",(n)=>{this.handleEvent(...n)})}dispose(){for(let o of this.disposalFunctions)o()}}class UT extends Vt{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...o){this.process.stderr.write(e(o.map((n)=>n instanceof bo?`{ ${n.toJSON().members.join(" | ")} }`:n))+"\x03")}logger={info:(...o)=>{this.log("i",...o)},warn:(...o)=>{this.log("w",...o)},error:(...o)=>{this.log("e",...o)}};constructor(){super((o,...n)=>{const t=JSON.stringify([o,...n]);return this.process.stdout.write(t+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(o)=>{const n=o.toString();this.unprocessedEvents.push(...n.split("\x03"));const t=this.unprocessedEvents.shift();this.incompleteData+=t??"";try{const S=co(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",S),this.handleEvent(...S);while(this.unprocessedEvents.length>0){const f=this.unprocessedEvents.shift();if(f){if(this.unprocessedEvents.length===0)this.incompleteData=f;const T=co(f);this.handleEvent(...T)}}this.incompleteData=""}catch(S){if(S instanceof Error)this.logger.error("\u2757",S.message,S.cause,S.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(o)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${o}`)}),process.on("end",()=>{this.logger.info("\uD83D\uDD25",this.id,"ended"),process.exit(0)}),process.on("SIGTERM",()=>{this.logger.error("\uD83D\uDD25",this.id,"terminated"),process.exit(0)}),process.on("SIGINT",()=>{this.logger.error("\uD83D\uDD25",this.id,"interrupted"),process.exit(0)}),process.pid)this.id=process.pid?.toString();this.on("user-joins",(o)=>{this.logger.info("\uD83D\uDC64","user",o,"joined");const n=new bF(`user:${o}`);this.relays.set(o,n),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let t of this.relayServices){const S=t(n);if(S)n.disposalFunctions.push(S)}this.on(`user:${o}`,(...t)=>{n.in.next(t)}),n.out.subscribe("socket",(t)=>{this.emit(...t)})}),this.on("user-leaves",(o)=>{const n=this.relays.get(o);if(this.off(`relay:${o}`),n)n.dispose(),this.relays.delete(o)}),process.stdout.write("\u2728")}relay(o){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(o)}}function E8(o){const{key:n,config:t}=o,S=kf.create(n,t),{actions:f}=S;for(let T of f)HF(n,T.key,Mo.STORE);return EF(n,-1,Mo.STORE),S}class NF extends Map{set(o,n){if(this.has(o))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:o,value:n}),this;return super.set(o,n)}clear(){throw new Error("Cannot clear an InvariantMap")}}class kf{o;type="continuity";globals=[];actions=[];perspectives=[];constructor(o){this.key=o}static existing=new NF;static create(o,n){const t=new kf(o),{type:S,globals:f,actions:T,perspectives:M}=n(t),F={type:S,key:o,globals:f,actions:T,perspectives:M};return kf.existing.set(o,F),F}add(...o){switch(o[0].type){case"atom":case"mutable_atom":this.globals.push(...o);break;case"transaction":this.actions.push(...o);break;case"atom_family":{const[t,S]=o;this.perspectives.push({type:"realtime_perspective",resourceAtoms:t,viewAtoms:S})}break}return this}}var Q8=mt({key:"usersInRoomIndex",mutable:!0,default:()=>new bo,toJson:(o)=>o.toJSON(),fromJson:(o)=>bo.fromJSON(o)}),VT=mt({key:"roomIndex",default:()=>new bo,mutable:!0,toJson:(o)=>o.toJSON(),fromJson:(o)=>bo.fromJSON(o)}),Cy={enteredAtEpoch:0},RS=dS({key:"usersInRooms",between:["room","user"],cardinality:"1:n"},Cy),D8=ZS({key:"usersInMyRoomView",get:(o)=>({find:n})=>{const t=KF(RS);return[n(t,o)]}});import{spawn as Ly}from"child_process";var rT=At({key:"roomArguments",default:["echo",["Hello World!"]]}),hF=ZS({key:"room",get:(o)=>async({get:n,find:t})=>{const S=t(rT,o),f=n(S),[T,M]=f,F=await new Promise((k)=>{const A=Ly(T,M,{env:process.env}),$=(O)=>{if(O.toString()==="\u2728")A.stdout.off("data",$),k(A)};A.stdout.on("data",$)});return new DT(F,o)}});var i8=FS({key:"createRoom",do:({get:o,set:n,find:t},S,f,T)=>{const M=T?[f,T]:[f],F=t(rT,S);n(F,M),n(VT,($)=>$.add(S));const k=t(hF,S);return o(k)}}),v8=FS({key:"joinRoom",do:(o,n,t,S)=>{const f={enteredAtEpoch:S};return aS(RS,(T)=>{T.set({room:n,user:t},f)},o.env().store),f}}),q8=FS({key:"leaveRoom",do:(o,n,t)=>{aS(RS,(S)=>{S.delete({room:n,user:t})},o.env().store)}}),p8=FS({key:"destroyRoom",do:(o,n)=>{aS(RS,(t)=>{t.delete({room:n})},o.env().store),o.set(VT,(t)=>(t.delete(n),t))}});function CT(o,n){return n.map((t)=>{switch(t.type){case"transaction_update":{const S=CT(o,t.updates);return{...t,updates:S}}default:return t}}).filter((t)=>{switch(t.type){case"atom_update":case"selector_update":return o.includes(t.key);case"state_creation":return o.includes(t.token.key);case"molecule_creation":return!0;case"transaction_update":return!0}})}var g8=At({key:"transactionRedactor",default:{occlude:(o)=>o}}),xF=At({key:"unacknowledgedUpdates",default:()=>[]});var iF=At({key:"sockets",default:null}),a8=mt({key:"socketsIndex",mutable:!0,default:()=>new bo,toJson:(o)=>o.toJSON(),fromJson:(o)=>bo.fromJSON(o)}),s8=mt({key:"usersIndex",mutable:!0,default:()=>new bo,toJson:(o)=>o.toJSON(),fromJson:(o)=>bo.fromJSON(o)}),LT=dS({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1"});function $5({socket:o,store:n=Mo.STORE}){return function t(S){let f=o;const T=S.key,M=uS(LT,f.id,n).userKeyOfSocket,F=$o(n,M);if(!F)return n.logger.error("\u274C","continuity",T,`Tried to create a synchronizer for a socket (${f.id}) that is not connected to a user.`),()=>{};const k=uS(LT,F,n).socketKeyOfUser;ao(k,({newValue:m})=>{if(n.logger.info("\uD83D\uDC4B","continuity",T,`seeing ${F} on new socket ${m}`),m===null){n.logger.warn("\u274C","continuity",T,`User (${F}) is not connected to a socket, waiting for them to reappear.`);return}const j=Jo(n,iF,m);f=$o(n,j);for(let i of $)f?.emit(`tx-new:${T}`,i)},`sync-continuity:${T}:${F}`,n);const A=Jo(n,xF,F),$=$o(n,A),O=[],G=(()=>{const m=[];for(let j of S.perspectives){const{viewAtoms:r}=j,i=Jo(n,r,F),X=ao(i,({oldValue:w,newValue:z})=>{const B=w.map((U)=>U.key),N=z.map((U)=>U.key),_=w.filter((U)=>!N.includes(U.key)),c=z.filter((U)=>!B.includes(U.key)).flatMap((U)=>{const l=U.type==="mutable_atom"?Lo(n,U):U,no=$o(n,l);return[l,no]});if(n.logger.info("\uD83D\uDC41","atom",j.resourceAtoms.key,`${F} has a new perspective`,{oldKeys:B,newKeys:N,revealed:c,concealed:_}),c.length>0)f?.emit(`reveal:${T}`,c);if(_.length>0)f?.emit(`conceal:${T}`,_)},`sync-continuity:${T}:${F}:perspective:${j.resourceAtoms.key}`,n);m.push(X)}return()=>{for(let j of m)j()}})(),I=()=>{const m=[];for(let r of S.globals){const i=r.type==="mutable_atom"?Lo(n,r):r,X=$o(n,i);m.push(i,X)}for(let r of S.perspectives){const{viewAtoms:i,resourceAtoms:X}=r,w=Jo(n,i,F),z=$o(n,w);n.logger.info("\uD83D\uDC41","atom",X.key,`${F} can see`,{viewAtoms:i,resourceAtoms:X,userView:z});for(let B of z){const N=B.type==="mutable_atom"?Lo(n,B):B,_=$o(n,N);m.push(N,_)}}const j=Vo(n)?n.transactionMeta.epoch.get(T)??null:null;f?.emit(`continuity-init:${T}`,j,m);for(let r of S.actions){const i=KT(r,(X)=>{try{const w=S.globals.map((N)=>{if(N.type==="atom")return N.key;return qn(N).key}).concat(S.perspectives.flatMap((N)=>{const{viewAtoms:_}=N,c=Jo(n,_,F);return $o(n,c).map((l)=>{return l.type==="mutable_atom"?"*"+l.key:l.key})})),z=CT(w,X.updates),B={...X,updates:z};Uo(n,A,(N)=>{if(B)N.push(B),N.sort((_,c)=>_.epoch-c.epoch);return N}),f?.emit(`tx-new:${T}`,B)}catch(w){if(w instanceof Error)n.logger.error("\u274C","continuity",T,`failed to send update from transaction ${r.key} to ${F}`,w.message)}},`sync-continuity:${T}:${F}`,n);O.push(i)}};f.off(`get:${T}`,I),f.on(`get:${T}`,I);const H=(m)=>{n.logger.info("\uD83D\uDECE\uFE0F","continuity",T,"received",m);const{key:j,id:r}=m,i=`tx-run:${j}:${r}`,X=`${i}:start`,w=`${i}:end`;performance.mark(X);try{dn({type:"transaction",key:j},r,n)(...m.params)}catch(c){if(c instanceof Error)n.logger.error("\u274C","continuity",T,`failed to run transaction ${j} with update ${r}`,c.message)}performance.mark(w);const z=performance.measure(i,X,w);n?.logger.info("\uD83D\uDE80","transaction",j,r,z.duration);const B=`valuesOfCardsView("${F}")`,N=n.selectorAtoms.getRelatedKeys(B),_=n.valueMap.get(B);n.logger.info("\uD83D\uDC41","continuity",T,`seeing ${F} card values`,{valuesOfCardsViewKey:B,rootsOfCardValueView:N,myCardValueView:_})};f.off(`tx-run:${T}`,H),f.on(`tx-run:${T}`,H);const V=(m)=>{if(n.logger.info("\uD83D\uDC4D","continuity",T,`${F} acknowledged epoch ${m}`),$[0]?.epoch===m)Uo(n,A,(r)=>{return r.shift(),r})};return f?.on(`ack:${T}`,V),()=>{for(let m of O)m();f?.off(`ack:${T}`,V),G(),f?.off(`get:${T}`,I),f?.off(`tx-run:${T}`,H)}}}var{file:YJ,serve:b0}=globalThis.Bun;function Y(o,n){if(!o||typeof o!=="object")return!1;if(o instanceof n)return!0;if(!Object.prototype.hasOwnProperty.call(n,y))throw new Error(`Class "${n.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 t=Object.getPrototypeOf(o).constructor;if(t)while(t){if(y in t&&t[y]===n[y])return!0;t=Object.getPrototypeOf(t)}return!1}var y=Symbol.for("drizzle:entityKind"),j5=Symbol.for("drizzle:hasOwnEntityKind");class Xo{constructor(o,n){this.table=o,this.config=n,this.name=n.name,this.keyAsName=n.keyAsName,this.notNull=n.notNull,this.default=n.default,this.defaultFn=n.defaultFn,this.onUpdateFn=n.onUpdateFn,this.hasDefault=n.hasDefault,this.primary=n.primaryKey,this.isUnique=n.isUnique,this.uniqueName=n.uniqueName,this.uniqueType=n.uniqueType,this.dataType=n.dataType,this.columnType=n.columnType,this.generated=n.generated,this.generatedIdentity=n.generatedIdentity}static[y]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(o){return o}mapToDriverValue(o){return o}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class IT{static[y]="ColumnBuilder";config;constructor(o,n,t){this.config={name:o,keyAsName:o==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:n,columnType:t,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(o){return this.config.default=o,this.config.hasDefault=!0,this}$defaultFn(o){return this.config.defaultFn=o,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(o){return this.config.onUpdateFn=o,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(o){if(this.config.name!=="")return;this.config.name=o}}var Hn=Symbol.for("drizzle:Name");class jT{static[y]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(o,n){if(this.reference=()=>{const{name:t,columns:S,foreignColumns:f}=o();return{name:t,columns:S,foreignTable:f[0].table,foreignColumns:f}},n)this._onUpdate=n.onUpdate,this._onDelete=n.onDelete}onUpdate(o){return this._onUpdate=o===void 0?"no action":o,this}onDelete(o){return this._onDelete=o===void 0?"no action":o,this}build(o){return new vF(o,this)}}class vF{constructor(o,n){this.table=o,this.reference=n.reference,this.onUpdate=n._onUpdate,this.onDelete=n._onDelete}static[y]="PgForeignKey";reference;onUpdate;onDelete;getName(){const{name:o,columns:n,foreignColumns:t}=this.reference(),S=n.map((M)=>M.name),f=t.map((M)=>M.name),T=[this.table[Hn],...S,t[0].table[Hn],...f];return o??`${T.join("_")}_fk`}}function Af(o,...n){return o(...n)}function qF(o,n){return`${o[Hn]}_${n.join("_")}_unique`}function pF(o,n,t){for(let S=n;S<o.length;S++){const f=o[S];if(f==="\\"){S++;continue}if(f==='"')return[o.slice(n,S).replace(/\\/g,""),S+1];if(t)continue;if(f===","||f==="}")return[o.slice(n,S).replace(/\\/g,""),S]}return[o.slice(n).replace(/\\/g,""),o.length]}function ZF(o,n=0){const t=[];let S=n,f=!1;while(S<o.length){const T=o[S];if(T===","){if(f||S===n)t.push("");f=!0,S++;continue}if(f=!1,T==="\\"){S+=2;continue}if(T==='"'){const[k,A]=pF(o,S+1,!0);t.push(k),S=A;continue}if(T==="}")return[t,S+1];if(T==="{"){const[k,A]=ZF(o,S+1);t.push(k),S=A;continue}const[M,F]=pF(o,S,!1);t.push(M),S=F}return[t,S]}function PF(o){const[n]=ZF(o,1);return n}function BT(o){return`{${o.map((n)=>{if(Array.isArray(n))return BT(n);if(typeof n==="string")return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`;return`${n}`}).join(",")}}`}class v extends IT{foreignKeyConfigs=[];static[y]="PgColumnBuilder";array(o){return new lF(this.config.name,this,o)}references(o,n={}){return this.foreignKeyConfigs.push({ref:o,actions:n}),this}unique(o,n){return this.config.isUnique=!0,this.config.uniqueName=o,this.config.uniqueType=n?.nulls,this}generatedAlwaysAs(o){return this.config.generated={as:o,type:"always",mode:"stored"},this}buildForeignKeys(o,n){return this.foreignKeyConfigs.map(({ref:t,actions:S})=>{return Af((f,T)=>{const M=new jT(()=>{const F=f();return{columns:[o],foreignColumns:[F]}});if(T.onUpdate)M.onUpdate(T.onUpdate);if(T.onDelete)M.onDelete(T.onDelete);return M.build(n)},t,S)})}buildExtraConfigColumn(o){return new gF(o,this.config)}}class C extends Xo{constructor(o,n){if(!n.uniqueName)n.uniqueName=qF(o,[n.name]);super(o,n);this.table=o}static[y]="PgColumn"}class gF extends C{static[y]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(o){return this.indexConfig.opClass=o,this}}class OS{static[y]="IndexedColumn";constructor(o,n,t,S){this.name=o,this.keyAsName=n,this.type=t,this.indexConfig=S}name;keyAsName;type;indexConfig}class lF extends v{static[y]="PgArrayBuilder";constructor(o,n,t){super(o,"array","PgArray");this.config.baseBuilder=n,this.config.size=t}build(o){const n=this.config.baseBuilder.build(o);return new cT(o,this.config,n)}}class cT extends C{constructor(o,n,t,S){super(o,n);this.baseColumn=t,this.range=S,this.size=n.size}size;static[y]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(o){if(typeof o==="string")o=PF(o);return o.map((n)=>this.baseColumn.mapFromDriverValue(n))}mapToDriverValue(o,n=!1){const t=o.map((S)=>S===null?null:Y(this.baseColumn,cT)?this.baseColumn.mapToDriverValue(S,!0):this.baseColumn.mapToDriverValue(S));if(n)return t;return BT(t)}}function eF(o){return!!o&&typeof o==="function"&&bT in o&&o[bT]===!0}function $f(o,n){return Iy(o,n,void 0)}function Iy(o,n,t){const S=Object.assign((f)=>new dF(f??"",S),{enumName:o,enumValues:n,schema:t,[bT]:!0});return S}var bT=Symbol.for("drizzle:isPgEnum");class dF extends v{static[y]="PgEnumColumnBuilder";constructor(o,n){super(o,"string","PgEnumColumn");this.config.enum=n}build(o){return new uF(o,this.config)}}class uF extends C{static[y]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(o,n){super(o,n);this.enum=n.enum}getSQLType(){return this.enum.enumName}}class xo{static[y]="Subquery";constructor(o,n,t,S=!1){this._={brand:"Subquery",sql:o,selectedFields:n,alias:t,isWith:S}}}class WS extends xo{static[y]="WithSubquery"}var aF="0.35.1";var NT,hT,Wo={startActiveSpan(o,n){if(!NT)return n();if(!hT)hT=NT.trace.getTracer("drizzle-orm",aF);return Af((t,S)=>S.startActiveSpan(o,(f)=>{try{return n(f)}catch(T){throw f.setStatus({code:t.SpanStatusCode.ERROR,message:T instanceof Error?T.message:"Unknown error"}),T}finally{f.end()}}),NT,hT)}};var mo=Symbol.for("drizzle:ViewBaseConfig");function Wn(o){return o[Hn]}function $t(o){return`${o[Jf]??"public"}.${o[Hn]}`}var Jf=Symbol.for("drizzle:Schema"),sF=Symbol.for("drizzle:Columns"),ok=Symbol.for("drizzle:ExtraConfigColumns"),xT=Symbol.for("drizzle:OriginalName"),iT=Symbol.for("drizzle:BaseName"),nk=Symbol.for("drizzle:IsAlias"),tk=Symbol.for("drizzle:ExtraConfigBuilder"),jy=Symbol.for("drizzle:IsDrizzleTable");class h{static[y]="Table";static Symbol={Name:Hn,Schema:Jf,OriginalName:xT,Columns:sF,ExtraConfigColumns:ok,BaseName:iT,IsAlias:nk,ExtraConfigBuilder:tk};[Hn];[xT];[Jf];[sF];[ok];[iT];[nk]=!1;[jy]=!0;[tk]=void 0;constructor(o,n,t){this[Hn]=this[xT]=o,this[Jf]=n,this[iT]=t}}function vT(o){return o!==null&&o!==void 0&&typeof o.getSQL==="function"}function By(o){const n={sql:"",params:[]};for(let t of o)if(n.sql+=t.sql,n.params.push(...t.params),t.typings?.length){if(!n.typings)n.typings=[];n.typings.push(...t.typings)}return n}function Sk(o){return typeof o==="object"&&o!==null&&"mapToDriverValue"in o&&typeof o.mapToDriverValue==="function"}function R(o,...n){const t=[];if(n.length>0||o.length>0&&o[0]!=="")t.push(new No(o[0]));for(let[S,f]of n.entries())t.push(f,new No(o[S+1]));return new q(t)}function qT(o,n){return o.map((t)=>{if(Y(t,sn)){if(!(t.name in n))throw new Error(`No value for placeholder "${t.name}" was provided`);return n[t.name]}if(Y(t,An)&&Y(t.value,sn)){if(!(t.value.name in n))throw new Error(`No value for placeholder "${t.value.name}" was provided`);return t.encoder.mapToDriverValue(n[t.value.name])}return t})}class No{static[y]="StringChunk";value;constructor(o){this.value=Array.isArray(o)?o:[o]}getSQL(){return new q([this])}}class q{constructor(o){this.queryChunks=o}static[y]="SQL";decoder=fk;shouldInlineParams=!1;append(o){return this.queryChunks.push(...o.queryChunks),this}toQuery(o){return Wo.startActiveSpan("drizzle.buildSQL",(n)=>{const t=this.buildQueryFromSourceParams(this.queryChunks,o);return n?.setAttributes({"drizzle.query.text":t.sql,"drizzle.query.params":JSON.stringify(t.params)}),t})}buildQueryFromSourceParams(o,n){const t=Object.assign({},n,{inlineParams:n.inlineParams||this.shouldInlineParams,paramStartIndex:n.paramStartIndex||{value:0}}),{casing:S,escapeName:f,escapeParam:T,prepareTyping:M,inlineParams:F,paramStartIndex:k}=t;return By(o.map((A)=>{if(Y(A,No))return{sql:A.value.join(""),params:[]};if(Y(A,yf))return{sql:f(A.value),params:[]};if(A===void 0)return{sql:"",params:[]};if(Array.isArray(A)){const $=[new No("(")];for(let[O,K]of A.entries())if($.push(K),O<A.length-1)$.push(new No(", "));return $.push(new No(")")),this.buildQueryFromSourceParams($,t)}if(Y(A,q))return this.buildQueryFromSourceParams(A.queryChunks,{...t,inlineParams:F||A.shouldInlineParams});if(Y(A,h)){const $=A[h.Symbol.Schema],O=A[h.Symbol.Name];return{sql:$===void 0?f(O):f($)+"."+f(O),params:[]}}if(Y(A,Xo)){const $=S.getColumnCasing(A);if(n.invokeSource==="indexes")return{sql:f($),params:[]};return{sql:f(A.table[h.Symbol.Name])+"."+f($),params:[]}}if(Y(A,fn)){const $=A[mo].schema,O=A[mo].name;return{sql:$===void 0?f(O):f($)+"."+f(O),params:[]}}if(Y(A,An)){if(Y(A.value,sn))return{sql:T(k.value++,A),params:[A],typings:["none"]};const $=A.value===null?null:A.encoder.mapToDriverValue(A.value);if(Y($,q))return this.buildQueryFromSourceParams([$],t);if(F)return{sql:this.mapInlineParam($,t),params:[]};let O=["none"];if(M)O=[M(A.encoder)];return{sql:T(k.value++,$),params:[$],typings:O}}if(Y(A,sn))return{sql:T(k.value++,A),params:[A],typings:["none"]};if(Y(A,q.Aliased)&&A.fieldAlias!==void 0)return{sql:f(A.fieldAlias),params:[]};if(Y(A,xo)){if(A._.isWith)return{sql:f(A._.alias),params:[]};return this.buildQueryFromSourceParams([new No("("),A._.sql,new No(") "),new yf(A._.alias)],t)}if(eF(A)){if(A.schema)return{sql:f(A.schema)+"."+f(A.enumName),params:[]};return{sql:f(A.enumName),params:[]}}if(vT(A)){if(A.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([A.getSQL()],t);return this.buildQueryFromSourceParams([new No("("),A.getSQL(),new No(")")],t)}if(F)return{sql:this.mapInlineParam(A,t),params:[]};return{sql:T(k.value++,A),params:[A],typings:["none"]}}))}mapInlineParam(o,{escapeString:n}){if(o===null)return"null";if(typeof o==="number"||typeof o==="boolean")return o.toString();if(typeof o==="string")return n(o);if(typeof o==="object"){const t=o.toString();if(t==="[object Object]")return n(JSON.stringify(o));return n(t)}throw new Error("Unexpected param value: "+o)}getSQL(){return this}as(o){if(o===void 0)return this;return new q.Aliased(this,o)}mapWith(o){return this.decoder=typeof o==="function"?{mapFromDriverValue:o}:o,this}inlineParams(){return this.shouldInlineParams=!0,this}if(o){return o?this:void 0}}class yf{constructor(o){this.value=o}static[y]="Name";brand;getSQL(){return new q([this])}}var fk={mapFromDriverValue:(o)=>o},Tk={mapToDriverValue:(o)=>o},GY={...fk,...Tk};class An{constructor(o,n=Tk){this.value=o,this.encoder=n}static[y]="Param";brand;getSQL(){return new q([this])}}((o)=>{function n(){return new q([])}o.empty=n;function t(k){return new q(k)}o.fromList=t;function S(k){return new q([new No(k)])}o.raw=S;function f(k,A){const $=[];for(let[O,K]of k.entries()){if(O>0&&A!==void 0)$.push(A);$.push(K)}return new q($)}o.join=f;function T(k){return new yf(k)}o.identifier=T;function M(k){return new sn(k)}o.placeholder=M;function F(k,A){return new An(k,A)}o.param=F})(R||(R={}));((o)=>{class n{constructor(t,S){this.sql=t,this.fieldAlias=S}static[y]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new n(this.sql,this.fieldAlias)}}o.Aliased=n})(q||(q={}));class sn{constructor(o){this.name=o}static[y]="Placeholder";getSQL(){return new q([this])}}class fn{static[y]="View";[mo];constructor({name:o,schema:n,selectedFields:t,query:S}){this[mo]={name:o,originalName:o,schema:n,selectedFields:t,query:S,isExisting:!S,isAlias:!1}}getSQL(){return new q([this])}}Xo.prototype.getSQL=function(){return new q([this])};h.prototype.getSQL=function(){return new q([this])};xo.prototype.getSQL=function(){return new q([this])};function Rf(o,n){return new Proxy(o,new _S(n,!1))}function Bn(o,n){return new Proxy(o,new rt(new Proxy(o.table,new _S(n,!1))))}function pT(o,n){return new q.Aliased(wS(o.sql,n),o.fieldAlias)}function wS(o,n){return R.join(o.queryChunks.map((t)=>{if(Y(t,Xo))return Bn(t,n);if(Y(t,q))return wS(t,n);if(Y(t,q.Aliased))return pT(t,n);return t}))}class rt{constructor(o){this.table=o}static[y]="ColumnAliasProxyHandler";get(o,n){if(n==="table")return this.table;return o[n]}}class _S{constructor(o,n){this.alias=o,this.replaceOriginalName=n}static[y]="TableAliasProxyHandler";get(o,n){if(n===h.Symbol.IsAlias)return!0;if(n===h.Symbol.Name)return this.alias;if(this.replaceOriginalName&&n===h.Symbol.OriginalName)return this.alias;if(n===mo)return{...o[mo],name:this.alias,isAlias:!0};if(n===h.Symbol.Columns){const S=o[h.Symbol.Columns];if(!S)return S;const f={};return Object.keys(S).map((T)=>{f[T]=new Proxy(S[T],new rt(new Proxy(o,this)))}),f}const t=o[n];if(Y(t,Xo))return new Proxy(t,new rt(new Proxy(o,this)));return t}}class Of extends Error{static[y]="DrizzleError";constructor({message:o,cause:n}){super(o);this.name="DrizzleError",this.cause=n}}class ZT extends Of{static[y]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}function Tn(o,n){if(Sk(n)&&!vT(o)&&!Y(o,An)&&!Y(o,sn)&&!Y(o,Xo)&&!Y(o,h)&&!Y(o,fn))return new An(o,n);return o}function KS(...o){const n=o.filter((t)=>t!==void 0);if(n.length===0)return;if(n.length===1)return new q(n);return new q([new No("("),R.join(n,new No(" and ")),new No(")")])}function Fk(...o){const n=o.filter((t)=>t!==void 0);if(n.length===0)return;if(n.length===1)return new q(n);return new q([new No("("),R.join(n,new No(" or ")),new No(")")])}function kk(o){return R`not ${o}`}function Rk(o,n){if(Array.isArray(n)){if(n.length===0)return R`false`;return R`${o} in ${n.map((t)=>Tn(t,o))}`}return R`${o} in ${Tn(n,o)}`}function Ok(o,n){if(Array.isArray(n)){if(n.length===0)return R`true`;return R`${o} not in ${n.map((t)=>Tn(t,o))}`}return R`${o} not in ${Tn(n,o)}`}function Wk(o){return R`${o} is null`}function _k(o){return R`${o} is not null`}function wk(o){return R`exists ${o}`}function Kk(o){return R`not exists ${o}`}function Xk(o,n,t){return R`${o} between ${Tn(n,o)} and ${Tn(t,o)}`}function Yk(o,n,t){return R`${o} not between ${Tn(n,o)} and ${Tn(t,o)}`}function Ek(o,n){return R`${o} like ${n}`}function Gk(o,n){return R`${o} not like ${n}`}function zk(o,n){return R`${o} ilike ${n}`}function Hk(o,n){return R`${o} not ilike ${n}`}var Ct=(o,n)=>{return R`${o} = ${Tn(n,o)}`},Mk=(o,n)=>{return R`${o} <> ${Tn(n,o)}`},Ak=(o,n)=>{return R`${o} > ${Tn(n,o)}`},$k=(o,n)=>{return R`${o} >= ${Tn(n,o)}`},Jk=(o,n)=>{return R`${o} < ${Tn(n,o)}`},yk=(o,n)=>{return R`${o} <= ${Tn(n,o)}`};function mk(o){return R`${o} asc`}function Qk(o){return R`${o} desc`}class Dk{static[y]="ConsoleLogWriter";write(o){console.log(o)}}class PT{static[y]="DefaultLogger";writer;constructor(o){this.writer=o?.writer??new Dk}logQuery(o,n){const t=n.map((f)=>{try{return JSON.stringify(f)}catch{return String(f)}}),S=t.length?` -- params: [${t.join(", ")}]`:"";this.writer.write(`Query: ${o}${S}`)}}class gT{static[y]="NoopLogger";logQuery(){}}class so{static[y]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(o){return this.then(void 0,o)}finally(o){return this.then((n)=>{return o?.(),n},(n)=>{throw o?.(),n})}then(o,n){return this.execute().then(o,n)}}function Uk(o,n,t){const S={},f=o.reduce((T,{path:M,field:F},k)=>{let A;if(Y(F,Xo))A=F;else if(Y(F,q))A=F.decoder;else A=F.sql.decoder;let $=T;for(let[O,K]of M.entries())if(O<M.length-1){if(!(K in $))$[K]={};$=$[K]}else{const G=n[k],I=$[K]=G===null?null:A.mapFromDriverValue(G);if(t&&Y(F,Xo)&&M.length===2){const H=M[0];if(!(H in S))S[H]=I===null?Wn(F.table):!1;else if(typeof S[H]==="string"&&S[H]!==Wn(F.table))S[H]=!1}}return T},{});if(t&&Object.keys(S).length>0){for(let[T,M]of Object.entries(S))if(typeof M==="string"&&!t[M])f[T]=null}return f}function _n(o,n){return Object.entries(o).reduce((t,[S,f])=>{if(typeof S!=="string")return t;const T=n?[...n,S]:[S];if(Y(f,Xo)||Y(f,q)||Y(f,q.Aliased))t.push({path:T,field:f});else if(Y(f,h))t.push(..._n(f[h.Symbol.Columns],T));else t.push(..._n(f,T));return t},[])}function lT(o,n){const t=Object.keys(o),S=Object.keys(n);if(t.length!==S.length)return!1;for(let[f,T]of t.entries())if(T!==S[f])return!1;return!0}function Wf(o,n){const t=Object.entries(n).filter(([,S])=>S!==void 0).map(([S,f])=>{if(Y(f,q))return[S,f];else return[S,new An(f,o[h.Symbol.Columns][S])]});if(t.length===0)throw new Error("No values to set");return Object.fromEntries(t)}function Vk(o,n){for(let t of n)for(let S of Object.getOwnPropertyNames(t.prototype)){if(S==="constructor")continue;Object.defineProperty(o.prototype,S,Object.getOwnPropertyDescriptor(t.prototype,S)||Object.create(null))}}function rk(o){return o[h.Symbol.Columns]}function eT(o){return Y(o,xo)?o._.alias:Y(o,fn)?o[mo].name:Y(o,q)?void 0:o[h.Symbol.IsAlias]?o[h.Symbol.Name]:o[h.Symbol.BaseName]}function Fo(o,n){return{name:typeof o==="string"&&o.length>0?o:"",config:typeof o==="object"?o:n}}class ot extends v{static[y]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(o){if(o){const{name:n,...t}=o;this.config.generatedIdentity={type:"always",sequenceName:n,sequenceOptions:t}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(o){if(o){const{name:n,...t}=o;this.config.generatedIdentity={type:"byDefault",sequenceName:n,sequenceOptions:t}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}function Bk(o,n){const{name:t,config:S}=Fo(o,n);if(S.mode==="number")return new Ck(t);return new Ik(t)}class Ck extends ot{static[y]="PgBigInt53Builder";constructor(o){super(o,"number","PgBigInt53")}build(o){return new Lk(o,this.config)}}class Lk extends C{static[y]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}}class Ik extends ot{static[y]="PgBigInt64Builder";constructor(o){super(o,"bigint","PgBigInt64")}build(o){return new jk(o,this.config)}}class jk extends C{static[y]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(o){return BigInt(o)}}function xk(o,n){const{name:t,config:S}=Fo(o,n);if(S.mode==="number")return new ck(t);return new Nk(t)}class ck extends v{static[y]="PgBigSerial53Builder";constructor(o){super(o,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new bk(o,this.config)}}class bk extends C{static[y]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}}class Nk extends v{static[y]="PgBigSerial64Builder";constructor(o){super(o,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(o){return new hk(o,this.config)}}class hk extends C{static[y]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(o){return BigInt(o)}}function XS(o){return new ik(o??"")}class ik extends v{static[y]="PgBooleanBuilder";constructor(o){super(o,"boolean","PgBoolean")}build(o){return new vk(o,this.config)}}class vk extends C{static[y]="PgBoolean";getSQLType(){return"boolean"}}function Zk(o,n={}){const{name:t,config:S}=Fo(o,n);return new qk(t,S)}class qk extends v{static[y]="PgCharBuilder";constructor(o,n){super(o,"string","PgChar");this.config.length=n.length,this.config.enumValues=n.enum}build(o){return new pk(o,this.config)}}class pk extends C{static[y]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function lk(o){return new Pk(o??"")}class Pk extends v{static[y]="PgCidrBuilder";constructor(o){super(o,"string","PgCidr")}build(o){return new gk(o,this.config)}}class gk extends C{static[y]="PgCidr";getSQLType(){return"cidr"}}function uk(o){return(n,t)=>{const{name:S,config:f}=Fo(n,t);return new ek(S,f,o)}}class ek extends v{static[y]="PgCustomColumnBuilder";constructor(o,n,t){super(o,"custom","PgCustomColumn");this.config.fieldConfig=n,this.config.customTypeParams=t}build(o){return new dk(o,this.config)}}class dk extends C{static[y]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(o,n){super(o,n);this.sqlName=n.customTypeParams.dataType(n.fieldConfig),this.mapTo=n.customTypeParams.toDriver,this.mapFrom=n.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(o){return typeof this.mapFrom==="function"?this.mapFrom(o):o}mapToDriverValue(o){return typeof this.mapTo==="function"?this.mapTo(o):o}}class pn extends v{static[y]="PgDateColumnBaseBuilder";defaultNow(){return this.default(R`now()`)}}function oA(o,n){const{name:t,config:S}=Fo(o,n);if(S?.mode==="date")return new ak(t);return new sk(t)}class ak extends pn{static[y]="PgDateBuilder";constructor(o){super(o,"date","PgDate")}build(o){return new _f(o,this.config)}}class _f extends C{static[y]="PgDate";getSQLType(){return"date"}mapFromDriverValue(o){return new Date(o)}mapToDriverValue(o){return o.toISOString()}}class sk extends pn{static[y]="PgDateStringBuilder";constructor(o){super(o,"string","PgDateString")}build(o){return new wf(o,this.config)}}class wf extends C{static[y]="PgDateString";getSQLType(){return"date"}}function SA(o){return new nA(o??"")}class nA extends v{static[y]="PgDoublePrecisionBuilder";constructor(o){super(o,"number","PgDoublePrecision")}build(o){return new tA(o,this.config)}}class tA extends C{static[y]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseFloat(o);return o}}function MA(o){return new fA(o??"")}class fA extends v{static[y]="PgInetBuilder";constructor(o){super(o,"string","PgInet")}build(o){return new TA(o,this.config)}}class TA extends C{static[y]="PgInet";getSQLType(){return"inet"}}function Kf(o){return new FA(o??"")}class FA extends ot{static[y]="PgIntegerBuilder";constructor(o){super(o,"number","PgInteger")}build(o){return new kA(o,this.config)}}class kA extends C{static[y]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseInt(o);return o}}function JA(o,n={}){const{name:t,config:S}=Fo(o,n);return new AA(t,S)}class AA extends v{static[y]="PgIntervalBuilder";constructor(o,n){super(o,"string","PgInterval");this.config.intervalConfig=n}build(o){return new $A(o,this.config)}}class $A extends C{static[y]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){const o=this.fields?` ${this.fields}`:"",n=this.precision?`(${this.precision})`:"";return`interval${o}${n}`}}function RA(o){return new yA(o??"")}class yA extends v{static[y]="PgJsonBuilder";constructor(o){super(o,"json","PgJson")}build(o){return new Xf(o,this.config)}}class Xf extends C{static[y]="PgJson";constructor(o,n){super(o,n)}getSQLType(){return"json"}mapToDriverValue(o){return JSON.stringify(o)}mapFromDriverValue(o){if(typeof o==="string")try{return JSON.parse(o)}catch{return o}return o}}function WA(o){return new OA(o??"")}class OA extends v{static[y]="PgJsonbBuilder";constructor(o){super(o,"json","PgJsonb")}build(o){return new Yf(o,this.config)}}class Yf extends C{static[y]="PgJsonb";constructor(o,n){super(o,n)}getSQLType(){return"jsonb"}mapToDriverValue(o){return JSON.stringify(o)}mapFromDriverValue(o){if(typeof o==="string")try{return JSON.parse(o)}catch{return o}return o}}function YA(o,n){const{name:t,config:S}=Fo(o,n);if(!S?.mode||S.mode==="tuple")return new _A(t);return new KA(t)}class _A extends v{static[y]="PgLineBuilder";constructor(o){super(o,"array","PgLine")}build(o){return new wA(o,this.config)}}class wA extends C{static[y]="PgLine";getSQLType(){return"line"}mapFromDriverValue(o){const[n,t,S]=o.slice(1,-1).split(",");return[Number.parseFloat(n),Number.parseFloat(t),Number.parseFloat(S)]}mapToDriverValue(o){return`{${o[0]},${o[1]},${o[2]}}`}}class KA extends v{static[y]="PgLineABCBuilder";constructor(o){super(o,"json","PgLineABC")}build(o){return new XA(o,this.config)}}class XA extends C{static[y]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(o){const[n,t,S]=o.slice(1,-1).split(",");return{a:Number.parseFloat(n),b:Number.parseFloat(t),c:Number.parseFloat(S)}}mapToDriverValue(o){return`{${o.a},${o.b},${o.c}}`}}function zA(o){return new EA(o??"")}class EA extends v{static[y]="PgMacaddrBuilder";constructor(o){super(o,"string","PgMacaddr")}build(o){return new GA(o,this.config)}}class GA extends C{static[y]="PgMacaddr";getSQLType(){return"macaddr"}}function QA(o){return new HA(o??"")}class HA extends v{static[y]="PgMacaddr8Builder";constructor(o){super(o,"string","PgMacaddr8")}build(o){return new mA(o,this.config)}}class mA extends C{static[y]="PgMacaddr8";getSQLType(){return"macaddr8"}}function UA(o,n){const{name:t,config:S}=Fo(o,n);return new DA(t,S?.precision,S?.scale)}class DA extends v{static[y]="PgNumericBuilder";constructor(o,n,t){super(o,"string","PgNumeric");this.config.precision=n,this.config.scale=t}build(o){return new Ef(o,this.config)}}class Ef extends C{static[y]="PgNumeric";precision;scale;constructor(o,n){super(o,n);this.precision=n.precision,this.scale=n.scale}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 IA(o,n){const{name:t,config:S}=Fo(o,n);if(!S?.mode||S.mode==="tuple")return new VA(t);return new CA(t)}class VA extends v{static[y]="PgPointTupleBuilder";constructor(o){super(o,"array","PgPointTuple")}build(o){return new rA(o,this.config)}}class rA extends C{static[y]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(o){if(typeof o==="string"){const[n,t]=o.slice(1,-1).split(",");return[Number.parseFloat(n),Number.parseFloat(t)]}return[o.x,o.y]}mapToDriverValue(o){return`(${o[0]},${o[1]})`}}class CA extends v{static[y]="PgPointObjectBuilder";constructor(o){super(o,"json","PgPointObject")}build(o){return new LA(o,this.config)}}class LA extends C{static[y]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(o){if(typeof o==="string"){const[n,t]=o.slice(1,-1).split(",");return{x:Number.parseFloat(n),y:Number.parseFloat(t)}}return o}mapToDriverValue(o){return`(${o.x},${o.y})`}}function cy(o){const n=[];for(let t=0;t<o.length;t+=2)n.push(Number.parseInt(o.slice(t,t+2),16));return new Uint8Array(n)}function jA(o,n){const t=new ArrayBuffer(8),S=new DataView(t);for(let f=0;f<8;f++)S.setUint8(f,o[n+f]);return S.getFloat64(0,!0)}function dT(o){const n=cy(o);let t=0;const S=n[t];t+=1;const f=new DataView(n.buffer),T=f.getUint32(t,S===1);t+=4;let M;if(T&536870912)M=f.getUint32(t,S===1),t+=4;if((T&65535)===1){const F=jA(n,t);t+=8;const k=jA(n,t);return t+=8,[F,k]}throw new Error("Unsupported geometry type")}function hA(o,n){const{name:t,config:S}=Fo(o,n);if(!S?.mode||S.mode==="tuple")return new BA(t);return new bA(t)}class BA extends v{static[y]="PgGeometryBuilder";constructor(o){super(o,"array","PgGeometry")}build(o){return new cA(o,this.config)}}class cA extends C{static[y]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(o){return dT(o)}mapToDriverValue(o){return`point(${o[0]} ${o[1]})`}}class bA extends v{static[y]="PgGeometryObjectBuilder";constructor(o){super(o,"json","PgGeometryObject")}build(o){return new NA(o,this.config)}}class NA extends C{static[y]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(o){const n=dT(o);return{x:n[0],y:n[1]}}mapToDriverValue(o){return`point(${o.x} ${o.y})`}}function vA(o){return new xA(o??"")}class xA extends v{static[y]="PgRealBuilder";constructor(o,n){super(o,"number","PgReal");this.config.length=n}build(o){return new iA(o,this.config)}}class iA extends C{static[y]="PgReal";constructor(o,n){super(o,n)}getSQLType(){return"real"}mapFromDriverValue=(o)=>{if(typeof o==="string")return Number.parseFloat(o);return o}}function ZA(o){return new qA(o??"")}class qA extends v{static[y]="PgSerialBuilder";constructor(o){super(o,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new pA(o,this.config)}}class pA extends C{static[y]="PgSerial";getSQLType(){return"serial"}}function lA(o){return new PA(o??"")}class PA extends ot{static[y]="PgSmallIntBuilder";constructor(o){super(o,"number","PgSmallInt")}build(o){return new gA(o,this.config)}}class gA extends C{static[y]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(o)=>{if(typeof o==="string")return Number(o);return o}}function uA(o){return new eA(o??"")}class eA extends v{static[y]="PgSmallSerialBuilder";constructor(o){super(o,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new dA(o,this.config)}}class dA extends C{static[y]="PgSmallSerial";getSQLType(){return"smallserial"}}function o$(o,n={}){const{name:t,config:S}=Fo(o,n);return new aA(t,S)}class aA extends v{static[y]="PgTextBuilder";constructor(o,n){super(o,"string","PgText");this.config.enumValues=n.enum}build(o){return new sA(o,this.config)}}class sA extends C{static[y]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function t$(o,n={}){const{name:t,config:S}=Fo(o,n);return new n$(t,S.withTimezone??!1,S.precision)}class n$ extends pn{constructor(o,n,t){super(o,"string","PgTime");this.withTimezone=n,this.precision=t,this.config.withTimezone=n,this.config.precision=t}static[y]="PgTimeBuilder";build(o){return new Gf(o,this.config)}}class Gf extends C{static[y]="PgTime";withTimezone;precision;constructor(o,n){super(o,n);this.withTimezone=n.withTimezone,this.precision=n.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function mn(o,n={}){const{name:t,config:S}=Fo(o,n);if(S?.mode==="string")return new f$(t,S.withTimezone??!1,S.precision);return new S$(t,S?.withTimezone??!1,S?.precision)}class S$ extends pn{static[y]="PgTimestampBuilder";constructor(o,n,t){super(o,"date","PgTimestamp");this.config.withTimezone=n,this.config.precision=t}build(o){return new zf(o,this.config)}}class zf extends C{static[y]="PgTimestamp";withTimezone;precision;constructor(o,n){super(o,n);this.withTimezone=n.withTimezone,this.precision=n.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(o)=>{return new Date(this.withTimezone?o:o+"+0000")};mapToDriverValue=(o)=>{return o.toISOString()}}class f$ extends pn{static[y]="PgTimestampStringBuilder";constructor(o,n,t){super(o,"string","PgTimestampString");this.config.withTimezone=n,this.config.precision=t}build(o){return new Hf(o,this.config)}}class Hf extends C{static[y]="PgTimestampString";withTimezone;precision;constructor(o,n){super(o,n);this.withTimezone=n.withTimezone,this.precision=n.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function $n(o){return new T$(o??"")}class T$ extends v{static[y]="PgUUIDBuilder";constructor(o){super(o,"string","PgUUID")}defaultRandom(){return this.default(R`gen_random_uuid()`)}build(o){return new mf(o,this.config)}}class mf extends C{static[y]="PgUUID";getSQLType(){return"uuid"}}function io(o,n={}){const{name:t,config:S}=Fo(o,n);return new M$(t,S)}class M$ extends v{static[y]="PgVarcharBuilder";constructor(o,n){super(o,"string","PgVarchar");this.config.length=n.length,this.config.enumValues=n.enum}build(o){return new F$(o,this.config)}}class F$ extends C{static[y]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function $$(o,n){const{name:t,config:S}=Fo(o,n);return new k$(t,S)}class k$ extends v{static[y]="PgBinaryVectorBuilder";constructor(o,n){super(o,"string","PgBinaryVector");this.config.dimensions=n.dimensions}build(o){return new A$(o,this.config)}}class A$ extends C{static[y]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function R$(o,n){const{name:t,config:S}=Fo(o,n);return new J$(t,S)}class J$ extends v{static[y]="PgHalfVectorBuilder";constructor(o,n){super(o,"array","PgHalfVector");this.config.dimensions=n.dimensions}build(o){return new y$(o,this.config)}}class y$ extends C{static[y]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(o){return JSON.stringify(o)}mapFromDriverValue(o){return o.slice(1,-1).split(",").map((n)=>Number.parseFloat(n))}}function _$(o,n){const{name:t,config:S}=Fo(o,n);return new O$(t,S)}class O$ extends v{static[y]="PgSparseVectorBuilder";constructor(o,n){super(o,"string","PgSparseVector");this.config.dimensions=n.dimensions}build(o){return new W$(o,this.config)}}class W$ extends C{static[y]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function X$(o,n){const{name:t,config:S}=Fo(o,n);return new w$(t,S)}class w$ extends v{static[y]="PgVectorBuilder";constructor(o,n){super(o,"array","PgVector");this.config.dimensions=n.dimensions}build(o){return new K$(o,this.config)}}class K$ extends C{static[y]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(o){return JSON.stringify(o)}mapFromDriverValue(o){return o.slice(1,-1).split(",").map((n)=>Number.parseFloat(n))}}function Y$(){return{bigint:Bk,bigserial:xk,boolean:XS,char:Zk,cidr:lk,customType:uk,date:oA,doublePrecision:SA,inet:MA,integer:Kf,interval:JA,json:RA,jsonb:WA,line:YA,macaddr:zA,macaddr8:QA,numeric:UA,point:IA,geometry:hA,real:vA,serial:ZA,smallint:lA,smallserial:uA,text:o$,time:t$,timestamp:mn,uuid:$n,varchar:io,bit:$$,halfvec:R$,sparsevec:_$,vector:X$}}function by(o,n,t,S,f=o){const T=new Qn(o,S,f),M=typeof n==="function"?n(Y$()):n,F=Object.fromEntries(Object.entries(M).map(([$,O])=>{const K=O;K.setName($);const G=K.build(T);return T[uT].push(...K.buildForeignKeys(G,T)),[$,G]})),k=Object.fromEntries(Object.entries(M).map(([$,O])=>{const K=O;K.setName($);const G=K.buildExtraConfigColumn(T);return[$,G]})),A=Object.assign(T,F);if(A[h.Symbol.Columns]=F,A[h.Symbol.ExtraConfigColumns]=k,t)A[Qn.Symbol.ExtraConfigBuilder]=t;return A}var uT=Symbol.for("drizzle:PgInlineForeignKeys");class Qn extends h{static[y]="PgTable";static Symbol=Object.assign({},h.Symbol,{InlineForeignKeys:uT});[uT]=[];[h.Symbol.ExtraConfigBuilder]=void 0}var nt=(o,n,t)=>{return by(o,n,t,void 0)};function E$(...o){if(o[0].columns)return new YS(o[0].columns,o[0].name);return new YS(o)}class YS{static[y]="PgPrimaryKeyBuilder";columns;name;constructor(o,n){this.columns=o,this.name=n}build(o){return new G$(o,this.columns,this.name)}}class G${constructor(o,n,t){this.table=o,this.columns=n,this.name=t}static[y]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[Qn.Symbol.Name]}_${this.columns.map((o)=>o.name).join("_")}_pk`}}function H$(){return{and:KS,between:Xk,eq:Ct,exists:wk,gt:Ak,gte:$k,ilike:zk,inArray:Rk,isNull:Wk,isNotNull:_k,like:Ek,lt:Jk,lte:yk,ne:Mk,not:kk,notBetween:Yk,notExists:Kk,notLike:Gk,notIlike:Hk,notInArray:Ok,or:Fk,sql:R}}function m$(){return{sql:R,asc:mk,desc:Qk}}function Q$(o,n){if(Object.keys(o).length===1&&"default"in o&&!Y(o.default,h))o=o.default;const t={},S={},f={};for(let[T,M]of Object.entries(o))if(Y(M,h)){const F=$t(M),k=S[F];t[F]=T,f[T]={tsName:T,dbName:M[h.Symbol.Name],schema:M[h.Symbol.Schema],columns:M[h.Symbol.Columns],relations:k?.relations??{},primaryKey:k?.primaryKey??[]};for(let $ of Object.values(M[h.Symbol.Columns]))if($.primary)f[T].primaryKey.push($);const A=M[h.Symbol.ExtraConfigBuilder]?.(M[h.Symbol.ExtraConfigColumns]);if(A){for(let $ of Object.values(A))if(Y($,YS))f[T].primaryKey.push(...$.columns)}}else if(Y(M,z$)){const F=$t(M.table),k=t[F],A=M.config(n(M.table));let $;for(let[O,K]of Object.entries(A))if(k){const G=f[k];if(G.relations[O]=K,$)G.primaryKey.push(...$)}else{if(!(F in S))S[F]={relations:{},primaryKey:$};S[F].relations[O]=K}}return{tables:f,tableNamesMap:t}}function Ny(o){return function n(t,S){return new tt(o,t,S,S?.fields.reduce((f,T)=>f&&T.notNull,!0)??!1)}}function hy(o){return function n(t,S){return new ES(o,t,S)}}function D$(o,n,t){if(Y(t,tt)&&t.config)return{fields:t.config.fields,references:t.config.references};const S=n[$t(t.referencedTable)];if(!S)throw new Error(`Table "${t.referencedTable[h.Symbol.Name]}" not found in schema`);const f=o[S];if(!f)throw new Error(`Table "${S}" not found in schema`);const T=t.sourceTable,M=n[$t(T)];if(!M)throw new Error(`Table "${T[h.Symbol.Name]}" not found in schema`);const F=[];for(let k of Object.values(f.relations))if(t.relationName&&t!==k&&k.relationName===t.relationName||!t.relationName&&k.referencedTable===t.sourceTable)F.push(k);if(F.length>1)throw t.relationName?new Error(`There are multiple relations with name "${t.relationName}" in table "${S}"`):new Error(`There are multiple relations between "${S}" and "${t.sourceTable[h.Symbol.Name]}". Please specify relation name`);if(F[0]&&Y(F[0],tt)&&F[0].config)return{fields:F[0].config.references,references:F[0].config.fields};throw new Error(`There is not enough information to infer relation "${M}.${t.fieldName}"`)}function U$(o){return{one:Ny(o),many:hy(o)}}function Qf(o,n,t,S,f=(T)=>T){const T={};for(let[M,F]of S.entries())if(F.isJson){const k=n.relations[F.tsKey],A=t[M],$=typeof A==="string"?JSON.parse(A):A;T[F.tsKey]=Y(k,tt)?$&&Qf(o,o[F.relationTableTsKey],$,F.selection,f):$.map((O)=>Qf(o,o[F.relationTableTsKey],O,F.selection,f))}else{const k=f(t[M]),A=F.field;let $;if(Y(A,Xo))$=A;else if(Y(A,q))$=A.decoder;else $=A.sql.decoder;T[F.tsKey]=k===null?null:$.mapFromDriverValue(k)}return T}class aT{constructor(o,n,t){this.sourceTable=o,this.referencedTable=n,this.relationName=t,this.referencedTableName=n[h.Symbol.Name]}static[y]="Relation";referencedTableName;fieldName}class z${constructor(o,n){this.table=o,this.config=n}static[y]="Relations"}class tt extends aT{constructor(o,n,t,S){super(o,n,t?.relationName);this.config=t,this.isNullable=S}static[y]="One";withFieldName(o){const n=new tt(this.sourceTable,this.referencedTable,this.config,this.isNullable);return n.fieldName=o,n}}class ES extends aT{constructor(o,n,t){super(o,n,t?.relationName);this.config=t}static[y]="Many";withFieldName(o){const n=new ES(this.sourceTable,this.referencedTable,this.config);return n.fieldName=o,n}}import I0 from"path";import AR from"os";import $R from"fs";function xy(o){if(Df.has(o))return Df.get(o);const n=Error.stackTraceLimit;return Error.stackTraceLimit=4,Df.set(o,new Error),Error.stackTraceLimit=n,Df.get(o)}var Df=new Map,sT=new Map,oM=Symbol("OriginError"),Lt={};class wn extends Promise{constructor(o,n,t,S,f={}){let T,M;super((F,k)=>{T=F,M=k});this.tagged=Array.isArray(o.raw),this.strings=o,this.args=n,this.handler=t,this.canceller=S,this.options=f,this.state=null,this.statement=null,this.resolve=(F)=>(this.active=!1,T(F)),this.reject=(F)=>(this.active=!1,M(F)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[oM]=this.handler.debug?new Error:this.tagged&&xy(this.strings)}get origin(){return(this.handler.debug?this[oM].stack:this.tagged&&sT.has(this.strings)?sT.get(this.strings):sT.set(this.strings,this[oM].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(o=1,n){if(this.options.simple=!1,typeof o==="function")n=o,o=1;if(this.cursorRows=o,typeof n==="function")return this.cursorFn=n,this;let t;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};t&&t();const S=new Promise((f,T)=>{this.cursorFn=(M)=>{return f({value:M,done:!1}),new Promise((F)=>t=F)},this.resolve=()=>(this.active=!1,f({done:!0})),this.reject=(M)=>(this.active=!1,T(M))});return this.execute(),S},return(){return t&&t(Lt),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw new Error(".stream has been renamed to .forEach")}forEach(o){return this.forEachFn=o,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}}function V$(o,n,t){const{host:S,port:f}=t||n,T=Object.assign(new Error("write "+o+" "+(n.path||S+":"+f)),{code:o,errno:o,address:n.path||S},n.path?{}:{port:f});return Error.captureStackTrace(T,V$),T}function r$(o){const n=new It(o);return Error.captureStackTrace(n,r$),n}function C$(o,n){const t=Object.assign(new Error(o+": "+n),{code:o});return Error.captureStackTrace(t,C$),t}function L$(o){const n=Object.assign(new Error(o+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:o});return Error.captureStackTrace(n,L$),n}class It extends Error{constructor(o){super(o.message);this.name=this.constructor.name,Object.assign(this,o)}}var Io={connection:V$,postgres:r$,generic:C$,notSupported:L$};function Lf(o,n,t,S){let f=o instanceof cn?o.value:o;if(f===void 0){if(o instanceof cn?o.value=S.transform.undefined:f=o=S.transform.undefined,f===void 0)throw Io.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+t.push(o instanceof cn?(n.push(o.value),o.array?o.array[o.type||Vf(o.value)]||o.type||c$(o.value):o.type):(n.push(o),Vf(o)))}function fM(o,n,t,S,f,T){for(let M=1;M<o.strings.length;M++)n+=TM(n,t,S,f,T)+o.strings[M],t=o.args[M];return n}function TM(o,n,t,S,f){return n instanceof Cf?n.build(o,t,S,f):n instanceof wn?SM(n,t,S,f):n instanceof mS?n.value:n&&n[0]instanceof wn?n.reduce((T,M)=>T+" "+SM(M,t,S,f),""):Lf(n,t,S,f)}function SM(o,n,t,S){return o.fragment=!0,fM(o,o.strings[0],o.args[0],n,t,S)}function B$(o,n,t,S,f){return o.map((T)=>"("+S.map((M)=>TM("values",T[M],n,t,f)).join(",")+")").join(",")}function I$(o,n,t,S,f){const T=Array.isArray(o[0]),M=n.length?n.flat():Object.keys(T?o[0]:o);return B$(T?o:[o],t,S,M,f)}function Uf(o,n,t,S,f){if(typeof o==="string"&&(o=[o].concat(n)),Array.isArray(o))return MM(o,f);let T;return(n.length?n.flat():Object.keys(o)).map((F)=>{return T=o[F],(T instanceof wn?SM(T,t,S,f):T instanceof mS?T.value:Lf(T,t,S,f))+" as "+If(f.transform.column.to?f.transform.column.to(F):F)}).join(",")}function nM(){throw Io.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}function c$(o){if(Array.isArray(o))return c$(o[0]);return typeof o==="string"?1009:0}function N$(o){return Object.keys(o).reduce((n,t)=>{if(o[t].from&&[].concat(o[t].from).forEach((S)=>n.parsers[S]=o[t].parse),o[t].serialize)n.serializers[o[t].to]=o[t].serialize,o[t].from&&[].concat(o[t].from).forEach((S)=>n.serializers[S]=o[t].serialize);return n},{parsers:{},serializers:{}})}function MM(o,{transform:{column:n}}){return o.map((t)=>If(n.to?n.to(t):t)).join(",")}function gy(o){return o.replace(Zy,"\\\\").replace(Py,'\\"')}function i$(o,n,t,S){const f=[],T=S===1020?";":",";for(;o.i<n.length;o.i++){if(o.char=n[o.i],o.quoted)if(o.char==="\\")o.str+=n[++o.i];else if(o.char==='"')f.push(t?t(o.str):o.str),o.str="",o.quoted=n[o.i+1]==='"',o.last=o.i+2;else o.str+=o.char;else if(o.char==='"')o.quoted=!0;else if(o.char==="{")o.last=++o.i,f.push(i$(o,n,t,S));else if(o.char==="}"){o.quoted=!1,o.last<o.i&&f.push(t?t(n.slice(o.last,o.i)):n.slice(o.last,o.i)),o.last=o.i+1;break}else if(o.char===T&&o.p!=="}"&&o.p!=='"')f.push(t?t(n.slice(o.last,o.i)):n.slice(o.last,o.i)),o.last=o.i+1;o.p=o.char}return o.last<o.i&&f.push(t?t(n.slice(o.last,o.i+1)):n.slice(o.last,o.i+1)),f}function FM(o){return function n(t,S){return typeof t==="object"&&t!==null&&(S.type===114||S.type===3802)?Array.isArray(t)?t.map((f)=>n(f,S)):Object.entries(t).reduce((f,[T,M])=>Object.assign(f,{[o(T)]:n(M,S)}),{}):t}}var iy={string:{to:25,from:null,serialize:(o)=>""+o},number:{to:0,from:[21,23,26,700,701],serialize:(o)=>""+o,parse:(o)=>+o},json:{to:114,from:[114,3802],serialize:(o)=>JSON.stringify(o),parse:(o)=>JSON.parse(o)},boolean:{to:16,from:16,serialize:(o)=>o===!0?"t":"f",parse:(o)=>o==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(o)=>(o instanceof Date?o:new Date(o)).toISOString(),parse:(o)=>new Date(o)},bytea:{to:17,from:17,serialize:(o)=>"\\x"+Buffer.from(o).toString("hex"),parse:(o)=>Buffer.from(o.slice(2),"hex")}};class rf{then(){nM()}catch(){nM()}finally(){nM()}}class mS extends rf{constructor(o){super();this.value=If(o)}}class cn extends rf{constructor(o,n,t){super();this.value=o,this.type=n,this.array=t}}class Cf extends rf{constructor(o,n){super();this.first=o,this.rest=n}build(o,n,t,S){const f=vy.map(([T,M])=>({fn:M,i:o.search(T)})).sort((T,M)=>T.i-M.i).pop();return f.i===-1?MM(this.first,S):f.fn(this.first,this.rest,n,t,S)}}var j$=N$(iy),vy=Object.entries({values:I$,in:(...o)=>{const n=I$(...o);return n==="()"?"(null)":n},select:Uf,as:Uf,returning:Uf,"\\(":Uf,update(o,n,t,S,f){return(n.length?n.flat():Object.keys(o)).map((T)=>If(f.transform.column.to?f.transform.column.to(T):T)+"="+TM("values",o[T],t,S,f))},insert(o,n,t,S,f){const T=n.length?n.flat():Object.keys(Array.isArray(o)?o[0]:o);return"("+MM(T,f)+")values"+B$(Array.isArray(o)?o:[o],t,S,T,f)}}).map(([o,n])=>[new RegExp("((?:^|[\\s(])"+o+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),n]),qy=j$.serializers,py=j$.parsers;var b$=function(o){const n=N$(o||{});return{serializers:Object.assign({},qy,n.serializers),parsers:Object.assign({},py,n.parsers)}},If=function o(n){return'"'+n.replace(/"/g,'""').replace(/\./g,'"."')+'"'},Vf=function o(n){return n instanceof cn?n.type:n instanceof Date?1184:n instanceof Uint8Array?17:n===!0||n===!1?16:typeof n==="bigint"?20:Array.isArray(n)?o(n[0]):0},Zy=/\\/g,Py=/"/g,h$=function o(n,t,S,f){if(Array.isArray(n)===!1)return n;if(!n.length)return"{}";const T=n[0],M=f===1020?";":",";if(Array.isArray(T)&&!T.type)return"{"+n.map((F)=>o(F,t,S,f)).join(M)+"}";return"{"+n.map((F)=>{if(F===void 0){if(F=S.transform.undefined,F===void 0)throw Io.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return F===null?"null":'"'+gy(t?t(F.type?F.value:F):""+F)+'"'}).join(M)+"}"},tM={i:0,char:null,str:"",quoted:!1,last:0},x$=function o(n,t,S){return tM.i=tM.last=0,i$(tM,n,t,S)},Jt=(o)=>{let n=o[0];for(let t=1;t<o.length;t++)n+=o[t]==="_"?o[++t].toUpperCase():o[t];return n},yt=(o)=>{let n=o[0].toUpperCase();for(let t=1;t<o.length;t++)n+=o[t]==="_"?o[++t].toUpperCase():o[t];return n},Rt=(o)=>o.replace(/_/g,"-"),GS=(o)=>o.replace(/([A-Z])/g,"_$1").toLowerCase(),zS=(o)=>(o.slice(0,1)+o.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),HS=(o)=>o.replace(/-/g,"_");Jt.column={from:Jt};Jt.value={from:FM(Jt)};GS.column={to:GS};var kM={...Jt};kM.column.to=GS;yt.column={from:yt};yt.value={from:FM(yt)};zS.column={to:zS};var AM={...yt};AM.column.to=zS;Rt.column={from:Rt};Rt.value={from:FM(Rt)};HS.column={to:HS};var $M={...Rt};$M.column.to=HS;import v$ from"net";import uy from"tls";import QS from"crypto";import JM from"stream";import{performance as q$}from"perf_hooks";class Ot 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}}function ly(o=[]){let n=o.slice(),t=0;return{get length(){return n.length-t},remove:(S)=>{const f=n.indexOf(S);return f===-1?null:(n.splice(f,1),S)},push:(S)=>(n.push(S),S),shift:()=>{const S=n[t++];if(t===n.length)t=0,n=[];else n[t-1]=void 0;return S}}}var Jn=ly;function jf(o){if(go.length-Oo.i<o){const n=go,t=n.length;go=Buffer.allocUnsafe(t+(t>>1)+o),n.copy(go)}}function dy(){return Oo.i=0,Oo}var go=Buffer.allocUnsafe(256),ey="BCcDdEFfHPpQSX".split("").reduce((o,n)=>{const t=n.charCodeAt(0);return o[n]=()=>{return go[0]=t,Oo.i=5,Oo},o},{}),Oo=Object.assign(dy,ey,{N:String.fromCharCode(0),i:0,inc(o){return Oo.i+=o,Oo},str(o){const n=Buffer.byteLength(o);return jf(n),Oo.i+=go.write(o,Oo.i,n,"utf8"),Oo},i16(o){return jf(2),go.writeUInt16BE(o,Oo.i),Oo.i+=2,Oo},i32(o,n){if(n||n===0)return go.writeUInt32BE(o,n),Oo;return jf(4),go.writeUInt32BE(o,Oo.i),Oo.i+=4,Oo},z(o){return jf(o),go.fill(0,Oo.i,Oo.i+o),Oo.i+=o,Oo},raw(o){return go=Buffer.concat([go.subarray(0,Oo.i),o]),Oo.i=go.length,Oo},end(o=1){go.writeUInt32BE(Oo.i-o,o);const n=go.subarray(0,Oo.i);return Oo.i=0,go=Buffer.allocUnsafe(256),n}}),P=Oo;function P$(o,n={},{onopen:t=jt,onend:S=jt,onclose:f=jt}={}){const{ssl:T,max:M,user:F,host:k,port:A,database:$,parsers:O,transform:K,onnotice:G,onnotify:I,onparameter:H,max_pipeline:V,keep_alive:m,backoff:j,target_session_attrs:r}=o,i=Jn(),X=ay++,w={pid:null,secret:null},z=RM(af,o.idle_timeout),B=RM(af,o.max_lifetime),N=RM(DJ,o.connect_timeout);let _=null,c,U=new Ot,l=Buffer.alloc(0),no=o.fetch_types,So={},_o={},Fn=Math.random().toString(36).slice(2),E=1,p=0,To=0,Ro=0,jo=0,fo=0,wo=0,Co=0,Ho=null,Yo=null,vo=!1,Ko=null,Xn=null,qo=null,ln=null,Bo=null,Eo=null,Yn=null,Ln=null,L=null,st=null;const po={queue:n.closed,idleTimer:z,connect(J){qo=J||!0,PM()},terminate:nS,execute:oS,cancel:zJ,end:af,count:0,id:X};return n.closed&&n.closed.push(po),po;async function GJ(){let J;try{J=o.socket?await Promise.resolve(o.socket(o)):new v$.Socket}catch(W){Gt(W);return}return J.on("error",Gt),J.on("close",gM),J.on("drain",pM),J}async function zJ({pid:J,secret:W},g,yo){try{c=P().i32(16).i32(80877102).i32(J).i32(W).end(16),await ZM(),_.once("error",yo),_.once("close",g)}catch(Do){yo(Do)}}function oS(J){if(vo)return pS(J,Io.connection("CONNECTION_DESTROYED",o));if(J.cancelled)return;try{return J.state=w,L?i.push(J):(L=J,L.active=!0),QJ(J),ho(HJ(J))&&!J.describeFirst&&!J.cursorFn&&i.length<V&&(!J.options.onexecute||J.options.onexecute(po))}catch(W){return i.length===0&&ho(St),In(W),!0}}function HJ(J){if(J.parameters.length>=65534)throw Io.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return J.options.simple?P().Q().str(J.statement.string+P.N).end():J.describeFirst?Buffer.concat([iM(J),p$]):J.prepare?J.prepared?qS(J):Buffer.concat([iM(J),qS(J)]):mJ(J)}function iM(J){return Buffer.concat([eM(J.statement.string,J.parameters,J.statement.types,J.statement.name),Jy("S",J.statement.name)])}function qS(J){return Buffer.concat([$y(J.parameters,J.statement.types,J.statement.name,J.cursorName),J.cursorFn?dM("",J.cursorRows):oR])}function mJ(J){return Buffer.concat([eM(J.statement.string,J.parameters,J.statement.types),nR,qS(J)])}function QJ(J){const W=[],g=[],yo=fM(J,J.strings[0],J.args[0],W,g,o);!J.tagged&&J.args.forEach((Do)=>Lf(Do,W,g,o)),J.prepare=o.prepare&&("prepare"in J.options?J.options.prepare:!0),J.string=yo,J.signature=J.prepare&&g+yo,J.onlyDescribe&&delete _o[J.signature],J.parameters=J.parameters||W,J.prepared=J.prepare&&J.signature in _o,J.describeFirst=J.onlyDescribe||W.length&&!J.prepared,J.statement=J.prepared?_o[J.signature]:{string:yo,types:g,name:J.prepare?Fn+E++:""},typeof o.debug==="function"&&o.debug(X,yo,W,g)}function ho(J,W){if(Eo=Eo?Buffer.concat([Eo,J]):Buffer.from(J),W||Eo.length>=1024)return vM(W);return Yo===null&&(Yo=setImmediate(vM)),!0}function vM(J){const W=_.write(Eo,J);return Yo!==null&&clearImmediate(Yo),Eo=Yo=null,W}function DJ(){In(Io.connection("CONNECT_TIMEOUT",o,_)),_.destroy()}async function qM(){if(ho(sy),!await new Promise((W)=>_.once("data",(g)=>W(g[0]===83)))&&T==="prefer")return Et();_.removeAllListeners(),_=uy.connect({socket:_,servername:v$.isIP(_.host)?void 0:_.host,...T==="require"||T==="allow"||T==="prefer"?{rejectUnauthorized:!1}:T==="verify-full"?{}:typeof T==="object"?T:{}}),_.on("secureConnect",Et),_.on("error",Gt),_.on("close",gM),_.on("drain",pM)}function pM(){!L&&t(po)}function uf(J){if(Ko){if(Ko.push(J),To-=J.length,To>=0)return}l=Ko?Buffer.concat(Ko,fo-To):l.length===0?J:Buffer.concat([l,J],l.length+J.length);while(l.length>4){if(fo=l.readUInt32BE(1),fo>=l.length){To=fo-l.length,Ko=[l];break}try{UJ(l.subarray(0,fo+1))}catch(W){L&&(L.cursorFn||L.describeFirst)&&ho(St),In(W)}l=l.subarray(fo+1),To=0,Ko=null}}async function ZM(){if(vo=!1,So={},_||(_=await GJ()),!_)return;if(N.start(),o.socket)return T?qM():Et();if(_.on("connect",T?qM:Et),o.path)return _.connect(o.path);_.ssl=T,_.connect(A[Ro],k[Ro]),_.host=k[Ro],_.port=A[Ro],Ro=(Ro+1)%A.length}function PM(){setTimeout(ZM,p?p+wo-q$.now():0)}function Et(){try{_o={},no=o.fetch_types,Fn=Math.random().toString(36).slice(2),E=1,B.start(),_.on("data",uf),m&&_.setKeepAlive&&_.setKeepAlive(!0,1000*m);const J=Ry();ho(J)}catch(J){Gt(J)}}function Gt(J){if(po.queue===n.connecting&&o.host[jo+1])return;In(J);while(i.length)pS(i.shift(),J)}function In(J){Bo&&(Bo.destroy(J),Bo=null),L&&pS(L,J),qo&&(pS(qo,J),qo=null)}function pS(J,W){Object.defineProperties(W,{stack:{value:W.stack+J.origin.replace(/.*\n/,"\n"),enumerable:o.debug},query:{value:J.string,enumerable:o.debug},parameters:{value:J.parameters,enumerable:o.debug},args:{value:J.args,enumerable:o.debug},types:{value:J.statement&&J.statement.types,enumerable:o.debug}}),J.reject(W)}function af(){return ln||(!po.reserved&&S(po),!po.reserved&&!qo&&!L&&i.length===0?(nS(),new Promise((J)=>_&&_.readyState!=="closed"?_.once("close",J):J())):ln=new Promise((J)=>Yn=J))}function nS(){if(vo=!0,Bo||L||qo||i.length)Gt(Io.connection("CONNECTION_DESTROYED",o));if(clearImmediate(Yo),_)_.removeListener("data",uf),_.removeListener("connect",Et),_.readyState==="open"&&_.end(P().X().end());Yn&&(Yn(),ln=Yn=null)}async function gM(J){if(l=Buffer.alloc(0),To=0,Ko=null,clearImmediate(Yo),_.removeListener("data",uf),_.removeListener("connect",Et),z.cancel(),B.cancel(),N.cancel(),_.removeAllListeners(),_=null,qo)return PM();!J&&(L||i.length)&&Gt(Io.connection("CONNECTION_CLOSED",o,_)),p=q$.now(),J&&o.shared.retries++,wo=(typeof j==="function"?j(o.shared.retries):j)*1000,f(po,Io.connection("CONNECTION_CLOSED",o,_))}function UJ(J,W=J[0]){(W===68?VJ:W===100?ty:W===65?dJ:W===83?rJ:W===90?CJ:W===67?LJ:W===50?lM:W===49?IJ:W===116?jJ:W===84?BJ:W===82?cJ:W===110?vJ:W===75?qJ:W===69?lJ:W===115?uJ:W===51?aJ:W===71?sJ:W===78?fy:W===72?oy:W===99?Sy:W===73?Ty:W===86?My:W===118?Fy:W===87?ny:ky)(J)}function VJ(J){let W=7,g,yo,Do;const Zo=L.isRaw?new Array(L.statement.columns.length):{};for(let eo=0;eo<L.statement.columns.length;eo++)yo=L.statement.columns[eo],g=J.readInt32BE(W),W+=4,Do=g===-1?null:L.isRaw===!0?J.subarray(W,W+=g):yo.parser===void 0?J.toString("utf8",W,W+=g):yo.parser.array===!0?yo.parser(J.toString("utf8",W+1,W+=g)):yo.parser(J.toString("utf8",W,W+=g)),L.isRaw?Zo[eo]=L.isRaw===!0?Do:K.value.from?K.value.from(Do,yo):Do:Zo[yo.name]=K.value.from?K.value.from(Do,yo):Do;L.forEachFn?L.forEachFn(K.row.from?K.row.from(Zo):Zo,U):U[Co++]=K.row.from?K.row.from(Zo):Zo}function rJ(J){const[W,g]=J.toString("utf8",5,J.length-1).split(P.N);if(So[W]=g,o.parameters[W]!==g)o.parameters[W]=g,H&&H(W,g)}function CJ(J){if(L&&L.options.simple&&L.resolve(Xn||U),L=Xn=null,U=new Ot,N.cancel(),qo){if(r){if(!So.in_hot_standby||!So.default_transaction_read_only)return gJ();else if(PJ(r,So))return nS()}if(no)return qo===!0&&(qo=null),pJ();qo!==!0&&oS(qo),o.shared.retries=jo=0,qo=null;return}while(i.length&&(L=i.shift())&&(L.active=!0,L.cancelled))P$(o).cancel(L.state,L.cancelled.resolve,L.cancelled.reject);if(L)return;po.reserved?!po.reserved.release&&J[5]===73?ln?nS():(po.reserved=null,t(po)):po.reserved():ln?nS():t(po)}function LJ(J){Co=0;for(let W=J.length-1;W>0;W--){if(J[W]===32&&J[W+1]<58&&U.count===null)U.count=+J.toString("utf8",W+1,J.length-1);if(J[W-1]>=65){U.command=J.toString("utf8",5,W),U.state=w;break}}if(st&&(st(),st=null),U.command==="BEGIN"&&M!==1&&!po.reserved)return In(Io.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(L.options.simple)return lM();if(L.cursorFn)U.count&&L.cursorFn(U),ho(St);L.resolve(U)}function IJ(){L.parsing=!1}function lM(){!U.statement&&(U.statement=L.statement),U.columns=L.statement.columns}function jJ(J){const W=J.readUInt16BE(5);for(let g=0;g<W;++g)!L.statement.types[g]&&(L.statement.types[g]=J.readUInt32BE(7+g*4));L.prepare&&(_o[L.signature]=L.statement),L.describeFirst&&!L.onlyDescribe&&(ho(qS(L)),L.describeFirst=!1)}function BJ(J){if(U.command)Xn=Xn||[U],Xn.push(U=new Ot),U.count=null,L.statement.columns=null;const W=J.readUInt16BE(5);let g=7,yo;L.statement.columns=Array(W);for(let Do=0;Do<W;++Do){yo=g;while(J[g++]!==0);const Zo=J.readUInt32BE(g),eo=J.readUInt16BE(g+4),en=J.readUInt32BE(g+6);L.statement.columns[Do]={name:K.column.from?K.column.from(J.toString("utf8",yo,g-1)):J.toString("utf8",yo,g-1),parser:O[en],table:Zo,number:eo,type:en},g+=18}if(U.statement=L.statement,L.onlyDescribe)return L.resolve(L.statement),ho(St)}async function cJ(J,W=J.readUInt32BE(5)){(W===3?bJ:W===5?NJ:W===10?hJ:W===11?xJ:W===12?iJ:W!==0?Ay:jt)(J,W)}async function bJ(){const J=await sf();ho(P().p().str(J).z(1).end())}async function NJ(J){const W="md5"+await Z$(Buffer.concat([Buffer.from(await Z$(await sf()+F)),J.subarray(9)]));ho(P().p().str(W).z(1).end())}async function hJ(){Ln=(await QS.randomBytes(18)).toString("base64"),P().p().str("SCRAM-SHA-256"+P.N);const J=P.i;ho(P.inc(4).str("n,,n=*,r="+Ln).i32(P.i-J-4,J).end())}async function xJ(J){const W=J.toString("utf8",9).split(",").reduce((eo,en)=>(eo[en[0]]=en.slice(2),eo),{}),g=await QS.pbkdf2Sync(await sf(),Buffer.from(W.s,"base64"),parseInt(W.i),32,"sha256"),yo=await Bf(g,"Client Key"),Do="n=*,r="+Ln+",r="+W.r+",s="+W.s+",i="+W.i+",c=biws,r="+W.r;Ho=(await Bf(await Bf(g,"Server Key"),Do)).toString("base64");const Zo="c=biws,r="+W.r+",p="+TR(yo,Buffer.from(await Bf(await fR(yo),Do))).toString("base64");ho(P().p().str(Zo).end())}function iJ(J){if(J.toString("utf8",9).split(P.N,1)[0].slice(2)===Ho)return;In(Io.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),_.destroy()}function sf(){return Promise.resolve(typeof o.pass==="function"?o.pass():o.pass)}function vJ(){if(U.statement=L.statement,U.statement.columns=[],L.onlyDescribe)return L.resolve(L.statement),ho(St)}function qJ(J){w.pid=J.readUInt32BE(5),w.secret=J.readUInt32BE(9)}async function pJ(){no=!1,(await new wn([`
|
|
4
4
|
select b.oid, b.typarray
|
|
5
5
|
from pg_catalog.pg_type a
|
|
6
6
|
left join pg_catalog.pg_type b on b.oid = a.typelem
|
|
7
7
|
where a.typcategory = 'A'
|
|
8
8
|
group by b.oid, b.typarray
|
|
9
9
|
order by b.oid
|
|
10
|
-
`],[],oS)).forEach(({oid:W,typarray:
|
|
10
|
+
`],[],oS)).forEach(({oid:W,typarray:g})=>ZJ(W,g))}function ZJ(J,W){if(!!o.parsers[W]&&!!o.serializers[W])return;const g=o.parsers[J];o.shared.typeArrayMap[J]=W,o.parsers[W]=(yo)=>x$(yo,g,W),o.parsers[W].array=!0,o.serializers[W]=(yo)=>h$(yo,o.serializers[J],o,W)}function PJ(J,W){return J==="read-write"&&W.default_transaction_read_only==="on"||J==="read-only"&&W.default_transaction_read_only==="off"||J==="primary"&&W.in_hot_standby==="on"||J==="standby"&&W.in_hot_standby==="off"||J==="prefer-standby"&&W.in_hot_standby==="off"&&o.host[jo]}function gJ(){const J=new wn([`
|
|
11
11
|
show transaction_read_only;
|
|
12
12
|
select pg_catalog.pg_is_in_recovery()
|
|
13
|
-
`],[],oS,null,{simple:!0});J.resolve=([[W],[
|
|
13
|
+
`],[],oS,null,{simple:!0});J.resolve=([[W],[g]])=>{So.default_transaction_read_only=W.transaction_read_only,So.in_hot_standby=g.pg_is_in_recovery?"on":"off"},J.execute()}function lJ(J){L&&(L.cursorFn||L.describeFirst)&&ho(St);const W=Io.postgres(yM(J));L&&L.retried?In(L.retried):L&&L.prepared&&tR.has(W.routine)?eJ(L,W):In(W)}function eJ(J,W){delete _o[J.signature],J.retried=W,oS(J)}function dJ(J){if(!I)return;let W=9;while(J[W++]!==0);I(J.toString("utf8",9,W-1),J.toString("utf8",W,J.length-1))}async function uJ(){try{const J=await Promise.resolve(L.cursorFn(U));Co=0,J===Lt?ho(yy(L.portal)):(U=new Ot,ho(dM("",L.cursorRows)))}catch(J){ho(St),L.reject(J)}}function aJ(){U.count&&L.cursorFn(U),L.resolve(U)}function sJ(){Bo=new JM.Writable({autoDestroy:!0,write(J,W,g){_.write(P().d().raw(J).end(),g)},destroy(J,W){W(J),_.write(P().f().str(J+P.N).end()),Bo=null},final(J){_.write(P().c().end()),st=J}}),L.resolve(Bo)}function oy(){Bo=new JM.Readable({read(){_.resume()}}),L.resolve(Bo)}function ny(){Bo=new JM.Duplex({autoDestroy:!0,read(){_.resume()},write(J,W,g){_.write(P().d().raw(J).end(),g)},destroy(J,W){W(J),_.write(P().f().str(J+P.N).end()),Bo=null},final(J){_.write(P().c().end()),st=J}}),L.resolve(Bo)}function ty(J){Bo&&(Bo.push(J.subarray(5))||_.pause())}function Sy(){Bo&&Bo.push(null),Bo=null}function fy(J){G?G(yM(J)):console.log(yM(J))}function Ty(){}function My(){In(Io.notSupported("FunctionCallResponse"))}function Fy(){In(Io.notSupported("NegotiateProtocolVersion"))}function ky(J){console.error("Postgres.js : Unknown Message:",J[0])}function Ay(J,W){console.error("Postgres.js : Unknown Auth:",W)}function $y(J,W,g="",yo=""){let Do,Zo;return P().B().str(yo+P.N).str(g+P.N).i16(0).i16(J.length),J.forEach((eo,en)=>{if(eo===null)return P.i32(4294967295);Zo=W[en],J[en]=eo=Zo in o.serializers?o.serializers[Zo](eo):""+eo,Do=P.i,P.inc(4).str(eo).i32(P.i-Do-4,Do)}),P.i16(0),P.end()}function eM(J,W,g,yo=""){return P().P().str(yo+P.N).str(J+P.N).i16(W.length),W.forEach((Do,Zo)=>P.i32(g[Zo]||0)),P.end()}function Jy(J,W=""){return P().D().str(J).str(W+P.N).end()}function dM(J="",W=0){return Buffer.concat([P().E().str(J+P.N).i32(W).end(),p$])}function yy(J=""){return Buffer.concat([P().C().str("P").str(J+P.N).end(),P().S().end()])}function Ry(){return c||P().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:F,database:$,client_encoding:"UTF8"},o.connection)).filter(([,J])=>J).map(([J,W])=>J+P.N+W).join(P.N)).z(2).end(0)}}function yM(o){const n={};let t=5;for(let S=5;S<o.length-1;S++)if(o[S]===0)n[SR[o[t]]]=o.toString("utf8",t+1,S),t=S+1;return n}function Z$(o){return QS.createHash("md5").update(o).digest("hex")}function Bf(o,n){return QS.createHmac("sha256",o).update(n).digest()}function fR(o){return QS.createHash("sha256").update(o).digest()}function TR(o,n){const t=Math.max(o.length,n.length),S=Buffer.allocUnsafe(t);for(let f=0;f<t;f++)S[f]=o[f]^n[f];return S}function RM(o,n){if(n=typeof n==="function"?n():n,!n)return{cancel:jt,start:jt};let t;return{cancel(){t&&(clearTimeout(t),t=null)},start(){t&&clearTimeout(t),t=setTimeout(S,n*1000,arguments)}};function S(f){o.apply(null,f),t=null}}var OM=P$,ay=1,St=P().S().end(),p$=P().H().end(),sy=P().i32(8).i32(80877103).end(8),oR=Buffer.concat([P().E().str(P.N).i32(0).end(),St]),nR=P().D().str("S").str(P.N).end(),jt=()=>{},tR=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),SR={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 MR(o){return new Date(Date.UTC(2000,0,1)+Number(o/BigInt(1000)))}function FR(o,n,t,S,f){const T=(M,[F,k])=>(M[F.charCodeAt(0)]=k,M);Object.entries({R:(M)=>{let F=1;const k=n[M.readUInt32BE(F)]={schema:M.toString("utf8",F+=4,F=M.indexOf(0,F))||"pg_catalog",table:M.toString("utf8",F+1,F=M.indexOf(0,F+1)),columns:Array(M.readUInt16BE(F+=2)),keys:[]};F+=2;let A=0,$;while(F<M.length)$=k.columns[A++]={key:M[F++],name:f.column.from?f.column.from(M.toString("utf8",F,F=M.indexOf(0,F))):M.toString("utf8",F,F=M.indexOf(0,F)),type:M.readUInt32BE(F+=1),parser:t[M.readUInt32BE(F)],atttypmod:M.readUInt32BE(F+=4)},$.key&&k.keys.push($),F+=4},Y:()=>{},O:()=>{},B:(M)=>{n.date=MR(M.readBigInt64BE(9)),n.lsn=M.subarray(1,9)},I:(M)=>{let F=1;const k=n[M.readUInt32BE(F)],{row:A}=cf(M,k.columns,F+=7,f);S(A,{command:"insert",relation:k})},D:(M)=>{let F=1;const k=n[M.readUInt32BE(F)];F+=4;const A=M[F]===75;S(A||M[F]===79?cf(M,k.columns,F+=3,f).row:null,{command:"delete",relation:k,key:A})},U:(M)=>{let F=1;const k=n[M.readUInt32BE(F)];F+=4;const A=M[F]===75,$=A||M[F]===79?cf(M,k.columns,F+=3,f):null;$&&(F=$.i);const{row:O}=cf(M,k.columns,F+3,f);S(O,{command:"update",relation:k,key:A,old:$&&$.row})},T:()=>{},C:()=>{}}).reduce(T,{})[o[0]](o)}function cf(o,n,t,S){let f,T,M;const F=S.raw?new Array(n.length):{};for(let k=0;k<n.length;k++)f=o[t++],T=n[k],M=f===110?null:f===117?void 0:T.parser===void 0?o.toString("utf8",t+4,t+=4+o.readUInt32BE(t)):T.parser.array===!0?T.parser(o.toString("utf8",t+5,t+=4+o.readUInt32BE(t))):T.parser(o.toString("utf8",t+4,t+=4+o.readUInt32BE(t))),S.raw?F[k]=S.raw===!0?M:S.value.from?S.value.from(M,T):M:F[T.name]=S.value.from?S.value.from(M,T):M;return{i:t,row:S.row.from?S.row.from(F):F}}function kR(o){const n=o.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!n)throw new Error("Malformed subscribe pattern: "+o);const[,t,S,f]=n;return(t||"*")+(S?":"+(S.indexOf(".")===-1?"public."+S:S):"")+(f?"="+f:"")}var g$=()=>{};function WM(o,n){const t=new Map,S="postgresjs_"+Math.random().toString(36).slice(2),f={};let T,M,F=!1;const k=O.sql=o({...n,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...n.connection,replication:"database"},onclose:async function(){if(F)return;M=null,f.pid=f.secret=void 0,K(await G(k,S,n.publications)),t.forEach((H)=>H.forEach(({onsubscribe:V})=>V()))},no_subscribe:!0}),A=k.end,$=k.close;return k.end=async()=>{return F=!0,M&&await new Promise((H)=>(M.once("close",H),M.end())),A()},k.close=async()=>{return M&&await new Promise((H)=>(M.once("close",H),M.end())),$()},O;async function O(H,V,m=g$,j=g$){if(H=kR(H),!T)T=G(k,S,n.publications);const r={fn:V,onsubscribe:m},i=t.has(H)?t.get(H).add(r):t.set(H,new Set([r])).get(H),X=()=>{i.delete(r),i.size===0&&t.delete(H)};return T.then((w)=>{return K(w),m(),M&&M.on("error",j),{unsubscribe:X,state:f,sql:k}})}function K(H){M=H.stream,f.pid=H.state.pid,f.secret=H.state.secret}async function G(H,V,m){if(!m)throw new Error("Missing publication names");const j=await H.unsafe(`CREATE_REPLICATION_SLOT ${V} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[r]=j,i=await H.unsafe(`START_REPLICATION SLOT ${V} LOGICAL ${r.consistent_point} (proto_version '1', publication_names '${m}')`).writable(),X={lsn:Buffer.concat(r.consistent_point.split("/").map((_)=>Buffer.from(("00000000"+_).slice(-8),"hex")))};return i.on("data",z),i.on("error",w),i.on("close",H.close),{stream:i,state:j.state};function w(_){console.error("Unexpected error during logical streaming - reconnecting",_)}function z(_){if(_[0]===119)FR(_.subarray(25),X,H.options.parsers,B,n.transform);else if(_[0]===107&&_[17])X.lsn=_.subarray(1,9),N()}function B(_,c){const U=c.relation.schema+"."+c.relation.table;I("*",_,c),I("*:"+U,_,c),c.relation.keys.length&&I("*:"+U+"="+c.relation.keys.map((l)=>_[l.name]),_,c),I(c.command,_,c),I(c.command+":"+U,_,c),c.relation.keys.length&&I(c.command+":"+U+"="+c.relation.keys.map((l)=>_[l.name]),_,c)}function N(){const _=Buffer.alloc(34);_[0]="r".charCodeAt(0),_.fill(X.lsn,1),_.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),i.write(_)}}function I(H,V,m){t.has(H)&&t.get(H).forEach(({fn:j})=>j(V,m,H))}}import l$ from"stream";function _M(o,n,t=393216){return new Promise(async(S,f)=>{await o.begin(async(T)=>{let M;!n&&([{oid:n}]=await T`select lo_creat(-1) as oid`);const[{fd:F}]=await T`select lo_open(${n}, ${t}) as fd`,k={writable:$,readable:A,close:()=>T`select lo_close(${F})`.then(M),tell:()=>T`select lo_tell64(${F})`,read:(O)=>T`select loread(${F}, ${O}) as data`,write:(O)=>T`select lowrite(${F}, ${O})`,truncate:(O)=>T`select lo_truncate64(${F}, ${O})`,seek:(O,K=0)=>T`select lo_lseek64(${F}, ${O}, ${K})`,size:()=>T`
|
|
14
14
|
select
|
|
15
15
|
lo_lseek64(${F}, location, 0) as position,
|
|
16
16
|
seek.size
|
|
@@ -20,10 +20,10 @@ var My=Object.defineProperty;var Fy=(o,n)=>{for(var t in n)My(o,t,{get:n[t],enum
|
|
|
20
20
|
tell.location
|
|
21
21
|
from (select lo_tell64($1) as location) tell
|
|
22
22
|
) seek
|
|
23
|
-
`};return S(k),new Promise(async(O)=>M=O);async function A({highWaterMark:O=16384,start:w=0,end:G=1/0}={}){let r=G-w;return w&&await k.seek(w),new x$.Readable({highWaterMark:O,async read(H){const D=H>r?H-r:H;r-=H;const[{data:I}]=await k.read(D);if(this.push(I),I.length<H)this.push(null)}})}async function $({highWaterMark:O=16384,start:w=0}={}){return w&&await k.seek(w),new x$.Writable({highWaterMark:O,write(G,r,H){k.write(G).then(()=>H(),H)}})}}).catch(f)})}function Bf(o,n){const t=fR(o,n),S=t.no_subscribe||$M(Bf,{...t});let f=!1;const T=Jn(),M=Jn(),F=Jn(),k=Jn(),A=Jn(),$=Jn(),O=Jn(),w=Jn(),G={connecting:M,reserved:F,closed:k,ended:A,open:$,busy:O,full:w},r=[...Array(t.max)].map(()=>AM(t,G,{onopen:Wo,onend:to,onclose:Mn})),H=D(i);return Object.assign(H,{get parameters(){return t.parameters},largeObject:JM.bind(null,H),subscribe:S,CLOSE:Lt,END:Lt,PostgresError:It,options:t,reserve:N,listen:I,begin:P,close:C,end:h}),H;function D(E){return E.debug=t.debug,Object.entries(t.types).reduce((fo,[_o,ro])=>{return fo[_o]=(Ho)=>new cn(Ho,ro.to),fo},x),Object.assign(To,{types:x,typed:x,unsafe:Jo,notify:v,array:Q,json:K,file:Io}),To;function x(fo,_o){return new cn(fo,_o)}function To(fo,..._o){return fo&&Array.isArray(fo.raw)?new wn(fo,_o,E,_):typeof fo==="string"&&!_o.length?new mS(t.transform.column.to?t.transform.column.to(fo):fo):new Vf(fo,_o)}function Jo(fo,_o=[],ro={}){return arguments.length===2&&!Array.isArray(_o)&&(ro=_o,_o=[]),new wn([fo],_o,E,_,{prepare:!1,...ro,simple:"simple"in ro?ro.simple:_o.length===0})}function Io(fo,_o=[],ro={}){return arguments.length===2&&!Array.isArray(_o)&&(ro=_o,_o=[]),new wn([],_o,(Xo)=>{SR.readFile(fo,"utf8",(vo,wo)=>{if(vo)return Xo.reject(vo);Xo.strings=[wo],E(Xo)})},_,{...ro,simple:"simple"in ro?ro.simple:_o.length===0})}}async function I(E,x,To){const Jo={fn:x,onlisten:To},Io=I.sql||(I.sql=Bf({...t,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(I.channels).forEach(([Xo,{listeners:vo}])=>{delete I.channels[Xo],Promise.all(vo.map((wo)=>I(Xo,wo.fn,wo.onlisten).catch(()=>{})))})},onnotify(Xo,vo){Xo in I.channels&&I.channels[Xo].listeners.forEach((wo)=>wo.fn(vo))}})),fo=I.channels||(I.channels={});if(E in fo){fo[E].listeners.push(Jo);const Xo=await fo[E].result;return Jo.onlisten&&Jo.onlisten(),{state:Xo.state,unlisten:Ho}}fo[E]={result:Io`listen ${Io.unsafe('"'+E.replace(/"/g,'""')+'"')}`,listeners:[Jo]};const ro=await fo[E].result;return Jo.onlisten&&Jo.onlisten(),{state:ro.state,unlisten:Ho};async function Ho(){if(E in fo===!1)return;if(fo[E].listeners=fo[E].listeners.filter((Xo)=>Xo!==Jo),fo[E].listeners.length)return;return delete fo[E],Io`unlisten ${Io.unsafe('"'+E.replace(/"/g,'""')+'"')}`}}async function v(E,x){return await H`select pg_notify(${E}, ${""+x})`}async function N(){const E=Jn(),x=$.length?$.shift():await new Promise((Io)=>{T.push({reserve:Io}),k.length&&So(k.shift())});Y(x,F),x.reserved=()=>E.length?x.execute(E.shift()):Y(x,F),x.reserved.release=!0;const To=D(Jo);return To.release=()=>{x.reserved=null,Wo(x)},To;function Jo(Io){x.queue===w?E.push(Io):x.execute(Io)||Y(x,w)}}async function P(E,x){!x&&(x=E,E="");const To=Jn();let Jo=0,Io,fo=null;try{return await H.unsafe("begin "+E.replace(/[^a-z ]/ig,""),[],{onexecute:ro}).execute(),await Promise.race([_o(Io,x),new Promise((Ho,Xo)=>Io.onclose=Xo)])}catch(Ho){throw Ho}async function _o(Ho,Xo,vo){const wo=D(jo);wo.savepoint=gn,wo.prepare=(Yo)=>fo=Yo.replace(/[^a-z0-9$-_. ]/gi);let Xn,qo;vo&&await wo`savepoint ${wo(vo)}`;try{if(qo=await new Promise((Yo,Yn)=>{const Ln=Xo(wo);Promise.resolve(Array.isArray(Ln)?Promise.all(Ln):Ln).then(Yo,Yn)}),Xn)throw Xn}catch(Yo){throw await(vo?wo`rollback to ${wo(vo)}`:wo`rollback`),Yo instanceof It&&Yo.code==="25P02"&&Xn||Yo}if(!vo)fo?await wo`prepare transaction '${wo.unsafe(fo)}'`:await wo`commit`;return qo;function gn(Yo,Yn){if(Yo&&Array.isArray(Yo.raw))return gn((Ln)=>Ln.apply(Ln,arguments));return arguments.length===1&&(Yn=Yo,Yo=null),_o(Ho,Yn,"s"+Jo+++(Yo?"_"+Yo:""))}function jo(Yo){Yo.catch((Yn)=>Xn||(Xn=Yn)),Ho.queue===w?To.push(Yo):Ho.execute(Yo)||Y(Ho,w)}}function ro(Ho){Io=Ho,Y(Ho,F),Ho.reserved=()=>To.length?Ho.execute(To.shift()):Y(Ho,F)}}function Y(E,x){return E.queue.remove(E),x.push(E),E.queue=x,x===$?E.idleTimer.start():E.idleTimer.cancel(),E}function K(E){return new cn(E,3802)}function Q(E,x){if(!Array.isArray(E))return Q(Array.from(arguments));return new cn(E,x||(E.length?Df(E)||25:0),t.shared.typeArrayMap)}function i(E){if(f)return E.reject(Lo.connection("CONNECTION_ENDED",t,t));if($.length)return g($.shift(),E);if(k.length)return So(k.shift(),E);O.length?g(O.shift(),E):T.push(E)}function g(E,x){return E.execute(x)?Y(E,O):Y(E,w)}function _(E){return new Promise((x,To)=>{E.state?E.active?AM(t).cancel(E.state,x,To):E.cancelled={resolve:x,reject:To}:(T.remove(E),E.cancelled=!0,E.reject(Lo.generic("57014","canceling statement due to user request")),x())})}async function h({timeout:E=null}={}){if(f)return f;await 1;let x;return f=Promise.race([new Promise((To)=>E!==null&&(x=setTimeout(a,E*1000,To))),Promise.all(r.map((To)=>To.end()).concat(I.sql?I.sql.end({timeout:0}):[],S.sql?S.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(x))}async function C(){await Promise.all(r.map((E)=>E.end()))}async function a(E){await Promise.all(r.map((x)=>x.terminate()));while(T.length)T.shift().reject(Lo.connection("CONNECTION_DESTROYED",t));E()}function So(E,x){return Y(E,M),E.connect(x),E}function to(E){Y(E,A)}function Wo(E){if(T.length===0)return Y(E,$);let x=Math.ceil(T.length/(M.length+1)),To=!0;while(To&&T.length&&x-- >0){const Jo=T.shift();if(Jo.reserve)return Jo.reserve(E);To=E.execute(Jo)}To?Y(E,O):Y(E,w)}function Mn(E,x){Y(E,k),E.reserved=null,E.onclose&&(E.onclose(x),E.onclose=null),t.onclose&&t.onclose(E.id),T.length&&So(E,T.shift())}}function fR(o,n){if(o&&o.shared)return o;const t=process.env,S=(!o||typeof o==="string"?n:o)||{},{url:f,multihost:T}=AR(o),M=[...f.searchParams].reduce((w,[G,r])=>(w[G]=r,w),{}),F=S.hostname||S.host||T||f.hostname||t.PGHOST||"localhost",k=S.port||f.port||t.PGPORT||5432,A=S.user||S.username||f.username||t.PGUSERNAME||t.PGUSER||$R();S.no_prepare&&(S.prepare=!1),M.sslmode&&(M.ssl=M.sslmode,delete M.sslmode),"timeout"in S&&(console.log("The timeout option is deprecated, use idle_timeout instead"),S.idle_timeout=S.timeout),M.sslrootcert==="system"&&(M.ssl="verify-full");const $=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],O={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:FR,max_pipeline:100,backoff:MR,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(F)?F:F.split(",").map((w)=>w.split(":")[0]),port:Array.isArray(k)?k:F.split(",").map((w)=>parseInt(w.split(":")[1]||k)),path:S.path||F.indexOf("/")>-1&&F+"/.s.PGSQL."+k,database:S.database||S.db||(f.pathname||"").slice(1)||t.PGDATABASE||A,user:A,pass:S.pass||S.password||f.password||t.PGPASSWORD||"",...Object.entries(O).reduce((w,[G,r])=>{const H=G in S?S[G]:(G in M)?M[G]==="disable"||M[G]==="false"?!1:M[G]:t["PG"+G.toUpperCase()]||r;return w[G]=typeof H==="string"&&$.includes(G)?+H:H,w},{}),connection:{application_name:"postgres.js",...S.connection,...Object.entries(M).reduce((w,[G,r])=>((G in O)||(w[G]=r),w),{})},types:S.types||{},target_session_attrs:TR(S,f,t),onnotice:S.onnotice,onnotify:S.onnotify,onclose:S.onclose,onparameter:S.onparameter,socket:S.socket,transform:kR(S.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...V$(S.types)}}function TR(o,n,t){const S=o.target_session_attrs||n.searchParams.get("target_session_attrs")||t.PGTARGETSESSIONATTRS;if(!S||["read-write","read-only","primary","standby","prefer-standby"].includes(S))return S;throw new Error("target_session_attrs "+S+" is not supported")}function MR(o){return(0.5+Math.random()/2)*Math.min(3**o/100,20)}function FR(){return 60*(30+Math.random()*30)}function kR(o){return{undefined:o.undefined,column:{from:typeof o.column==="function"?o.column:o.column&&o.column.from,to:o.column&&o.column.to},value:{from:typeof o.value==="function"?o.value:o.value&&o.value.from,to:o.value&&o.value.to},row:{from:typeof o.row==="function"?o.row:o.row&&o.row.from,to:o.row&&o.row.to}}}function AR(o){if(!o||typeof o!=="string")return{url:{searchParams:new Map}};let n=o;n=n.slice(n.indexOf("://")+3).split(/[?/]/)[0],n=decodeURIComponent(n.slice(n.indexOf("@")+1));const t=new URL(o.replace(n,n.split(",")[0]));return{url:{username:decodeURIComponent(t.username),password:decodeURIComponent(t.password),host:t.host,hostname:t.hostname,port:t.port,pathname:t.pathname,searchParams:t.searchParams},multihost:n.indexOf(",")>-1&&n}}function $R(){try{return tR.userInfo().username}catch(o){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}Object.assign(Bf,{PostgresError:It,toPascal:yt,pascal:fM,toCamel:Jt,camel:SM,toKebab:Rt,kebab:TM,fromPascal:zS,fromCamel:GS,fromKebab:HS,BigInt:{to:20,from:[20],parse:(o)=>BigInt(o),serialize:(o)=>o.toString()}});var Bt=Bf;class cf extends ao{constructor(o,n,t,S){super();this.session=n,this.dialect=t,this.config={table:o,withList:S}}static[y]="PgDelete";config;where(o){return this.config.where=o,this}returning(o=this.config.table[j.Symbol.Columns]){return this.config.returning=_n(o),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){const{typings:o,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(o){return Oo.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,o,!0)})}prepare(o){return this._prepare(o)}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o)})};$dynamic(){return this}}class bf{constructor(o,n,t,S){this.table=o,this.session=n,this.dialect=t,this.withList=S}static[y]="PgInsertBuilder";values(o){if(o=Array.isArray(o)?o:[o],o.length===0)throw new Error("values() must be called with at least one value");const n=o.map((t)=>{const S={},f=this.table[j.Symbol.Columns];for(let T of Object.keys(t)){const M=t[T];S[T]=X(M,b)?M:new An(M,f[T])}return S});return new i$(this.table,n,this.session,this.dialect,this.withList)}}class i$ extends ao{constructor(o,n,t,S,f){super();this.session=t,this.dialect=S,this.config={table:o,values:n,withList:f}}static[y]="PgInsert";config;returning(o=this.config.table[j.Symbol.Columns]){return this.config.returning=_n(o),this}onConflictDoNothing(o={}){if(o.target===void 0)this.config.onConflict=R`do nothing`;else{let n="";n=Array.isArray(o.target)?o.target.map((S)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(S))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(o.target));const t=o.where?R` where ${o.where}`:void 0;this.config.onConflict=R`(${R.raw(n)})${t} do nothing`}return this}onConflictDoUpdate(o){if(o.where&&(o.targetWhere||o.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');const n=o.where?R` where ${o.where}`:void 0,t=o.targetWhere?R` where ${o.targetWhere}`:void 0,S=o.setWhere?R` where ${o.setWhere}`:void 0,f=this.dialect.buildUpdateSet(this.config.table,Rf(this.config.table,o.set));let T="";return T=Array.isArray(o.target)?o.target.map((M)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(M))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(o.target)),this.config.onConflict=R`(${R.raw(T)})${t} do update set ${f}${n}${S}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){const{typings:o,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(o){return Oo.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,o,!0)})}prepare(o){return this._prepare(o)}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o)})};$dynamic(){return this}}function JR(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((t)=>t.toLowerCase()).join("_")}function yR(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((t,S,f)=>{const T=f===0?S.toLowerCase():`${S[0].toUpperCase()}${S.slice(1)}`;return t+T},"")}function RR(o){return o}class yM{static[y]="CasingCache";cache={};cachedTables={};convert;constructor(o){this.convert=o==="snake_case"?JR:o==="camelCase"?yR:RR}getColumnCasing(o){if(!o.keyAsName)return o.name;const n=o.table[j.Symbol.Schema]??"public",t=o.table[j.Symbol.OriginalName],S=`${n}.${t}.${o.name}`;if(!this.cache[S])this.cacheTable(o.table);return this.cache[S]}cacheTable(o){const n=o[j.Symbol.Schema]??"public",t=o[j.Symbol.OriginalName],S=`${n}.${t}`;if(!this.cachedTables[S]){for(let f of Object.values(o[j.Symbol.Columns])){const T=`${S}.${f.name}`;this.cache[T]=this.convert(f.name)}this.cachedTables[S]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class DS extends Sn{static[y]="PgViewBase"}class Wt{static[y]="PgDialect";casing;constructor(o){this.casing=new yM(o?.casing)}async migrate(o,n,t){const S=typeof t==="string"?"__drizzle_migrations":t.migrationsTable??"__drizzle_migrations",f=typeof t==="string"?"drizzle":t.migrationsSchema??"drizzle",T=R`
|
|
23
|
+
`};return S(k),new Promise(async(O)=>M=O);async function A({highWaterMark:O=16384,start:K=0,end:G=1/0}={}){let I=G-K;return K&&await k.seek(K),new l$.Readable({highWaterMark:O,async read(H){const V=H>I?H-I:H;I-=H;const[{data:m}]=await k.read(V);if(this.push(m),m.length<H)this.push(null)}})}async function $({highWaterMark:O=16384,start:K=0}={}){return K&&await k.seek(K),new l$.Writable({highWaterMark:O,write(G,I,H){k.write(G).then(()=>H(),H)}})}}).catch(f)})}function bf(o,n){const t=JR(o,n),S=t.no_subscribe||WM(bf,{...t});let f=!1;const T=Jn(),M=Jn(),F=Jn(),k=Jn(),A=Jn(),$=Jn(),O=Jn(),K=Jn(),G={connecting:M,reserved:F,closed:k,ended:A,open:$,busy:O,full:K},I=[...Array(t.max)].map(()=>OM(t,G,{onopen:_o,onend:So,onclose:Fn})),H=V(B);return Object.assign(H,{get parameters(){return t.parameters},largeObject:_M.bind(null,H),subscribe:S,CLOSE:Lt,END:Lt,PostgresError:It,options:t,reserve:r,listen:m,begin:i,close:U,end:c}),H;function V(E){return E.debug=t.debug,Object.entries(t.types).reduce((fo,[wo,Co])=>{return fo[wo]=(Ho)=>new cn(Ho,Co.to),fo},p),Object.assign(To,{types:p,typed:p,unsafe:Ro,notify:j,array:z,json:w,file:jo}),To;function p(fo,wo){return new cn(fo,wo)}function To(fo,...wo){return fo&&Array.isArray(fo.raw)?new wn(fo,wo,E,_):typeof fo==="string"&&!wo.length?new mS(t.transform.column.to?t.transform.column.to(fo):fo):new Cf(fo,wo)}function Ro(fo,wo=[],Co={}){return arguments.length===2&&!Array.isArray(wo)&&(Co=wo,wo=[]),new wn([fo],wo,E,_,{prepare:!1,...Co,simple:"simple"in Co?Co.simple:wo.length===0})}function jo(fo,wo=[],Co={}){return arguments.length===2&&!Array.isArray(wo)&&(Co=wo,wo=[]),new wn([],wo,(Yo)=>{$R.readFile(fo,"utf8",(vo,Ko)=>{if(vo)return Yo.reject(vo);Yo.strings=[Ko],E(Yo)})},_,{...Co,simple:"simple"in Co?Co.simple:wo.length===0})}}async function m(E,p,To){const Ro={fn:p,onlisten:To},jo=m.sql||(m.sql=bf({...t,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(m.channels).forEach(([Yo,{listeners:vo}])=>{delete m.channels[Yo],Promise.all(vo.map((Ko)=>m(Yo,Ko.fn,Ko.onlisten).catch(()=>{})))})},onnotify(Yo,vo){Yo in m.channels&&m.channels[Yo].listeners.forEach((Ko)=>Ko.fn(vo))}})),fo=m.channels||(m.channels={});if(E in fo){fo[E].listeners.push(Ro);const Yo=await fo[E].result;return Ro.onlisten&&Ro.onlisten(),{state:Yo.state,unlisten:Ho}}fo[E]={result:jo`listen ${jo.unsafe('"'+E.replace(/"/g,'""')+'"')}`,listeners:[Ro]};const Co=await fo[E].result;return Ro.onlisten&&Ro.onlisten(),{state:Co.state,unlisten:Ho};async function Ho(){if(E in fo===!1)return;if(fo[E].listeners=fo[E].listeners.filter((Yo)=>Yo!==Ro),fo[E].listeners.length)return;return delete fo[E],jo`unlisten ${jo.unsafe('"'+E.replace(/"/g,'""')+'"')}`}}async function j(E,p){return await H`select pg_notify(${E}, ${""+p})`}async function r(){const E=Jn(),p=$.length?$.shift():await new Promise((jo)=>{T.push({reserve:jo}),k.length&&no(k.shift())});X(p,F),p.reserved=()=>E.length?p.execute(E.shift()):X(p,F),p.reserved.release=!0;const To=V(Ro);return To.release=()=>{p.reserved=null,_o(p)},To;function Ro(jo){p.queue===K?E.push(jo):p.execute(jo)||X(p,K)}}async function i(E,p){!p&&(p=E,E="");const To=Jn();let Ro=0,jo,fo=null;try{return await H.unsafe("begin "+E.replace(/[^a-z ]/ig,""),[],{onexecute:Co}).execute(),await Promise.race([wo(jo,p),new Promise((Ho,Yo)=>jo.onclose=Yo)])}catch(Ho){throw Ho}async function wo(Ho,Yo,vo){const Ko=V(Bo);Ko.savepoint=ln,Ko.prepare=(Eo)=>fo=Eo.replace(/[^a-z0-9$-_. ]/gi);let Xn,qo;vo&&await Ko`savepoint ${Ko(vo)}`;try{if(qo=await new Promise((Eo,Yn)=>{const Ln=Yo(Ko);Promise.resolve(Array.isArray(Ln)?Promise.all(Ln):Ln).then(Eo,Yn)}),Xn)throw Xn}catch(Eo){throw await(vo?Ko`rollback to ${Ko(vo)}`:Ko`rollback`),Eo instanceof It&&Eo.code==="25P02"&&Xn||Eo}if(!vo)fo?await Ko`prepare transaction '${Ko.unsafe(fo)}'`:await Ko`commit`;return qo;function ln(Eo,Yn){if(Eo&&Array.isArray(Eo.raw))return ln((Ln)=>Ln.apply(Ln,arguments));return arguments.length===1&&(Yn=Eo,Eo=null),wo(Ho,Yn,"s"+Ro+++(Eo?"_"+Eo:""))}function Bo(Eo){Eo.catch((Yn)=>Xn||(Xn=Yn)),Ho.queue===K?To.push(Eo):Ho.execute(Eo)||X(Ho,K)}}function Co(Ho){jo=Ho,X(Ho,F),Ho.reserved=()=>To.length?Ho.execute(To.shift()):X(Ho,F)}}function X(E,p){return E.queue.remove(E),p.push(E),E.queue=p,p===$?E.idleTimer.start():E.idleTimer.cancel(),E}function w(E){return new cn(E,3802)}function z(E,p){if(!Array.isArray(E))return z(Array.from(arguments));return new cn(E,p||(E.length?Vf(E)||25:0),t.shared.typeArrayMap)}function B(E){if(f)return E.reject(Io.connection("CONNECTION_ENDED",t,t));if($.length)return N($.shift(),E);if(k.length)return no(k.shift(),E);O.length?N(O.shift(),E):T.push(E)}function N(E,p){return E.execute(p)?X(E,O):X(E,K)}function _(E){return new Promise((p,To)=>{E.state?E.active?OM(t).cancel(E.state,p,To):E.cancelled={resolve:p,reject:To}:(T.remove(E),E.cancelled=!0,E.reject(Io.generic("57014","canceling statement due to user request")),p())})}async function c({timeout:E=null}={}){if(f)return f;await 1;let p;return f=Promise.race([new Promise((To)=>E!==null&&(p=setTimeout(l,E*1000,To))),Promise.all(I.map((To)=>To.end()).concat(m.sql?m.sql.end({timeout:0}):[],S.sql?S.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(p))}async function U(){await Promise.all(I.map((E)=>E.end()))}async function l(E){await Promise.all(I.map((p)=>p.terminate()));while(T.length)T.shift().reject(Io.connection("CONNECTION_DESTROYED",t));E()}function no(E,p){return X(E,M),E.connect(p),E}function So(E){X(E,A)}function _o(E){if(T.length===0)return X(E,$);let p=Math.ceil(T.length/(M.length+1)),To=!0;while(To&&T.length&&p-- >0){const Ro=T.shift();if(Ro.reserve)return Ro.reserve(E);To=E.execute(Ro)}To?X(E,O):X(E,K)}function Fn(E,p){X(E,k),E.reserved=null,E.onclose&&(E.onclose(p),E.onclose=null),t.onclose&&t.onclose(E.id),T.length&&no(E,T.shift())}}function JR(o,n){if(o&&o.shared)return o;const t=process.env,S=(!o||typeof o==="string"?n:o)||{},{url:f,multihost:T}=_R(o),M=[...f.searchParams].reduce((K,[G,I])=>(K[G]=I,K),{}),F=S.hostname||S.host||T||f.hostname||t.PGHOST||"localhost",k=S.port||f.port||t.PGPORT||5432,A=S.user||S.username||f.username||t.PGUSERNAME||t.PGUSER||wR();S.no_prepare&&(S.prepare=!1),M.sslmode&&(M.ssl=M.sslmode,delete M.sslmode),"timeout"in S&&(console.log("The timeout option is deprecated, use idle_timeout instead"),S.idle_timeout=S.timeout),M.sslrootcert==="system"&&(M.ssl="verify-full");const $=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],O={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:OR,max_pipeline:100,backoff:RR,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(F)?F:F.split(",").map((K)=>K.split(":")[0]),port:Array.isArray(k)?k:F.split(",").map((K)=>parseInt(K.split(":")[1]||k)),path:S.path||F.indexOf("/")>-1&&F+"/.s.PGSQL."+k,database:S.database||S.db||(f.pathname||"").slice(1)||t.PGDATABASE||A,user:A,pass:S.pass||S.password||f.password||t.PGPASSWORD||"",...Object.entries(O).reduce((K,[G,I])=>{const H=G in S?S[G]:(G in M)?M[G]==="disable"||M[G]==="false"?!1:M[G]:t["PG"+G.toUpperCase()]||I;return K[G]=typeof H==="string"&&$.includes(G)?+H:H,K},{}),connection:{application_name:"postgres.js",...S.connection,...Object.entries(M).reduce((K,[G,I])=>((G in O)||(K[G]=I),K),{})},types:S.types||{},target_session_attrs:yR(S,f,t),onnotice:S.onnotice,onnotify:S.onnotify,onclose:S.onclose,onparameter:S.onparameter,socket:S.socket,transform:WR(S.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...b$(S.types)}}function yR(o,n,t){const S=o.target_session_attrs||n.searchParams.get("target_session_attrs")||t.PGTARGETSESSIONATTRS;if(!S||["read-write","read-only","primary","standby","prefer-standby"].includes(S))return S;throw new Error("target_session_attrs "+S+" is not supported")}function RR(o){return(0.5+Math.random()/2)*Math.min(3**o/100,20)}function OR(){return 60*(30+Math.random()*30)}function WR(o){return{undefined:o.undefined,column:{from:typeof o.column==="function"?o.column:o.column&&o.column.from,to:o.column&&o.column.to},value:{from:typeof o.value==="function"?o.value:o.value&&o.value.from,to:o.value&&o.value.to},row:{from:typeof o.row==="function"?o.row:o.row&&o.row.from,to:o.row&&o.row.to}}}function _R(o){if(!o||typeof o!=="string")return{url:{searchParams:new Map}};let n=o;n=n.slice(n.indexOf("://")+3).split(/[?/]/)[0],n=decodeURIComponent(n.slice(n.indexOf("@")+1));const t=new URL(o.replace(n,n.split(",")[0]));return{url:{username:decodeURIComponent(t.username),password:decodeURIComponent(t.password),host:t.host,hostname:t.hostname,port:t.port,pathname:t.pathname,searchParams:t.searchParams},multihost:n.indexOf(",")>-1&&n}}function wR(){try{return AR.userInfo().username}catch(o){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}Object.assign(bf,{PostgresError:It,toPascal:yt,pascal:AM,toCamel:Jt,camel:kM,toKebab:Rt,kebab:$M,fromPascal:zS,fromCamel:GS,fromKebab:HS,BigInt:{to:20,from:[20],parse:(o)=>BigInt(o),serialize:(o)=>o.toString()}});var Bt=bf;class Nf extends so{constructor(o,n,t,S){super();this.session=n,this.dialect=t,this.config={table:o,withList:S}}static[y]="PgDelete";config;where(o){return this.config.where=o,this}returning(o=this.config.table[h.Symbol.Columns]){return this.config.returning=_n(o),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){const{typings:o,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(o){return Wo.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,o,!0)})}prepare(o){return this._prepare(o)}execute=(o)=>{return Wo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o)})};$dynamic(){return this}}class hf{constructor(o,n,t,S){this.table=o,this.session=n,this.dialect=t,this.withList=S}static[y]="PgInsertBuilder";values(o){if(o=Array.isArray(o)?o:[o],o.length===0)throw new Error("values() must be called with at least one value");const n=o.map((t)=>{const S={},f=this.table[h.Symbol.Columns];for(let T of Object.keys(t)){const M=t[T];S[T]=Y(M,q)?M:new An(M,f[T])}return S});return new e$(this.table,n,this.session,this.dialect,this.withList)}}class e$ extends so{constructor(o,n,t,S,f){super();this.session=t,this.dialect=S,this.config={table:o,values:n,withList:f}}static[y]="PgInsert";config;returning(o=this.config.table[h.Symbol.Columns]){return this.config.returning=_n(o),this}onConflictDoNothing(o={}){if(o.target===void 0)this.config.onConflict=R`do nothing`;else{let n="";n=Array.isArray(o.target)?o.target.map((S)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(S))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(o.target));const t=o.where?R` where ${o.where}`:void 0;this.config.onConflict=R`(${R.raw(n)})${t} do nothing`}return this}onConflictDoUpdate(o){if(o.where&&(o.targetWhere||o.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');const n=o.where?R` where ${o.where}`:void 0,t=o.targetWhere?R` where ${o.targetWhere}`:void 0,S=o.setWhere?R` where ${o.setWhere}`:void 0,f=this.dialect.buildUpdateSet(this.config.table,Wf(this.config.table,o.set));let T="";return T=Array.isArray(o.target)?o.target.map((M)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(M))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(o.target)),this.config.onConflict=R`(${R.raw(T)})${t} do update set ${f}${n}${S}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){const{typings:o,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(o){return Wo.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,o,!0)})}prepare(o){return this._prepare(o)}execute=(o)=>{return Wo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o)})};$dynamic(){return this}}function KR(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((t)=>t.toLowerCase()).join("_")}function XR(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((t,S,f)=>{const T=f===0?S.toLowerCase():`${S[0].toUpperCase()}${S.slice(1)}`;return t+T},"")}function YR(o){return o}class wM{static[y]="CasingCache";cache={};cachedTables={};convert;constructor(o){this.convert=o==="snake_case"?KR:o==="camelCase"?XR:YR}getColumnCasing(o){if(!o.keyAsName)return o.name;const n=o.table[h.Symbol.Schema]??"public",t=o.table[h.Symbol.OriginalName],S=`${n}.${t}.${o.name}`;if(!this.cache[S])this.cacheTable(o.table);return this.cache[S]}cacheTable(o){const n=o[h.Symbol.Schema]??"public",t=o[h.Symbol.OriginalName],S=`${n}.${t}`;if(!this.cachedTables[S]){for(let f of Object.values(o[h.Symbol.Columns])){const T=`${S}.${f.name}`;this.cache[T]=this.convert(f.name)}this.cachedTables[S]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class DS extends fn{static[y]="PgViewBase"}class Wt{static[y]="PgDialect";casing;constructor(o){this.casing=new wM(o?.casing)}async migrate(o,n,t){const S=typeof t==="string"?"__drizzle_migrations":t.migrationsTable??"__drizzle_migrations",f=typeof t==="string"?"drizzle":t.migrationsSchema??"drizzle",T=R`
|
|
24
24
|
CREATE TABLE IF NOT EXISTS ${R.identifier(f)}.${R.identifier(S)} (
|
|
25
25
|
id SERIAL PRIMARY KEY,
|
|
26
26
|
hash text NOT NULL,
|
|
27
27
|
created_at bigint
|
|
28
28
|
)
|
|
29
|
-
`;await n.execute(R`CREATE SCHEMA IF NOT EXISTS ${R.identifier(f)}`),await n.execute(T);const F=(await n.all(R`select id, hash, created_at from ${R.identifier(f)}.${R.identifier(S)} order by created_at desc limit 1`))[0];await n.transaction(async(k)=>{for await(let A of o)if(!F||Number(F.created_at)<A.folderMillis){for(let $ of A.sql)await k.execute(R.raw($));await k.execute(R`insert into ${R.identifier(f)}.${R.identifier(S)} ("hash", "created_at") values(${A.hash}, ${A.folderMillis})`)}})}escapeName(o){return`"${o}"`}escapeParam(o){return`\$${o+1}`}escapeString(o){return`'${o.replace(/'/g,"''")}'`}buildWithCTE(o){if(!o?.length)return;const n=[R`with `];for(let[t,S]of o.entries())if(n.push(R`${R.identifier(S._.alias)} as (${S._.sql})`),t<o.length-1)n.push(R`, `);return n.push(R` `),R.join(n)}buildDeleteQuery({table:o,where:n,returning:t,withList:S}){const f=this.buildWithCTE(S),T=t?R` returning ${this.buildSelection(t,{isSingleTable:!0})}`:void 0,M=n?R` where ${n}`:void 0;return R`${f}delete from ${o}${M}${T}`}buildUpdateSet(o,n){const t=o[j.Symbol.Columns],S=Object.keys(t).filter((T)=>n[T]!==void 0||t[T]?.onUpdateFn!==void 0),f=S.length;return R.join(S.flatMap((T,M)=>{const F=t[T],k=n[T]??R.param(F.onUpdateFn(),F),A=R`${R.identifier(this.casing.getColumnCasing(F))} = ${k}`;if(M<f-1)return[A,R.raw(", ")];return[A]}))}buildUpdateQuery({table:o,set:n,where:t,returning:S,withList:f}){const T=this.buildWithCTE(f),M=this.buildUpdateSet(o,n),F=S?R` returning ${this.buildSelection(S,{isSingleTable:!0})}`:void 0,k=t?R` where ${t}`:void 0;return R`${T}update ${o} set ${M}${k}${F}`}buildSelection(o,{isSingleTable:n=!1}={}){const t=o.length,S=o.flatMap(({field:f},T)=>{const M=[];if(X(f,b.Aliased)&&f.isSelectionField)M.push(R.identifier(f.fieldAlias));else if(X(f,b.Aliased)||X(f,b)){const F=X(f,b.Aliased)?f.sql:f;if(n)M.push(new b(F.queryChunks.map((k)=>{if(X(k,U))return R.identifier(this.casing.getColumnCasing(k));return k})));else M.push(F);if(X(f,b.Aliased))M.push(R` as ${R.identifier(f.fieldAlias)}`)}else if(X(f,Ko))if(n)M.push(R.identifier(this.casing.getColumnCasing(f)));else M.push(f);if(T<t-1)M.push(R`, `);return M});return R.join(S)}buildSelectQuery({withList:o,fields:n,fieldsFlat:t,where:S,having:f,table:T,joins:M,orderBy:F,groupBy:k,limit:A,offset:$,lockingClause:O,distinct:w,setOperators:G}){const r=t??_n(n);for(let So of r)if(X(So.field,Ko)&&Wn(So.field.table)!==(X(T,xo)?T._.alias:X(T,DS)?T[mo].name:X(T,b)?void 0:Wn(T))&&!((to)=>M?.some(({alias:Wo})=>Wo===(to[j.Symbol.IsAlias]?Wn(to):to[j.Symbol.BaseName])))(So.field.table)){const to=Wn(So.field.table);throw new Error(`Your "${So.path.join("->")}" field references a column "${to}"."${So.field.name}", but the table "${to}" is not part of the query! Did you forget to join it?`)}const H=!M||M.length===0,D=this.buildWithCTE(o);let I;if(w)I=w===!0?R` distinct`:R` distinct on (${R.join(w.on,R`, `)})`;const v=this.buildSelection(r,{isSingleTable:H}),N=(()=>{if(X(T,j)&&T[j.Symbol.OriginalName]!==T[j.Symbol.Name]){let So=R`${R.identifier(T[j.Symbol.OriginalName])}`;if(T[j.Symbol.Schema])So=R`${R.identifier(T[j.Symbol.Schema])}.${So}`;return R`${So} ${R.identifier(T[j.Symbol.Name])}`}return T})(),P=[];if(M)for(let[So,to]of M.entries()){if(So===0)P.push(R` `);const Wo=to.table,Mn=to.lateral?R` lateral`:void 0;if(X(Wo,Qn)){const E=Wo[Qn.Symbol.Name],x=Wo[Qn.Symbol.Schema],To=Wo[Qn.Symbol.OriginalName],Jo=E===To?void 0:to.alias;P.push(R`${R.raw(to.joinType)} join${Mn} ${x?R`${R.identifier(x)}.`:void 0}${R.identifier(To)}${Jo&&R` ${R.identifier(Jo)}`} on ${to.on}`)}else if(X(Wo,Sn)){const E=Wo[mo].name,x=Wo[mo].schema,To=Wo[mo].originalName,Jo=E===To?void 0:to.alias;P.push(R`${R.raw(to.joinType)} join${Mn} ${x?R`${R.identifier(x)}.`:void 0}${R.identifier(To)}${Jo&&R` ${R.identifier(Jo)}`} on ${to.on}`)}else P.push(R`${R.raw(to.joinType)} join${Mn} ${Wo} on ${to.on}`);if(So<M.length-1)P.push(R` `)}const Y=R.join(P),K=S?R` where ${S}`:void 0,Q=f?R` having ${f}`:void 0;let i;if(F&&F.length>0)i=R` order by ${R.join(F,R`, `)}`;let g;if(k&&k.length>0)g=R` group by ${R.join(k,R`, `)}`;const _=typeof A==="object"||typeof A==="number"&&A>=0?R` limit ${A}`:void 0,h=$?R` offset ${$}`:void 0,C=R.empty();if(O){const So=R` for ${R.raw(O.strength)}`;if(O.config.of)So.append(R` of ${R.join(Array.isArray(O.config.of)?O.config.of:[O.config.of],R`, `)}`);if(O.config.noWait)So.append(R` no wait`);else if(O.config.skipLocked)So.append(R` skip locked`);C.append(So)}const a=R`${D}select${I} ${v} from ${N}${Y}${K}${g}${Q}${i}${_}${h}${C}`;if(G.length>0)return this.buildSetOperations(a,G);return a}buildSetOperations(o,n){const[t,...S]=n;if(!t)throw new Error("Cannot pass undefined values to any set operator");if(S.length===0)return this.buildSetOperationQuery({leftSelect:o,setOperator:t});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:o,setOperator:t}),S)}buildSetOperationQuery({leftSelect:o,setOperator:{type:n,isAll:t,rightSelect:S,limit:f,orderBy:T,offset:M}}){const F=R`(${o.getSQL()}) `,k=R`(${S.getSQL()})`;let A;if(T&&T.length>0){const G=[];for(let r of T)if(X(r,U))G.push(R.identifier(r.name));else if(X(r,b)){for(let H=0;H<r.queryChunks.length;H++){const D=r.queryChunks[H];if(X(D,U))r.queryChunks[H]=R.identifier(D.name)}G.push(R`${r}`)}else G.push(R`${r}`);A=R` order by ${R.join(G,R`, `)} `}const $=typeof f==="object"||typeof f==="number"&&f>=0?R` limit ${f}`:void 0,O=R.raw(`${n} ${t?"all ":""}`),w=M?R` offset ${M}`:void 0;return R`${F}${O}${k}${A}${$}${w}`}buildInsertQuery({table:o,values:n,onConflict:t,returning:S,withList:f}){const T=[],M=o[j.Symbol.Columns],F=Object.entries(M).filter(([G,r])=>!r.shouldDisableInsert()),k=F.map(([,G])=>R.identifier(this.casing.getColumnCasing(G)));for(let[G,r]of n.entries()){const H=[];for(let[D,I]of F){const v=r[D];if(v===void 0||X(v,An)&&v.value===void 0)if(I.defaultFn!==void 0){const N=I.defaultFn(),P=X(N,b)?N:R.param(N,I);H.push(P)}else if(!I.default&&I.onUpdateFn!==void 0){const N=I.onUpdateFn(),P=X(N,b)?N:R.param(N,I);H.push(P)}else H.push(R`default`);else H.push(v)}if(T.push(H),G<n.length-1)T.push(R`, `)}const A=this.buildWithCTE(f),$=R.join(T),O=S?R` returning ${this.buildSelection(S,{isSingleTable:!0})}`:void 0,w=t?R` on conflict ${t}`:void 0;return R`${A}insert into ${o} ${k} values ${$}${w}${O}`}buildRefreshMaterializedViewQuery({view:o,concurrently:n,withNoData:t}){const S=n?R` concurrently`:void 0,f=t?R` with no data`:void 0;return R`refresh materialized view${S} ${o}${f}`}prepareTyping(o){if(X(o,Kf)||X(o,wf))return"json";else if(X(o,Xf))return"decimal";else if(X(o,Yf))return"time";else if(X(o,Ef)||X(o,Gf))return"timestamp";else if(X(o,Of)||X(o,Wf))return"date";else if(X(o,zf))return"uuid";else return"none"}sqlToQuery(o,n){return o.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:n})}buildRelationalQueryWithoutPK({fullSchema:o,schema:n,tableNamesMap:t,table:S,tableConfig:f,queryConfig:T,tableAlias:M,nestedQueryRelation:F,joinOn:k}){let A=[],$,O,w=[],G;const r=[];if(T===!0)A=Object.entries(f.columns).map(([I,v])=>({dbKey:v.name,tsKey:I,field:Bn(v,M),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{const D=Object.fromEntries(Object.entries(f.columns).map(([K,Q])=>[K,Bn(Q,M)]));if(T.where){const K=typeof T.where==="function"?T.where(D,_$()):T.where;G=K&&wS(K,M)}const I=[];let v=[];if(T.columns){let K=!1;for(let[Q,i]of Object.entries(T.columns)){if(i===void 0)continue;if(Q in f.columns){if(!K&&i===!0)K=!0;v.push(Q)}}if(v.length>0)v=K?v.filter((Q)=>T.columns?.[Q]===!0):Object.keys(f.columns).filter((Q)=>!v.includes(Q))}else v=Object.keys(f.columns);for(let K of v){const Q=f.columns[K];I.push({tsKey:K,value:Q})}let N=[];if(T.with)N=Object.entries(T.with).filter((K)=>!!K[1]).map(([K,Q])=>({tsKey:K,queryConfig:Q,relation:f.relations[K]}));let P;if(T.extras){P=typeof T.extras==="function"?T.extras(D,{sql:R}):T.extras;for(let[K,Q]of Object.entries(P))I.push({tsKey:K,value:hT(Q,M)})}for(let{tsKey:K,value:Q}of I)A.push({dbKey:X(Q,b.Aliased)?Q.fieldAlias:f.columns[K].name,tsKey:K,field:X(Q,Ko)?Bn(Q,M):Q,relationTableTsKey:void 0,isJson:!1,selection:[]});let Y=typeof T.orderBy==="function"?T.orderBy(D,w$()):T.orderBy??[];if(!Array.isArray(Y))Y=[Y];w=Y.map((K)=>{if(X(K,Ko))return Bn(K,M);return wS(K,M)}),$=T.limit,O=T.offset;for(let{tsKey:K,queryConfig:Q,relation:i}of N){const g=X$(n,t,i),_=$t(i.referencedTable),h=t[_],C=`${M}_${K}`,a=KS(...g.fields.map((Wo,Mn)=>Ct(Bn(g.references[Mn],C),Bn(Wo,M)))),So=this.buildRelationalQueryWithoutPK({fullSchema:o,schema:n,tableNamesMap:t,table:o[h],tableConfig:n[h],queryConfig:X(i,nt)?Q===!0?{limit:1}:{...Q,limit:1}:Q,tableAlias:C,joinOn:a,nestedQueryRelation:i}),to=R`${R.identifier(C)}.${R.identifier("data")}`.as(K);r.push({on:R`true`,table:new xo(So.sql,{},C),alias:C,joinType:"left",lateral:!0}),A.push({dbKey:K,tsKey:K,field:to,relationTableTsKey:h,isJson:!0,selection:So.selection})}}if(A.length===0)throw new yf({message:`No fields selected for table "${f.tsName}" ("${M}")`});let H;if(G=KS(k,G),F){let D=R`json_build_array(${R.join(A.map(({field:N,tsKey:P,isJson:Y})=>Y?R`${R.identifier(`${M}_${P}`)}.${R.identifier("data")}`:X(N,b.Aliased)?N.sql:N),R`, `)})`;if(X(F,ES))D=R`coalesce(json_agg(${D}${w.length>0?R` order by ${R.join(w,R`, `)}`:void 0}), '[]'::json)`;const I=[{dbKey:"data",tsKey:"data",field:D.as("data"),isJson:!0,relationTableTsKey:f.tsName,selection:A}];if($!==void 0||O!==void 0||w.length>0)H=this.buildSelectQuery({table:Jf(S,M),fields:{},fieldsFlat:[{path:[],field:R.raw("*")}],where:G,limit:$,offset:O,orderBy:w,setOperators:[]}),G=void 0,$=void 0,O=void 0,w=[];else H=Jf(S,M);H=this.buildSelectQuery({table:X(H,Qn)?H:new xo(H,{},M),fields:{},fieldsFlat:I.map(({field:N})=>({path:[],field:X(N,Ko)?Bn(N,M):N})),joins:r,where:G,limit:$,offset:O,orderBy:w,setOperators:[]})}else H=this.buildSelectQuery({table:Jf(S,M),fields:{},fieldsFlat:A.map(({field:D})=>({path:[],field:X(D,Ko)?Bn(D,M):D})),joins:r,where:G,limit:$,offset:O,orderBy:w,setOperators:[]});return{tableTsKey:f.tsName,sql:H,selection:A}}}class Tn{static[y]="SelectionProxyHandler";config;constructor(o){this.config={...o}}get(o,n){if(n==="_")return{...o._,selectedFields:new Proxy(o._.selectedFields,this)};if(n===mo)return{...o[mo],selectedFields:new Proxy(o[mo].selectedFields,this)};if(typeof n==="symbol")return o[n];const S=(X(o,xo)?o._.selectedFields:X(o,Sn)?o[mo].selectedFields:o)[n];if(X(S,b.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!S.isSelectionField)return S.sql;const f=S.clone();return f.isSelectionField=!0,f}if(X(S,b)){if(this.config.sqlBehavior==="sql")return S;throw new Error(`You tried to reference "${n}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(X(S,Ko)){if(this.config.alias)return new Proxy(S,new rt(new Proxy(S.table,new _S(this.config.alias,this.config.replaceOriginalName??!1))));return S}if(typeof S!=="object"||S===null)return S;return new Proxy(S,new Tn(this.config))}}class RM{static[y]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}function ct(o,n){return(t,S,...f)=>{const T=[S,...f].map((M)=>({type:o,isAll:n,rightSelect:M}));for(let M of T)if(!qT(t.getSelectedFields(),M.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return t.addSetOperators(T)}}class so{static[y]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(o){if(this.fields=o.fields,this.session=o.session,this.dialect=o.dialect,o.withList)this.withList=o.withList;this.distinct=o.distinct}from(o){const n=!!this.fields;let t;if(this.fields)t=this.fields;else if(X(o,xo))t=Object.fromEntries(Object.keys(o._.selectedFields).map((S)=>[S,o[S]]));else if(X(o,DS))t=o[mo].selectedFields;else if(X(o,b))t={};else t=Gk(o);return new OM({table:o,fields:t,isPartialSelect:n,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}}class v$ extends RM{static[y]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:o,fields:n,isPartialSelect:t,session:S,dialect:f,withList:T,distinct:M}){super();this.config={withList:T,table:o,fields:{...n},distinct:M,setOperators:[]},this.isPartialSelect=t,this.session=S,this.dialect=f,this._={selectedFields:n},this.tableName=pT(o),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(o){return(n,t)=>{const S=this.tableName,f=pT(n);if(typeof f==="string"&&this.config.joins?.some((T)=>T.alias===f))throw new Error(`Alias "${f}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof S==="string")this.config.fields={[S]:this.config.fields};if(typeof f==="string"&&!X(n,b)){const T=X(n,xo)?n._.selectedFields:X(n,Sn)?n[mo].selectedFields:n[j.Symbol.Columns];this.config.fields[f]=T}}if(typeof t==="function")t=t(new Proxy(this.config.fields,new Tn({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:t,table:n,joinType:o,alias:f}),typeof f==="string")switch(o){case"left":{this.joinsNotNullableMap[f]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([T])=>[T,!1])),this.joinsNotNullableMap[f]=!0;break}case"inner":{this.joinsNotNullableMap[f]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([T])=>[T,!1])),this.joinsNotNullableMap[f]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");createSetOperator(o,n){return(t)=>{const S=typeof t==="function"?t(OR()):t;if(!qT(this.getSelectedFields(),S.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:o,isAll:n,rightSelect:S}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);intersectAll=this.createSetOperator("intersect",!0);except=this.createSetOperator("except",!1);exceptAll=this.createSetOperator("except",!0);addSetOperators(o){return this.config.setOperators.push(...o),this}where(o){if(typeof o==="function")o=o(new Proxy(this.config.fields,new Tn({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=o,this}having(o){if(typeof o==="function")o=o(new Proxy(this.config.fields,new Tn({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=o,this}groupBy(...o){if(typeof o[0]==="function"){const n=o[0](new Proxy(this.config.fields,new Tn({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(n)?n:[n]}else this.config.groupBy=o;return this}orderBy(...o){if(typeof o[0]==="function"){const n=o[0](new Proxy(this.config.fields,new Tn({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),t=Array.isArray(n)?n:[n];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=t;else this.config.orderBy=t}else{const n=o;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=n;else this.config.orderBy=n}return this}limit(o){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=o;else this.config.limit=o;return this}offset(o){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=o;else this.config.offset=o;return this}for(o,n={}){return this.config.lockingClause={strength:o,config:n},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){const{typings:o,...n}=this.dialect.sqlToQuery(this.getSQL());return n}as(o){return new Proxy(new xo(this.getSQL(),this.config.fields,o),new Tn({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new Tn({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class OM extends v${static[y]="PgSelect";_prepare(o){const{session:n,config:t,dialect:S,joinsNotNullableMap:f}=this;if(!n)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return Oo.startActiveSpan("drizzle.prepareQuery",()=>{const T=_n(t.fields),M=n.prepareQuery(S.sqlToQuery(this.getSQL()),T,o,!0);return M.joinsNotNullableMap=f,M})}prepare(o){return this._prepare(o)}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o)})}}Ek(OM,[ao]);var OR=()=>({union:WR,unionAll:_R,intersect:wR,intersectAll:KR,except:XR,exceptAll:YR}),WR=ct("union",!1),_R=ct("union",!0),wR=ct("intersect",!1),KR=ct("intersect",!0),XR=ct("except",!1),YR=ct("except",!0);class WM{static[y]="PgQueryBuilder";dialect;dialectConfig;constructor(o){this.dialect=X(o,Wt)?o:void 0,this.dialectConfig=X(o,Wt)?void 0:o}$with(o){const n=this;return{as(t){if(typeof t==="function")t=t(n);return new Proxy(new WS(t.getSQL(),t.getSelectedFields(),o,!0),new Tn({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}with(...o){const n=this;function t(T){return new so({fields:T??void 0,session:void 0,dialect:n.getDialect(),withList:o})}function S(T){return new so({fields:T??void 0,session:void 0,dialect:n.getDialect(),distinct:!0})}function f(T,M){return new so({fields:M??void 0,session:void 0,dialect:n.getDialect(),distinct:{on:T}})}return{select:t,selectDistinct:S,selectDistinctOn:f}}select(o){return new so({fields:o??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(o){return new so({fields:o??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(o,n){return new so({fields:n??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:o}})}getDialect(){if(!this.dialect)this.dialect=new Wt(this.dialectConfig);return this.dialect}}class _M extends ao{constructor(o,n,t){super();this.session=n,this.dialect=t,this.config={view:o}}static[y]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){const{typings:o,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(o){return Oo.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,o,!0)})}prepare(o){return this._prepare(o)}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o)})}}class Nf{constructor(o,n,t,S){this.table=o,this.session=n,this.dialect=t,this.withList=S}static[y]="PgUpdateBuilder";set(o){return new q$(this.table,Rf(this.table,o),this.session,this.dialect,this.withList)}}class q$ extends ao{constructor(o,n,t,S,f){super();this.session=t,this.dialect=S,this.config={set:n,table:o,withList:f}}static[y]="PgUpdate";config;where(o){return this.config.where=o,this}returning(o=this.config.table[j.Symbol.Columns]){return this.config.returning=_n(o),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){const{typings:o,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(o){return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,o,!0)}prepare(o){return this._prepare(o)}execute=(o)=>{return this._prepare().execute(o)};$dynamic(){return this}}class US extends b{constructor(o){super(US.buildEmbeddedCount(o.source,o.filters).queryChunks);this.params=o,this.mapWith(Number),this.session=o.session,this.sql=US.buildCount(o.source,o.filters)}sql;static[y]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(o,n){return R`(select count(*) from ${o}${R.raw(" where ").if(n)}${n})`}static buildCount(o,n){return R`select count(*) as count from ${o}${R.raw(" where ").if(n)}${n};`}then(o,n){return Promise.resolve(this.session.count(this.sql)).then(o,n)}catch(o){return this.then(void 0,o)}finally(o){return this.then((n)=>{return o?.(),n},(n)=>{throw o?.(),n})}}class KM{constructor(o,n,t,S,f,T,M){this.fullSchema=o,this.schema=n,this.tableNamesMap=t,this.table=S,this.tableConfig=f,this.dialect=T,this.session=M}static[y]="PgRelationalQueryBuilder";findMany(o){return new wM(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?o:{},"many")}findFirst(o){return new wM(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?{...o,limit:1}:{limit:1},"first")}}class wM extends ao{constructor(o,n,t,S,f,T,M,F,k){super();this.fullSchema=o,this.schema=n,this.tableNamesMap=t,this.table=S,this.tableConfig=f,this.dialect=T,this.session=M,this.config=F,this.mode=k}static[y]="PgRelationalQuery";_prepare(o){return Oo.startActiveSpan("drizzle.prepareQuery",()=>{const{query:n,builtQuery:t}=this._toSQL();return this.session.prepareQuery(t,void 0,o,!0,(S,f)=>{const T=S.map((M)=>Hf(this.schema,this.tableConfig,M,n.selection,f));if(this.mode==="first")return T[0];return T})})}prepare(o){return this._prepare(o)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){const o=this._getQuery(),n=this.dialect.sqlToQuery(o.sql);return{query:o,builtQuery:n}}toSQL(){return this._toSQL().builtQuery}execute(){return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute()})}}class XM extends ao{constructor(o,n,t,S){super();this.execute=o,this.sql=n,this.query=t,this.mapBatchResult=S}static[y]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(o,n){return n?this.mapBatchResult(o):o}_prepare(){return this}isResponseInArrayMode(){return!1}}class VS{constructor(o,n,t){if(this.dialect=o,this.session=n,this._=t?{schema:t.schema,fullSchema:t.fullSchema,tableNamesMap:t.tableNamesMap,session:n}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:n},this.query={},this._.schema)for(let[S,f]of Object.entries(this._.schema))this.query[S]=new KM(t.fullSchema,this._.schema,this._.tableNamesMap,t.fullSchema[S],f,o,n)}static[y]="PgDatabase";query;$with(o){const n=this;return{as(t){if(typeof t==="function")t=t(new WM(n.dialect));return new Proxy(new WS(t.getSQL(),t.getSelectedFields(),o,!0),new Tn({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}$count(o,n){return new US({source:o,filters:n,session:this.session})}with(...o){const n=this;function t(k){return new so({fields:k??void 0,session:n.session,dialect:n.dialect,withList:o})}function S(k){return new so({fields:k??void 0,session:n.session,dialect:n.dialect,withList:o,distinct:!0})}function f(k,A){return new so({fields:A??void 0,session:n.session,dialect:n.dialect,withList:o,distinct:{on:k}})}function T(k){return new Nf(k,n.session,n.dialect,o)}function M(k){return new bf(k,n.session,n.dialect,o)}function F(k){return new cf(k,n.session,n.dialect,o)}return{select:t,selectDistinct:S,selectDistinctOn:f,update:T,insert:M,delete:F}}select(o){return new so({fields:o??void 0,session:this.session,dialect:this.dialect})}selectDistinct(o){return new so({fields:o??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(o,n){return new so({fields:n??void 0,session:this.session,dialect:this.dialect,distinct:{on:o}})}update(o){return new Nf(o,this.session,this.dialect)}insert(o){return new bf(o,this.session,this.dialect)}delete(o){return new cf(o,this.session,this.dialect)}refreshMaterializedView(o){return new _M(o,this.session,this.dialect)}execute(o){const n=typeof o==="string"?R.raw(o):o.getSQL(),t=this.dialect.sqlToQuery(n),S=this.session.prepareQuery(t,void 0,void 0,!1);return new XM(()=>S.execute(),n,t,(f)=>S.mapResult(f,!0))}transaction(o,n){return this.session.transaction(o,n)}}function YM(o){return new p$(!0,o)}class p${constructor(o,n){this.unique=o,this.name=n}static[y]="PgIndexBuilderOn";on(...o){return new hf(o.map((n)=>{if(X(n,b))return n;n=n;const t=new OS(n.name,!!n.keyAsName,n.columnType,n.indexConfig);return n.indexConfig=JSON.parse(JSON.stringify(n.defaultConfig)),t}),this.unique,!1,this.name)}onOnly(...o){return new hf(o.map((n)=>{if(X(n,b))return n;n=n;const t=new OS(n.name,!!n.keyAsName,n.columnType,n.indexConfig);return n.indexConfig=n.defaultConfig,t}),this.unique,!0,this.name)}using(o,...n){return new hf(n.map((t)=>{if(X(t,b))return t;t=t;const S=new OS(t.name,!!t.keyAsName,t.columnType,t.indexConfig);return t.indexConfig=JSON.parse(JSON.stringify(t.defaultConfig)),S}),this.unique,!0,this.name,o)}}class hf{static[y]="PgIndexBuilder";config;constructor(o,n,t,S,f="btree"){this.config={name:S,columns:o,unique:n,only:t,method:f}}concurrently(){return this.config.concurrently=!0,this}with(o){return this.config.with=o,this}where(o){return this.config.where=o,this}build(o){return new Z$(this.config,o)}}class Z${static[y]="PgIndex";config;constructor(o,n){this.config={...o,table:n}}}class EM{constructor(o){this.query=o}getQuery(){return this.query}mapResult(o,n){return o}static[y]="PgPreparedQuery";joinsNotNullableMap}class GM{constructor(o){this.dialect=o}static[y]="PgSession";execute(o){return Oo.startActiveSpan("drizzle.operation",()=>{return Oo.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(o),void 0,void 0,!1)}).execute()})}all(o){return this.prepareQuery(this.dialect.sqlToQuery(o),void 0,void 0,!1).all()}async count(o){const n=await this.execute(o);return Number(n[0].count)}}class zM extends VS{constructor(o,n,t,S=0){super(o,n,t);this.schema=t,this.nestedIndex=S}static[y]="PgTransaction";rollback(){throw new xT}getTransactionConfigSQL(o){const n=[];if(o.isolationLevel)n.push(`isolation level ${o.isolationLevel}`);if(o.accessMode)n.push(o.accessMode);if(typeof o.deferrable==="boolean")n.push(o.deferrable?"deferrable":"not deferrable");return R.raw(n.join(" "))}setTransaction(o){return this.session.execute(R`set transaction ${this.getTransactionConfigSQL(o)}`)}}class P$ extends EM{constructor(o,n,t,S,f,T,M){super({sql:n,params:t});this.client=o,this.queryString=n,this.params=t,this.logger=S,this.fields=f,this._isResponseInArrayMode=T,this.customResultMapper=M}static[y]="PostgresJsPreparedQuery";async execute(o={}){return Oo.startActiveSpan("drizzle.execute",async(n)=>{const t=NT(this.params,o);n?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(t)}),this.logger.logQuery(this.queryString,t);const{fields:S,queryString:f,client:T,joinsNotNullableMap:M,customResultMapper:F}=this;if(!S&&!F)return Oo.startActiveSpan("drizzle.driver.execute",()=>{return T.unsafe(f,t)});const k=await Oo.startActiveSpan("drizzle.driver.execute",()=>{return n?.setAttributes({"drizzle.query.text":f,"drizzle.query.params":JSON.stringify(t)}),T.unsafe(f,t).values()});return Oo.startActiveSpan("drizzle.mapResponse",()=>{return F?F(k):k.map((A)=>Yk(S,A,M))})})}all(o={}){return Oo.startActiveSpan("drizzle.execute",async(n)=>{const t=NT(this.params,o);return n?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(t)}),this.logger.logQuery(this.queryString,t),Oo.startActiveSpan("drizzle.driver.execute",()=>{return n?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(t)}),this.client.unsafe(this.queryString,t)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class rS extends GM{constructor(o,n,t,S={}){super(n);this.client=o,this.schema=t,this.options=S,this.logger=S.logger??new vT}static[y]="PostgresJsSession";logger;prepareQuery(o,n,t,S,f){return new P$(this.client,o.sql,o.params,this.logger,n,S,f)}query(o,n){return this.logger.logQuery(o,n),this.client.unsafe(o,n).values()}queryObjects(o,n){return this.client.unsafe(o,n)}transaction(o,n){return this.client.begin(async(t)=>{const S=new rS(t,this.dialect,this.schema,this.options),f=new HM(this.dialect,S,this.schema);if(n)await f.setTransaction(n);return o(f)})}}class HM extends zM{constructor(o,n,t,S=0){super(o,n,t,S);this.session=n}static[y]="PostgresJsTransaction";transaction(o){return this.session.client.savepoint((n)=>{const t=new rS(n,this.dialect,this.schema,this.session.options),S=new HM(this.dialect,t,this.schema);return o(S)})}}function bt(o,n={}){const t=(k)=>k;for(let k of["1184","1082","1083","1114"])o.options.parsers[k]=t,o.options.serializers[k]=t;o.options.serializers["114"]=t,o.options.serializers["3802"]=t;const S=new Wt({casing:n.casing});let f;if(n.logger===!0)f=new iT;else if(n.logger!==!1)f=n.logger;let T;if(n.schema){const k=K$(n.schema,Y$);T={fullSchema:n.schema,schema:k.tables,tableNamesMap:k.tableNamesMap}}const M=new rS(o,S,T,{logger:f}),F=new g$(S,M,T);return F.$client=o,F}function xf(...o){if(typeof o[0]==="function")return bt(o[0],o[1]);if(typeof o[0]==="object"){const{connection:t,client:S,...f}=o[0];if(S)return bt(S,f);if(typeof t==="object"&&t.url!==void 0){const{url:M,...F}=t,k=Bt(M,F);return bt(k,f)}const T=Bt(t);return bt(T,f)}const n=Bt(o[0]);return bt(n,o[1])}class g$ extends VS{static[y]="PostgresJsDatabase"}((o)=>{function n(t){return bt({},t)}o.mock=n})(xf||(xf={}));function GR(o){d$=o}function vf(){return d$}function L(o,n){const t=vf(),S=qf({issueData:n,data:o.data,path:o.path,errorMaps:[o.common.contextualErrorMap,o.schemaErrorMap,t,t===it?void 0:it].filter((f)=>!!f)});o.common.issues.push(S)}function pf(o,n,t,S){if(t==="a"&&!S)throw new TypeError("Private accessor was defined without a getter");if(typeof n==="function"?o!==n||!S:!n.has(o))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?S:t==="a"?S.call(o):S?S.value:n.get(o)}function u$(o,n,t,S,f){if(S==="m")throw new TypeError("Private method is not writable");if(S==="a"&&!f)throw new TypeError("Private accessor was defined without a setter");if(typeof n==="function"?o!==n||!f:!n.has(o))throw new TypeError("Cannot write private member to an object whose class did not declare it");return S==="a"?f.call(o,t):f?f.value=t:n.set(o,t),t}function oo(o){if(!o)return{};const{errorMap:n,invalid_type_error:t,required_error:S,description:f}=o;if(n&&(t||S))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(n)return{errorMap:n,description:f};return{errorMap:(M,F)=>{var k,A;const{message:$}=o;if(M.code==="invalid_enum_value")return{message:$!==null&&$!==void 0?$:F.defaultError};if(typeof F.data==="undefined")return{message:(k=$!==null&&$!==void 0?$:S)!==null&&k!==void 0?k:F.defaultError};if(M.code!=="invalid_type")return{message:F.defaultError};return{message:(A=$!==null&&$!==void 0?$:t)!==null&&A!==void 0?A:F.defaultError}},description:f}}function s$(o){let n="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";if(o.precision)n=`${n}\\.\\d{${o.precision}}`;else if(o.precision==null)n=`${n}(\\.\\d+)?`;return n}function cR(o){return new RegExp(`^${s$(o)}\$`)}function oJ(o){let n=`${a$}T${s$(o)}`;const t=[];if(t.push(o.local?"Z?":"Z"),o.offset)t.push("([+-]\\d{2}:?\\d{2})");return n=`${n}(${t.join("|")})`,new RegExp(`^${n}\$`)}function bR(o,n){if((n==="v4"||!n)&&LR.test(o))return!0;if((n==="v6"||!n)&&IR.test(o))return!0;return!1}function NR(o,n){const t=(o.toString().split(".")[1]||"").length,S=(n.toString().split(".")[1]||"").length,f=t>S?t:S,T=parseInt(o.toFixed(f).replace(".","")),M=parseInt(n.toFixed(f).replace(".",""));return T%M/Math.pow(10,f)}function Nt(o){if(o instanceof Qo){const n={};for(let t in o.shape){const S=o.shape[t];n[t]=Vn.create(Nt(S))}return new Qo({...o._def,shape:()=>n})}else if(o instanceof Un)return new Un({...o._def,type:Nt(o.element)});else if(o instanceof Vn)return Vn.create(Nt(o.unwrap()));else if(o instanceof Zn)return Zn.create(Nt(o.unwrap()));else if(o instanceof Nn)return Nn.create(o.items.map((n)=>Nt(n)));else return o}function VM(o,n){const t=St(o),S=St(n);if(o===n)return{valid:!0,data:o};else if(t===B.object&&S===B.object){const f=Ao.objectKeys(n),T=Ao.objectKeys(o).filter((F)=>f.indexOf(F)!==-1),M={...o,...n};for(let F of T){const k=VM(o[F],n[F]);if(!k.valid)return{valid:!1};M[F]=k.data}return{valid:!0,data:M}}else if(t===B.array&&S===B.array){if(o.length!==n.length)return{valid:!1};const f=[];for(let T=0;T<o.length;T++){const M=o[T],F=n[T],k=VM(M,F);if(!k.valid)return{valid:!1};f.push(k.data)}return{valid:!0,data:f}}else if(t===B.date&&S===B.date&&+o===+n)return{valid:!0,data:o};else return{valid:!1}}function nJ(o,n){return new Ft({values:o,typeName:e.ZodEnum,...oo(n)})}function tJ(o,n={},t){if(o)return wt.create().superRefine((S,f)=>{var T,M;if(!o(S)){const F=typeof n==="function"?n(S):typeof n==="string"?{message:n}:n,k=(M=(T=F.fatal)!==null&&T!==void 0?T:t)!==null&&M!==void 0?M:!0,A=typeof F==="string"?{message:F}:F;f.addIssue({code:"custom",...A,fatal:k})}});return wt.create()}var Ao;(function(o){o.assertEqual=(f)=>f;function n(f){}o.assertIs=n;function t(f){throw new Error}o.assertNever=t,o.arrayToEnum=(f)=>{const T={};for(let M of f)T[M]=M;return T},o.getValidEnumValues=(f)=>{const T=o.objectKeys(f).filter((F)=>typeof f[f[F]]!=="number"),M={};for(let F of T)M[F]=f[F];return o.objectValues(M)},o.objectValues=(f)=>{return o.objectKeys(f).map(function(T){return f[T]})},o.objectKeys=typeof Object.keys==="function"?(f)=>Object.keys(f):(f)=>{const T=[];for(let M in f)if(Object.prototype.hasOwnProperty.call(f,M))T.push(M);return T},o.find=(f,T)=>{for(let M of f)if(T(M))return M;return},o.isInteger=typeof Number.isInteger==="function"?(f)=>Number.isInteger(f):(f)=>typeof f==="number"&&isFinite(f)&&Math.floor(f)===f;function S(f,T=" | "){return f.map((M)=>typeof M==="string"?`'${M}'`:M).join(T)}o.joinValues=S,o.jsonStringifyReplacer=(f,T)=>{if(typeof T==="bigint")return T.toString();return T}})(Ao||(Ao={}));var QM;(function(o){o.mergeShapes=(n,t)=>{return{...n,...t}}})(QM||(QM={}));var B=Ao.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),St=(o)=>{switch(typeof o){case"undefined":return B.undefined;case"string":return B.string;case"number":return isNaN(o)?B.nan:B.number;case"boolean":return B.boolean;case"function":return B.function;case"bigint":return B.bigint;case"symbol":return B.symbol;case"object":if(Array.isArray(o))return B.array;if(o===null)return B.null;if(o.then&&typeof o.then==="function"&&o.catch&&typeof o.catch==="function")return B.promise;if(typeof Map!=="undefined"&&o instanceof Map)return B.map;if(typeof Set!=="undefined"&&o instanceof Set)return B.set;if(typeof Date!=="undefined"&&o instanceof Date)return B.date;return B.object;default:return B.unknown}},z=Ao.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),ER=(o)=>{return JSON.stringify(o,null,2).replace(/"([^"]+)":/g,"$1:")};class yn extends Error{constructor(o){super();this.issues=[],this.addIssue=(t)=>{this.issues=[...this.issues,t]},this.addIssues=(t=[])=>{this.issues=[...this.issues,...t]};const n=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,n);else this.__proto__=n;this.name="ZodError",this.issues=o}get errors(){return this.issues}format(o){const n=o||function(f){return f.message},t={_errors:[]},S=(f)=>{for(let T of f.issues)if(T.code==="invalid_union")T.unionErrors.map(S);else if(T.code==="invalid_return_type")S(T.returnTypeError);else if(T.code==="invalid_arguments")S(T.argumentsError);else if(T.path.length===0)t._errors.push(n(T));else{let M=t,F=0;while(F<T.path.length){const k=T.path[F];if(F!==T.path.length-1)M[k]=M[k]||{_errors:[]};else M[k]=M[k]||{_errors:[]},M[k]._errors.push(n(T));M=M[k],F++}}};return S(this),t}static assert(o){if(!(o instanceof yn))throw new Error(`Not a ZodError: ${o}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ao.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(o=(n)=>n.message){const n={},t=[];for(let S of this.issues)if(S.path.length>0)n[S.path[0]]=n[S.path[0]]||[],n[S.path[0]].push(o(S));else t.push(o(S));return{formErrors:t,fieldErrors:n}}get formErrors(){return this.flatten()}}yn.create=(o)=>{return new yn(o)};var it=(o,n)=>{let t;switch(o.code){case z.invalid_type:if(o.received===B.undefined)t="Required";else t=`Expected ${o.expected}, received ${o.received}`;break;case z.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(o.expected,Ao.jsonStringifyReplacer)}`;break;case z.unrecognized_keys:t=`Unrecognized key(s) in object: ${Ao.joinValues(o.keys,", ")}`;break;case z.invalid_union:t="Invalid input";break;case z.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${Ao.joinValues(o.options)}`;break;case z.invalid_enum_value:t=`Invalid enum value. Expected ${Ao.joinValues(o.options)}, received '${o.received}'`;break;case z.invalid_arguments:t="Invalid function arguments";break;case z.invalid_return_type:t="Invalid function return type";break;case z.invalid_date:t="Invalid date";break;case z.invalid_string:if(typeof o.validation==="object")if("includes"in o.validation){if(t=`Invalid input: must include "${o.validation.includes}"`,typeof o.validation.position==="number")t=`${t} at one or more positions greater than or equal to ${o.validation.position}`}else if("startsWith"in o.validation)t=`Invalid input: must start with "${o.validation.startsWith}"`;else if("endsWith"in o.validation)t=`Invalid input: must end with "${o.validation.endsWith}"`;else Ao.assertNever(o.validation);else if(o.validation!=="regex")t=`Invalid ${o.validation}`;else t="Invalid";break;case z.too_small:if(o.type==="array")t=`Array must contain ${o.exact?"exactly":o.inclusive?"at least":"more than"} ${o.minimum} element(s)`;else if(o.type==="string")t=`String must contain ${o.exact?"exactly":o.inclusive?"at least":"over"} ${o.minimum} character(s)`;else if(o.type==="number")t=`Number must be ${o.exact?"exactly equal to ":o.inclusive?"greater than or equal to ":"greater than "}${o.minimum}`;else if(o.type==="date")t=`Date must be ${o.exact?"exactly equal to ":o.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(o.minimum))}`;else t="Invalid input";break;case z.too_big:if(o.type==="array")t=`Array must contain ${o.exact?"exactly":o.inclusive?"at most":"less than"} ${o.maximum} element(s)`;else if(o.type==="string")t=`String must contain ${o.exact?"exactly":o.inclusive?"at most":"under"} ${o.maximum} character(s)`;else if(o.type==="number")t=`Number must be ${o.exact?"exactly":o.inclusive?"less than or equal to":"less than"} ${o.maximum}`;else if(o.type==="bigint")t=`BigInt must be ${o.exact?"exactly":o.inclusive?"less than or equal to":"less than"} ${o.maximum}`;else if(o.type==="date")t=`Date must be ${o.exact?"exactly":o.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(o.maximum))}`;else t="Invalid input";break;case z.custom:t="Invalid input";break;case z.invalid_intersection_types:t="Intersection results could not be merged";break;case z.not_multiple_of:t=`Number must be a multiple of ${o.multipleOf}`;break;case z.not_finite:t="Number must be finite";break;default:t=n.defaultError,Ao.assertNever(o)}return{message:t}},d$=it,qf=(o)=>{const{data:n,path:t,errorMaps:S,issueData:f}=o,T=[...t,...f.path||[]],M={...f,path:T};if(f.message!==void 0)return{...f,path:T,message:f.message};let F="";const k=S.filter((A)=>!!A).slice().reverse();for(let A of k)F=A(M,{data:n,defaultError:F}).message;return{...f,path:T,message:F}},zR=[];class lo{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(o,n){const t=[];for(let S of n){if(S.status==="aborted")return d;if(S.status==="dirty")o.dirty();t.push(S.value)}return{status:o.value,value:t}}static async mergeObjectAsync(o,n){const t=[];for(let S of n){const f=await S.key,T=await S.value;t.push({key:f,value:T})}return lo.mergeObjectSync(o,t)}static mergeObjectSync(o,n){const t={};for(let S of n){const{key:f,value:T}=S;if(f.status==="aborted")return d;if(T.status==="aborted")return d;if(f.status==="dirty")o.dirty();if(T.status==="dirty")o.dirty();if(f.value!=="__proto__"&&(typeof T.value!=="undefined"||S.alwaysSet))t[f.value]=T.value}return{status:o.value,value:t}}}var d=Object.freeze({status:"aborted"}),ht=(o)=>({status:"dirty",value:o}),on=(o)=>({status:"valid",value:o}),DM=(o)=>o.status==="aborted",UM=(o)=>o.status==="dirty",IS=(o)=>o.status==="valid",jS=(o)=>typeof Promise!=="undefined"&&o instanceof Promise;var q;(function(o){o.errToObj=(n)=>typeof n==="string"?{message:n}:n||{},o.toString=(n)=>typeof n==="string"?n:n===null||n===void 0?void 0:n.message})(q||(q={}));var CS,LS;class rn{constructor(o,n,t,S){this._cachedPath=[],this.parent=o,this.data=n,this._path=t,this._key=S}get path(){if(!this._cachedPath.length)if(this._key instanceof Array)this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var l$=(o,n)=>{if(IS(n))return{success:!0,data:n.value};else{if(!o.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new yn(o.common.issues);return this._error=t,this._error}}}};class no{constructor(o){this.spa=this.safeParseAsync,this._def=o,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(o){return St(o.data)}_getOrReturnCtx(o,n){return n||{common:o.parent.common,data:o.data,parsedType:St(o.data),schemaErrorMap:this._def.errorMap,path:o.path,parent:o.parent}}_processInputParams(o){return{status:new lo,ctx:{common:o.parent.common,data:o.data,parsedType:St(o.data),schemaErrorMap:this._def.errorMap,path:o.path,parent:o.parent}}}_parseSync(o){const n=this._parse(o);if(jS(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(o){const n=this._parse(o);return Promise.resolve(n)}parse(o,n){const t=this.safeParse(o,n);if(t.success)return t.data;throw t.error}safeParse(o,n){var t;const S={common:{issues:[],async:(t=n===null||n===void 0?void 0:n.async)!==null&&t!==void 0?t:!1,contextualErrorMap:n===null||n===void 0?void 0:n.errorMap},path:(n===null||n===void 0?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:o,parsedType:St(o)},f=this._parseSync({data:o,path:S.path,parent:S});return l$(S,f)}async parseAsync(o,n){const t=await this.safeParseAsync(o,n);if(t.success)return t.data;throw t.error}async safeParseAsync(o,n){const t={common:{issues:[],contextualErrorMap:n===null||n===void 0?void 0:n.errorMap,async:!0},path:(n===null||n===void 0?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:o,parsedType:St(o)},S=this._parse({data:o,path:t.path,parent:t}),f=await(jS(S)?S:Promise.resolve(S));return l$(t,f)}refine(o,n){const t=(S)=>{if(typeof n==="string"||typeof n==="undefined")return{message:n};else if(typeof n==="function")return n(S);else return n};return this._refinement((S,f)=>{const T=o(S),M=()=>f.addIssue({code:z.custom,...t(S)});if(typeof Promise!=="undefined"&&T instanceof Promise)return T.then((F)=>{if(!F)return M(),!1;else return!0});if(!T)return M(),!1;else return!0})}refinement(o,n){return this._refinement((t,S)=>{if(!o(t))return S.addIssue(typeof n==="function"?n(t,S):n),!1;else return!0})}_refinement(o){return new Kn({schema:this,typeName:e.ZodEffects,effect:{type:"refinement",refinement:o}})}superRefine(o){return this._refinement(o)}optional(){return Vn.create(this,this._def)}nullable(){return Zn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Un.create(this,this._def)}promise(){return Xt.create(this,this._def)}or(o){return Zt.create([this,o],this._def)}and(o){return Pt.create(this,o,this._def)}transform(o){return new Kn({...oo(this._def),schema:this,typeName:e.ZodEffects,effect:{type:"transform",transform:o}})}default(o){const n=typeof o==="function"?o:()=>o;return new dt({...oo(this._def),innerType:this,defaultValue:n,typeName:e.ZodDefault})}brand(){return new Pf({typeName:e.ZodBranded,type:this,...oo(this._def)})}catch(o){const n=typeof o==="function"?o:()=>o;return new ut({...oo(this._def),innerType:this,catchValue:n,typeName:e.ZodCatch})}describe(o){return new this.constructor({...this._def,description:o})}pipe(o){return xS.create(this,o)}readonly(){return at.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var HR=/^c[^\s-]{8,}$/i,mR=/^[0-9a-z]+$/,QR=/^[0-9A-HJKMNP-TV-Z]{26}$/,DR=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,UR=/^[a-z0-9_-]{21}$/i,VR=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,rR=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,CR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",mM,LR=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,IR=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,jR=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,a$="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",BR=new RegExp(`^${a$}\$`);class Dn extends no{_parse(o){if(this._def.coerce)o.data=String(o.data);if(this._getType(o)!==B.string){const f=this._getOrReturnCtx(o);return L(f,{code:z.invalid_type,expected:B.string,received:f.parsedType}),d}const t=new lo;let S=void 0;for(let f of this._def.checks)if(f.kind==="min"){if(o.data.length<f.value)S=this._getOrReturnCtx(o,S),L(S,{code:z.too_small,minimum:f.value,type:"string",inclusive:!0,exact:!1,message:f.message}),t.dirty()}else if(f.kind==="max"){if(o.data.length>f.value)S=this._getOrReturnCtx(o,S),L(S,{code:z.too_big,maximum:f.value,type:"string",inclusive:!0,exact:!1,message:f.message}),t.dirty()}else if(f.kind==="length"){const T=o.data.length>f.value,M=o.data.length<f.value;if(T||M){if(S=this._getOrReturnCtx(o,S),T)L(S,{code:z.too_big,maximum:f.value,type:"string",inclusive:!0,exact:!0,message:f.message});else if(M)L(S,{code:z.too_small,minimum:f.value,type:"string",inclusive:!0,exact:!0,message:f.message});t.dirty()}}else if(f.kind==="email"){if(!rR.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"email",code:z.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="emoji"){if(!mM)mM=new RegExp(CR,"u");if(!mM.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"emoji",code:z.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="uuid"){if(!DR.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"uuid",code:z.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="nanoid"){if(!UR.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"nanoid",code:z.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="cuid"){if(!HR.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"cuid",code:z.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="cuid2"){if(!mR.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"cuid2",code:z.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="ulid"){if(!QR.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"ulid",code:z.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="url")try{new URL(o.data)}catch(T){S=this._getOrReturnCtx(o,S),L(S,{validation:"url",code:z.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="regex"){if(f.regex.lastIndex=0,!f.regex.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"regex",code:z.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="trim")o.data=o.data.trim();else if(f.kind==="includes"){if(!o.data.includes(f.value,f.position))S=this._getOrReturnCtx(o,S),L(S,{code:z.invalid_string,validation:{includes:f.value,position:f.position},message:f.message}),t.dirty()}else if(f.kind==="toLowerCase")o.data=o.data.toLowerCase();else if(f.kind==="toUpperCase")o.data=o.data.toUpperCase();else if(f.kind==="startsWith"){if(!o.data.startsWith(f.value))S=this._getOrReturnCtx(o,S),L(S,{code:z.invalid_string,validation:{startsWith:f.value},message:f.message}),t.dirty()}else if(f.kind==="endsWith"){if(!o.data.endsWith(f.value))S=this._getOrReturnCtx(o,S),L(S,{code:z.invalid_string,validation:{endsWith:f.value},message:f.message}),t.dirty()}else if(f.kind==="datetime"){if(!oJ(f).test(o.data))S=this._getOrReturnCtx(o,S),L(S,{code:z.invalid_string,validation:"datetime",message:f.message}),t.dirty()}else if(f.kind==="date"){if(!BR.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{code:z.invalid_string,validation:"date",message:f.message}),t.dirty()}else if(f.kind==="time"){if(!cR(f).test(o.data))S=this._getOrReturnCtx(o,S),L(S,{code:z.invalid_string,validation:"time",message:f.message}),t.dirty()}else if(f.kind==="duration"){if(!VR.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"duration",code:z.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="ip"){if(!bR(o.data,f.version))S=this._getOrReturnCtx(o,S),L(S,{validation:"ip",code:z.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="base64"){if(!jR.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"base64",code:z.invalid_string,message:f.message}),t.dirty()}else Ao.assertNever(f);return{status:t.value,value:o.data}}_regex(o,n,t){return this.refinement((S)=>o.test(S),{validation:n,code:z.invalid_string,...q.errToObj(t)})}_addCheck(o){return new Dn({...this._def,checks:[...this._def.checks,o]})}email(o){return this._addCheck({kind:"email",...q.errToObj(o)})}url(o){return this._addCheck({kind:"url",...q.errToObj(o)})}emoji(o){return this._addCheck({kind:"emoji",...q.errToObj(o)})}uuid(o){return this._addCheck({kind:"uuid",...q.errToObj(o)})}nanoid(o){return this._addCheck({kind:"nanoid",...q.errToObj(o)})}cuid(o){return this._addCheck({kind:"cuid",...q.errToObj(o)})}cuid2(o){return this._addCheck({kind:"cuid2",...q.errToObj(o)})}ulid(o){return this._addCheck({kind:"ulid",...q.errToObj(o)})}base64(o){return this._addCheck({kind:"base64",...q.errToObj(o)})}ip(o){return this._addCheck({kind:"ip",...q.errToObj(o)})}datetime(o){var n,t;if(typeof o==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:o});return this._addCheck({kind:"datetime",precision:typeof(o===null||o===void 0?void 0:o.precision)==="undefined"?null:o===null||o===void 0?void 0:o.precision,offset:(n=o===null||o===void 0?void 0:o.offset)!==null&&n!==void 0?n:!1,local:(t=o===null||o===void 0?void 0:o.local)!==null&&t!==void 0?t:!1,...q.errToObj(o===null||o===void 0?void 0:o.message)})}date(o){return this._addCheck({kind:"date",message:o})}time(o){if(typeof o==="string")return this._addCheck({kind:"time",precision:null,message:o});return this._addCheck({kind:"time",precision:typeof(o===null||o===void 0?void 0:o.precision)==="undefined"?null:o===null||o===void 0?void 0:o.precision,...q.errToObj(o===null||o===void 0?void 0:o.message)})}duration(o){return this._addCheck({kind:"duration",...q.errToObj(o)})}regex(o,n){return this._addCheck({kind:"regex",regex:o,...q.errToObj(n)})}includes(o,n){return this._addCheck({kind:"includes",value:o,position:n===null||n===void 0?void 0:n.position,...q.errToObj(n===null||n===void 0?void 0:n.message)})}startsWith(o,n){return this._addCheck({kind:"startsWith",value:o,...q.errToObj(n)})}endsWith(o,n){return this._addCheck({kind:"endsWith",value:o,...q.errToObj(n)})}min(o,n){return this._addCheck({kind:"min",value:o,...q.errToObj(n)})}max(o,n){return this._addCheck({kind:"max",value:o,...q.errToObj(n)})}length(o,n){return this._addCheck({kind:"length",value:o,...q.errToObj(n)})}nonempty(o){return this.min(1,q.errToObj(o))}trim(){return new Dn({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Dn({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Dn({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((o)=>o.kind==="datetime")}get isDate(){return!!this._def.checks.find((o)=>o.kind==="date")}get isTime(){return!!this._def.checks.find((o)=>o.kind==="time")}get isDuration(){return!!this._def.checks.find((o)=>o.kind==="duration")}get isEmail(){return!!this._def.checks.find((o)=>o.kind==="email")}get isURL(){return!!this._def.checks.find((o)=>o.kind==="url")}get isEmoji(){return!!this._def.checks.find((o)=>o.kind==="emoji")}get isUUID(){return!!this._def.checks.find((o)=>o.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((o)=>o.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((o)=>o.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((o)=>o.kind==="cuid2")}get isULID(){return!!this._def.checks.find((o)=>o.kind==="ulid")}get isIP(){return!!this._def.checks.find((o)=>o.kind==="ip")}get isBase64(){return!!this._def.checks.find((o)=>o.kind==="base64")}get minLength(){let o=null;for(let n of this._def.checks)if(n.kind==="min"){if(o===null||n.value>o)o=n.value}return o}get maxLength(){let o=null;for(let n of this._def.checks)if(n.kind==="max"){if(o===null||n.value<o)o=n.value}return o}}Dn.create=(o)=>{var n;return new Dn({checks:[],typeName:e.ZodString,coerce:(n=o===null||o===void 0?void 0:o.coerce)!==null&&n!==void 0?n:!1,...oo(o)})};class Tt extends no{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(o){if(this._def.coerce)o.data=Number(o.data);if(this._getType(o)!==B.number){const f=this._getOrReturnCtx(o);return L(f,{code:z.invalid_type,expected:B.number,received:f.parsedType}),d}let t=void 0;const S=new lo;for(let f of this._def.checks)if(f.kind==="int"){if(!Ao.isInteger(o.data))t=this._getOrReturnCtx(o,t),L(t,{code:z.invalid_type,expected:"integer",received:"float",message:f.message}),S.dirty()}else if(f.kind==="min"){if(f.inclusive?o.data<f.value:o.data<=f.value)t=this._getOrReturnCtx(o,t),L(t,{code:z.too_small,minimum:f.value,type:"number",inclusive:f.inclusive,exact:!1,message:f.message}),S.dirty()}else if(f.kind==="max"){if(f.inclusive?o.data>f.value:o.data>=f.value)t=this._getOrReturnCtx(o,t),L(t,{code:z.too_big,maximum:f.value,type:"number",inclusive:f.inclusive,exact:!1,message:f.message}),S.dirty()}else if(f.kind==="multipleOf"){if(NR(o.data,f.value)!==0)t=this._getOrReturnCtx(o,t),L(t,{code:z.not_multiple_of,multipleOf:f.value,message:f.message}),S.dirty()}else if(f.kind==="finite"){if(!Number.isFinite(o.data))t=this._getOrReturnCtx(o,t),L(t,{code:z.not_finite,message:f.message}),S.dirty()}else Ao.assertNever(f);return{status:S.value,value:o.data}}gte(o,n){return this.setLimit("min",o,!0,q.toString(n))}gt(o,n){return this.setLimit("min",o,!1,q.toString(n))}lte(o,n){return this.setLimit("max",o,!0,q.toString(n))}lt(o,n){return this.setLimit("max",o,!1,q.toString(n))}setLimit(o,n,t,S){return new Tt({...this._def,checks:[...this._def.checks,{kind:o,value:n,inclusive:t,message:q.toString(S)}]})}_addCheck(o){return new Tt({...this._def,checks:[...this._def.checks,o]})}int(o){return this._addCheck({kind:"int",message:q.toString(o)})}positive(o){return this._addCheck({kind:"min",value:0,inclusive:!1,message:q.toString(o)})}negative(o){return this._addCheck({kind:"max",value:0,inclusive:!1,message:q.toString(o)})}nonpositive(o){return this._addCheck({kind:"max",value:0,inclusive:!0,message:q.toString(o)})}nonnegative(o){return this._addCheck({kind:"min",value:0,inclusive:!0,message:q.toString(o)})}multipleOf(o,n){return this._addCheck({kind:"multipleOf",value:o,message:q.toString(n)})}finite(o){return this._addCheck({kind:"finite",message:q.toString(o)})}safe(o){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:q.toString(o)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:q.toString(o)})}get minValue(){let o=null;for(let n of this._def.checks)if(n.kind==="min"){if(o===null||n.value>o)o=n.value}return o}get maxValue(){let o=null;for(let n of this._def.checks)if(n.kind==="max"){if(o===null||n.value<o)o=n.value}return o}get isInt(){return!!this._def.checks.find((o)=>o.kind==="int"||o.kind==="multipleOf"&&Ao.isInteger(o.value))}get isFinite(){let o=null,n=null;for(let t of this._def.checks)if(t.kind==="finite"||t.kind==="int"||t.kind==="multipleOf")return!0;else if(t.kind==="min"){if(n===null||t.value>n)n=t.value}else if(t.kind==="max"){if(o===null||t.value<o)o=t.value}return Number.isFinite(n)&&Number.isFinite(o)}}Tt.create=(o)=>{return new Tt({checks:[],typeName:e.ZodNumber,coerce:(o===null||o===void 0?void 0:o.coerce)||!1,...oo(o)})};class Mt extends no{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(o){if(this._def.coerce)o.data=BigInt(o.data);if(this._getType(o)!==B.bigint){const f=this._getOrReturnCtx(o);return L(f,{code:z.invalid_type,expected:B.bigint,received:f.parsedType}),d}let t=void 0;const S=new lo;for(let f of this._def.checks)if(f.kind==="min"){if(f.inclusive?o.data<f.value:o.data<=f.value)t=this._getOrReturnCtx(o,t),L(t,{code:z.too_small,type:"bigint",minimum:f.value,inclusive:f.inclusive,message:f.message}),S.dirty()}else if(f.kind==="max"){if(f.inclusive?o.data>f.value:o.data>=f.value)t=this._getOrReturnCtx(o,t),L(t,{code:z.too_big,type:"bigint",maximum:f.value,inclusive:f.inclusive,message:f.message}),S.dirty()}else if(f.kind==="multipleOf"){if(o.data%f.value!==BigInt(0))t=this._getOrReturnCtx(o,t),L(t,{code:z.not_multiple_of,multipleOf:f.value,message:f.message}),S.dirty()}else Ao.assertNever(f);return{status:S.value,value:o.data}}gte(o,n){return this.setLimit("min",o,!0,q.toString(n))}gt(o,n){return this.setLimit("min",o,!1,q.toString(n))}lte(o,n){return this.setLimit("max",o,!0,q.toString(n))}lt(o,n){return this.setLimit("max",o,!1,q.toString(n))}setLimit(o,n,t,S){return new Mt({...this._def,checks:[...this._def.checks,{kind:o,value:n,inclusive:t,message:q.toString(S)}]})}_addCheck(o){return new Mt({...this._def,checks:[...this._def.checks,o]})}positive(o){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:q.toString(o)})}negative(o){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:q.toString(o)})}nonpositive(o){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:q.toString(o)})}nonnegative(o){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:q.toString(o)})}multipleOf(o,n){return this._addCheck({kind:"multipleOf",value:o,message:q.toString(n)})}get minValue(){let o=null;for(let n of this._def.checks)if(n.kind==="min"){if(o===null||n.value>o)o=n.value}return o}get maxValue(){let o=null;for(let n of this._def.checks)if(n.kind==="max"){if(o===null||n.value<o)o=n.value}return o}}Mt.create=(o)=>{var n;return new Mt({checks:[],typeName:e.ZodBigInt,coerce:(n=o===null||o===void 0?void 0:o.coerce)!==null&&n!==void 0?n:!1,...oo(o)})};class vt extends no{_parse(o){if(this._def.coerce)o.data=Boolean(o.data);if(this._getType(o)!==B.boolean){const t=this._getOrReturnCtx(o);return L(t,{code:z.invalid_type,expected:B.boolean,received:t.parsedType}),d}return on(o.data)}}vt.create=(o)=>{return new vt({typeName:e.ZodBoolean,coerce:(o===null||o===void 0?void 0:o.coerce)||!1,...oo(o)})};class _t extends no{_parse(o){if(this._def.coerce)o.data=new Date(o.data);if(this._getType(o)!==B.date){const f=this._getOrReturnCtx(o);return L(f,{code:z.invalid_type,expected:B.date,received:f.parsedType}),d}if(isNaN(o.data.getTime())){const f=this._getOrReturnCtx(o);return L(f,{code:z.invalid_date}),d}const t=new lo;let S=void 0;for(let f of this._def.checks)if(f.kind==="min"){if(o.data.getTime()<f.value)S=this._getOrReturnCtx(o,S),L(S,{code:z.too_small,message:f.message,inclusive:!0,exact:!1,minimum:f.value,type:"date"}),t.dirty()}else if(f.kind==="max"){if(o.data.getTime()>f.value)S=this._getOrReturnCtx(o,S),L(S,{code:z.too_big,message:f.message,inclusive:!0,exact:!1,maximum:f.value,type:"date"}),t.dirty()}else Ao.assertNever(f);return{status:t.value,value:new Date(o.data.getTime())}}_addCheck(o){return new _t({...this._def,checks:[...this._def.checks,o]})}min(o,n){return this._addCheck({kind:"min",value:o.getTime(),message:q.toString(n)})}max(o,n){return this._addCheck({kind:"max",value:o.getTime(),message:q.toString(n)})}get minDate(){let o=null;for(let n of this._def.checks)if(n.kind==="min"){if(o===null||n.value>o)o=n.value}return o!=null?new Date(o):null}get maxDate(){let o=null;for(let n of this._def.checks)if(n.kind==="max"){if(o===null||n.value<o)o=n.value}return o!=null?new Date(o):null}}_t.create=(o)=>{return new _t({checks:[],coerce:(o===null||o===void 0?void 0:o.coerce)||!1,typeName:e.ZodDate,...oo(o)})};class BS extends no{_parse(o){if(this._getType(o)!==B.symbol){const t=this._getOrReturnCtx(o);return L(t,{code:z.invalid_type,expected:B.symbol,received:t.parsedType}),d}return on(o.data)}}BS.create=(o)=>{return new BS({typeName:e.ZodSymbol,...oo(o)})};class qt extends no{_parse(o){if(this._getType(o)!==B.undefined){const t=this._getOrReturnCtx(o);return L(t,{code:z.invalid_type,expected:B.undefined,received:t.parsedType}),d}return on(o.data)}}qt.create=(o)=>{return new qt({typeName:e.ZodUndefined,...oo(o)})};class pt extends no{_parse(o){if(this._getType(o)!==B.null){const t=this._getOrReturnCtx(o);return L(t,{code:z.invalid_type,expected:B.null,received:t.parsedType}),d}return on(o.data)}}pt.create=(o)=>{return new pt({typeName:e.ZodNull,...oo(o)})};class wt extends no{constructor(){super(...arguments);this._any=!0}_parse(o){return on(o.data)}}wt.create=(o)=>{return new wt({typeName:e.ZodAny,...oo(o)})};class ft extends no{constructor(){super(...arguments);this._unknown=!0}_parse(o){return on(o.data)}}ft.create=(o)=>{return new ft({typeName:e.ZodUnknown,...oo(o)})};class bn extends no{_parse(o){const n=this._getOrReturnCtx(o);return L(n,{code:z.invalid_type,expected:B.never,received:n.parsedType}),d}}bn.create=(o)=>{return new bn({typeName:e.ZodNever,...oo(o)})};class cS extends no{_parse(o){if(this._getType(o)!==B.undefined){const t=this._getOrReturnCtx(o);return L(t,{code:z.invalid_type,expected:B.void,received:t.parsedType}),d}return on(o.data)}}cS.create=(o)=>{return new cS({typeName:e.ZodVoid,...oo(o)})};class Un extends no{_parse(o){const{ctx:n,status:t}=this._processInputParams(o),S=this._def;if(n.parsedType!==B.array)return L(n,{code:z.invalid_type,expected:B.array,received:n.parsedType}),d;if(S.exactLength!==null){const T=n.data.length>S.exactLength.value,M=n.data.length<S.exactLength.value;if(T||M)L(n,{code:T?z.too_big:z.too_small,minimum:M?S.exactLength.value:void 0,maximum:T?S.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:S.exactLength.message}),t.dirty()}if(S.minLength!==null){if(n.data.length<S.minLength.value)L(n,{code:z.too_small,minimum:S.minLength.value,type:"array",inclusive:!0,exact:!1,message:S.minLength.message}),t.dirty()}if(S.maxLength!==null){if(n.data.length>S.maxLength.value)L(n,{code:z.too_big,maximum:S.maxLength.value,type:"array",inclusive:!0,exact:!1,message:S.maxLength.message}),t.dirty()}if(n.common.async)return Promise.all([...n.data].map((T,M)=>{return S.type._parseAsync(new rn(n,T,n.path,M))})).then((T)=>{return lo.mergeArray(t,T)});const f=[...n.data].map((T,M)=>{return S.type._parseSync(new rn(n,T,n.path,M))});return lo.mergeArray(t,f)}get element(){return this._def.type}min(o,n){return new Un({...this._def,minLength:{value:o,message:q.toString(n)}})}max(o,n){return new Un({...this._def,maxLength:{value:o,message:q.toString(n)}})}length(o,n){return new Un({...this._def,exactLength:{value:o,message:q.toString(n)}})}nonempty(o){return this.min(1,o)}}Un.create=(o,n)=>{return new Un({type:o,minLength:null,maxLength:null,exactLength:null,typeName:e.ZodArray,...oo(n)})};class Qo extends no{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const o=this._def.shape(),n=Ao.objectKeys(o);return this._cached={shape:o,keys:n}}_parse(o){if(this._getType(o)!==B.object){const k=this._getOrReturnCtx(o);return L(k,{code:z.invalid_type,expected:B.object,received:k.parsedType}),d}const{status:t,ctx:S}=this._processInputParams(o),{shape:f,keys:T}=this._getCached(),M=[];if(!(this._def.catchall instanceof bn&&this._def.unknownKeys==="strip")){for(let k in S.data)if(!T.includes(k))M.push(k)}const F=[];for(let k of T){const A=f[k],$=S.data[k];F.push({key:{status:"valid",value:k},value:A._parse(new rn(S,$,S.path,k)),alwaysSet:k in S.data})}if(this._def.catchall instanceof bn){const k=this._def.unknownKeys;if(k==="passthrough")for(let A of M)F.push({key:{status:"valid",value:A},value:{status:"valid",value:S.data[A]}});else if(k==="strict"){if(M.length>0)L(S,{code:z.unrecognized_keys,keys:M}),t.dirty()}else if(k==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const k=this._def.catchall;for(let A of M){const $=S.data[A];F.push({key:{status:"valid",value:A},value:k._parse(new rn(S,$,S.path,A)),alwaysSet:A in S.data})}}if(S.common.async)return Promise.resolve().then(async()=>{const k=[];for(let A of F){const $=await A.key,O=await A.value;k.push({key:$,value:O,alwaysSet:A.alwaysSet})}return k}).then((k)=>{return lo.mergeObjectSync(t,k)});else return lo.mergeObjectSync(t,F)}get shape(){return this._def.shape()}strict(o){return q.errToObj,new Qo({...this._def,unknownKeys:"strict",...o!==void 0?{errorMap:(n,t)=>{var S,f,T,M;const F=(T=(f=(S=this._def).errorMap)===null||f===void 0?void 0:f.call(S,n,t).message)!==null&&T!==void 0?T:t.defaultError;if(n.code==="unrecognized_keys")return{message:(M=q.errToObj(o).message)!==null&&M!==void 0?M:F};return{message:F}}}:{}})}strip(){return new Qo({...this._def,unknownKeys:"strip"})}passthrough(){return new Qo({...this._def,unknownKeys:"passthrough"})}extend(o){return new Qo({...this._def,shape:()=>({...this._def.shape(),...o})})}merge(o){return new Qo({unknownKeys:o._def.unknownKeys,catchall:o._def.catchall,shape:()=>({...this._def.shape(),...o._def.shape()}),typeName:e.ZodObject})}setKey(o,n){return this.augment({[o]:n})}catchall(o){return new Qo({...this._def,catchall:o})}pick(o){const n={};return Ao.objectKeys(o).forEach((t)=>{if(o[t]&&this.shape[t])n[t]=this.shape[t]}),new Qo({...this._def,shape:()=>n})}omit(o){const n={};return Ao.objectKeys(this.shape).forEach((t)=>{if(!o[t])n[t]=this.shape[t]}),new Qo({...this._def,shape:()=>n})}deepPartial(){return Nt(this)}partial(o){const n={};return Ao.objectKeys(this.shape).forEach((t)=>{const S=this.shape[t];if(o&&!o[t])n[t]=S;else n[t]=S.optional()}),new Qo({...this._def,shape:()=>n})}required(o){const n={};return Ao.objectKeys(this.shape).forEach((t)=>{if(o&&!o[t])n[t]=this.shape[t];else{let f=this.shape[t];while(f instanceof Vn)f=f._def.innerType;n[t]=f}}),new Qo({...this._def,shape:()=>n})}keyof(){return nJ(Ao.objectKeys(this.shape))}}Qo.create=(o,n)=>{return new Qo({shape:()=>o,unknownKeys:"strip",catchall:bn.create(),typeName:e.ZodObject,...oo(n)})};Qo.strictCreate=(o,n)=>{return new Qo({shape:()=>o,unknownKeys:"strict",catchall:bn.create(),typeName:e.ZodObject,...oo(n)})};Qo.lazycreate=(o,n)=>{return new Qo({shape:o,unknownKeys:"strip",catchall:bn.create(),typeName:e.ZodObject,...oo(n)})};class Zt extends no{_parse(o){const{ctx:n}=this._processInputParams(o),t=this._def.options;function S(f){for(let M of f)if(M.result.status==="valid")return M.result;for(let M of f)if(M.result.status==="dirty")return n.common.issues.push(...M.ctx.common.issues),M.result;const T=f.map((M)=>new yn(M.ctx.common.issues));return L(n,{code:z.invalid_union,unionErrors:T}),d}if(n.common.async)return Promise.all(t.map(async(f)=>{const T={...n,common:{...n.common,issues:[]},parent:null};return{result:await f._parseAsync({data:n.data,path:n.path,parent:T}),ctx:T}})).then(S);else{let f=void 0;const T=[];for(let F of t){const k={...n,common:{...n.common,issues:[]},parent:null},A=F._parseSync({data:n.data,path:n.path,parent:k});if(A.status==="valid")return A;else if(A.status==="dirty"&&!f)f={result:A,ctx:k};if(k.common.issues.length)T.push(k.common.issues)}if(f)return n.common.issues.push(...f.ctx.common.issues),f.result;const M=T.map((F)=>new yn(F));return L(n,{code:z.invalid_union,unionErrors:M}),d}}get options(){return this._def.options}}Zt.create=(o,n)=>{return new Zt({options:o,typeName:e.ZodUnion,...oo(n)})};var pn=(o)=>{if(o instanceof gt)return pn(o.schema);else if(o instanceof Kn)return pn(o.innerType());else if(o instanceof lt)return[o.value];else if(o instanceof Ft)return o.options;else if(o instanceof et)return Ao.objectValues(o.enum);else if(o instanceof dt)return pn(o._def.innerType);else if(o instanceof qt)return[void 0];else if(o instanceof pt)return[null];else if(o instanceof Vn)return[void 0,...pn(o.unwrap())];else if(o instanceof Zn)return[null,...pn(o.unwrap())];else if(o instanceof Pf)return pn(o.unwrap());else if(o instanceof at)return pn(o.unwrap());else if(o instanceof ut)return pn(o._def.innerType);else return[]};class Zf extends no{_parse(o){const{ctx:n}=this._processInputParams(o);if(n.parsedType!==B.object)return L(n,{code:z.invalid_type,expected:B.object,received:n.parsedType}),d;const t=this.discriminator,S=n.data[t],f=this.optionsMap.get(S);if(!f)return L(n,{code:z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[t]}),d;if(n.common.async)return f._parseAsync({data:n.data,path:n.path,parent:n});else return f._parseSync({data:n.data,path:n.path,parent:n})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(o,n,t){const S=new Map;for(let f of n){const T=pn(f.shape[o]);if(!T.length)throw new Error(`A discriminator value for key \`${o}\` could not be extracted from all schema options`);for(let M of T){if(S.has(M))throw new Error(`Discriminator property ${String(o)} has duplicate value ${String(M)}`);S.set(M,f)}}return new Zf({typeName:e.ZodDiscriminatedUnion,discriminator:o,options:n,optionsMap:S,...oo(t)})}}class Pt extends no{_parse(o){const{status:n,ctx:t}=this._processInputParams(o),S=(f,T)=>{if(DM(f)||DM(T))return d;const M=VM(f.value,T.value);if(!M.valid)return L(t,{code:z.invalid_intersection_types}),d;if(UM(f)||UM(T))n.dirty();return{status:n.value,value:M.data}};if(t.common.async)return Promise.all([this._def.left._parseAsync({data:t.data,path:t.path,parent:t}),this._def.right._parseAsync({data:t.data,path:t.path,parent:t})]).then(([f,T])=>S(f,T));else return S(this._def.left._parseSync({data:t.data,path:t.path,parent:t}),this._def.right._parseSync({data:t.data,path:t.path,parent:t}))}}Pt.create=(o,n,t)=>{return new Pt({left:o,right:n,typeName:e.ZodIntersection,...oo(t)})};class Nn extends no{_parse(o){const{status:n,ctx:t}=this._processInputParams(o);if(t.parsedType!==B.array)return L(t,{code:z.invalid_type,expected:B.array,received:t.parsedType}),d;if(t.data.length<this._def.items.length)return L(t,{code:z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),d;if(!this._def.rest&&t.data.length>this._def.items.length)L(t,{code:z.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty();const f=[...t.data].map((T,M)=>{const F=this._def.items[M]||this._def.rest;if(!F)return null;return F._parse(new rn(t,T,t.path,M))}).filter((T)=>!!T);if(t.common.async)return Promise.all(f).then((T)=>{return lo.mergeArray(n,T)});else return lo.mergeArray(n,f)}get items(){return this._def.items}rest(o){return new Nn({...this._def,rest:o})}}Nn.create=(o,n)=>{if(!Array.isArray(o))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Nn({items:o,typeName:e.ZodTuple,rest:null,...oo(n)})};class bS extends no{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(o){const{status:n,ctx:t}=this._processInputParams(o);if(t.parsedType!==B.object)return L(t,{code:z.invalid_type,expected:B.object,received:t.parsedType}),d;const S=[],f=this._def.keyType,T=this._def.valueType;for(let M in t.data)S.push({key:f._parse(new rn(t,M,t.path,M)),value:T._parse(new rn(t,t.data[M],t.path,M)),alwaysSet:M in t.data});if(t.common.async)return lo.mergeObjectAsync(n,S);else return lo.mergeObjectSync(n,S)}get element(){return this._def.valueType}static create(o,n,t){if(n instanceof no)return new bS({keyType:o,valueType:n,typeName:e.ZodRecord,...oo(t)});return new bS({keyType:Dn.create(),valueType:o,typeName:e.ZodRecord,...oo(n)})}}class NS extends no{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(o){const{status:n,ctx:t}=this._processInputParams(o);if(t.parsedType!==B.map)return L(t,{code:z.invalid_type,expected:B.map,received:t.parsedType}),d;const S=this._def.keyType,f=this._def.valueType,T=[...t.data.entries()].map(([M,F],k)=>{return{key:S._parse(new rn(t,M,t.path,[k,"key"])),value:f._parse(new rn(t,F,t.path,[k,"value"]))}});if(t.common.async){const M=new Map;return Promise.resolve().then(async()=>{for(let F of T){const k=await F.key,A=await F.value;if(k.status==="aborted"||A.status==="aborted")return d;if(k.status==="dirty"||A.status==="dirty")n.dirty();M.set(k.value,A.value)}return{status:n.value,value:M}})}else{const M=new Map;for(let F of T){const{key:k,value:A}=F;if(k.status==="aborted"||A.status==="aborted")return d;if(k.status==="dirty"||A.status==="dirty")n.dirty();M.set(k.value,A.value)}return{status:n.value,value:M}}}}NS.create=(o,n,t)=>{return new NS({valueType:n,keyType:o,typeName:e.ZodMap,...oo(t)})};class Kt extends no{_parse(o){const{status:n,ctx:t}=this._processInputParams(o);if(t.parsedType!==B.set)return L(t,{code:z.invalid_type,expected:B.set,received:t.parsedType}),d;const S=this._def;if(S.minSize!==null){if(t.data.size<S.minSize.value)L(t,{code:z.too_small,minimum:S.minSize.value,type:"set",inclusive:!0,exact:!1,message:S.minSize.message}),n.dirty()}if(S.maxSize!==null){if(t.data.size>S.maxSize.value)L(t,{code:z.too_big,maximum:S.maxSize.value,type:"set",inclusive:!0,exact:!1,message:S.maxSize.message}),n.dirty()}const f=this._def.valueType;function T(F){const k=new Set;for(let A of F){if(A.status==="aborted")return d;if(A.status==="dirty")n.dirty();k.add(A.value)}return{status:n.value,value:k}}const M=[...t.data.values()].map((F,k)=>f._parse(new rn(t,F,t.path,k)));if(t.common.async)return Promise.all(M).then((F)=>T(F));else return T(M)}min(o,n){return new Kt({...this._def,minSize:{value:o,message:q.toString(n)}})}max(o,n){return new Kt({...this._def,maxSize:{value:o,message:q.toString(n)}})}size(o,n){return this.min(o,n).max(o,n)}nonempty(o){return this.min(1,o)}}Kt.create=(o,n)=>{return new Kt({valueType:o,minSize:null,maxSize:null,typeName:e.ZodSet,...oo(n)})};class xt extends no{constructor(){super(...arguments);this.validate=this.implement}_parse(o){const{ctx:n}=this._processInputParams(o);if(n.parsedType!==B.function)return L(n,{code:z.invalid_type,expected:B.function,received:n.parsedType}),d;function t(M,F){return qf({data:M,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,vf(),it].filter((k)=>!!k),issueData:{code:z.invalid_arguments,argumentsError:F}})}function S(M,F){return qf({data:M,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,vf(),it].filter((k)=>!!k),issueData:{code:z.invalid_return_type,returnTypeError:F}})}const f={errorMap:n.common.contextualErrorMap},T=n.data;if(this._def.returns instanceof Xt){const M=this;return on(async function(...F){const k=new yn([]),A=await M._def.args.parseAsync(F,f).catch((w)=>{throw k.addIssue(t(F,w)),k}),$=await Reflect.apply(T,this,A);return await M._def.returns._def.type.parseAsync($,f).catch((w)=>{throw k.addIssue(S($,w)),k})})}else{const M=this;return on(function(...F){const k=M._def.args.safeParse(F,f);if(!k.success)throw new yn([t(F,k.error)]);const A=Reflect.apply(T,this,k.data),$=M._def.returns.safeParse(A,f);if(!$.success)throw new yn([S(A,$.error)]);return $.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...o){return new xt({...this._def,args:Nn.create(o).rest(ft.create())})}returns(o){return new xt({...this._def,returns:o})}implement(o){return this.parse(o)}strictImplement(o){return this.parse(o)}static create(o,n,t){return new xt({args:o?o:Nn.create([]).rest(ft.create()),returns:n||ft.create(),typeName:e.ZodFunction,...oo(t)})}}class gt extends no{get schema(){return this._def.getter()}_parse(o){const{ctx:n}=this._processInputParams(o);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}gt.create=(o,n)=>{return new gt({getter:o,typeName:e.ZodLazy,...oo(n)})};class lt extends no{_parse(o){if(o.data!==this._def.value){const n=this._getOrReturnCtx(o);return L(n,{received:n.data,code:z.invalid_literal,expected:this._def.value}),d}return{status:"valid",value:o.data}}get value(){return this._def.value}}lt.create=(o,n)=>{return new lt({value:o,typeName:e.ZodLiteral,...oo(n)})};class Ft extends no{constructor(){super(...arguments);CS.set(this,void 0)}_parse(o){if(typeof o.data!=="string"){const n=this._getOrReturnCtx(o),t=this._def.values;return L(n,{expected:Ao.joinValues(t),received:n.parsedType,code:z.invalid_type}),d}if(!pf(this,CS,"f"))u$(this,CS,new Set(this._def.values),"f");if(!pf(this,CS,"f").has(o.data)){const n=this._getOrReturnCtx(o),t=this._def.values;return L(n,{received:n.data,code:z.invalid_enum_value,options:t}),d}return on(o.data)}get options(){return this._def.values}get enum(){const o={};for(let n of this._def.values)o[n]=n;return o}get Values(){const o={};for(let n of this._def.values)o[n]=n;return o}get Enum(){const o={};for(let n of this._def.values)o[n]=n;return o}extract(o,n=this._def){return Ft.create(o,{...this._def,...n})}exclude(o,n=this._def){return Ft.create(this.options.filter((t)=>!o.includes(t)),{...this._def,...n})}}CS=new WeakMap;Ft.create=nJ;class et extends no{constructor(){super(...arguments);LS.set(this,void 0)}_parse(o){const n=Ao.getValidEnumValues(this._def.values),t=this._getOrReturnCtx(o);if(t.parsedType!==B.string&&t.parsedType!==B.number){const S=Ao.objectValues(n);return L(t,{expected:Ao.joinValues(S),received:t.parsedType,code:z.invalid_type}),d}if(!pf(this,LS,"f"))u$(this,LS,new Set(Ao.getValidEnumValues(this._def.values)),"f");if(!pf(this,LS,"f").has(o.data)){const S=Ao.objectValues(n);return L(t,{received:t.data,code:z.invalid_enum_value,options:S}),d}return on(o.data)}get enum(){return this._def.values}}LS=new WeakMap;et.create=(o,n)=>{return new et({values:o,typeName:e.ZodNativeEnum,...oo(n)})};class Xt extends no{unwrap(){return this._def.type}_parse(o){const{ctx:n}=this._processInputParams(o);if(n.parsedType!==B.promise&&n.common.async===!1)return L(n,{code:z.invalid_type,expected:B.promise,received:n.parsedType}),d;const t=n.parsedType===B.promise?n.data:Promise.resolve(n.data);return on(t.then((S)=>{return this._def.type.parseAsync(S,{path:n.path,errorMap:n.common.contextualErrorMap})}))}}Xt.create=(o,n)=>{return new Xt({type:o,typeName:e.ZodPromise,...oo(n)})};class Kn extends no{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===e.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(o){const{status:n,ctx:t}=this._processInputParams(o),S=this._def.effect||null,f={addIssue:(T)=>{if(L(t,T),T.fatal)n.abort();else n.dirty()},get path(){return t.path}};if(f.addIssue=f.addIssue.bind(f),S.type==="preprocess"){const T=S.transform(t.data,f);if(t.common.async)return Promise.resolve(T).then(async(M)=>{if(n.value==="aborted")return d;const F=await this._def.schema._parseAsync({data:M,path:t.path,parent:t});if(F.status==="aborted")return d;if(F.status==="dirty")return ht(F.value);if(n.value==="dirty")return ht(F.value);return F});else{if(n.value==="aborted")return d;const M=this._def.schema._parseSync({data:T,path:t.path,parent:t});if(M.status==="aborted")return d;if(M.status==="dirty")return ht(M.value);if(n.value==="dirty")return ht(M.value);return M}}if(S.type==="refinement"){const T=(M)=>{const F=S.refinement(M,f);if(t.common.async)return Promise.resolve(F);if(F instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return M};if(t.common.async===!1){const M=this._def.schema._parseSync({data:t.data,path:t.path,parent:t});if(M.status==="aborted")return d;if(M.status==="dirty")n.dirty();return T(M.value),{status:n.value,value:M.value}}else return this._def.schema._parseAsync({data:t.data,path:t.path,parent:t}).then((M)=>{if(M.status==="aborted")return d;if(M.status==="dirty")n.dirty();return T(M.value).then(()=>{return{status:n.value,value:M.value}})})}if(S.type==="transform")if(t.common.async===!1){const T=this._def.schema._parseSync({data:t.data,path:t.path,parent:t});if(!IS(T))return T;const M=S.transform(T.value,f);if(M instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:M}}else return this._def.schema._parseAsync({data:t.data,path:t.path,parent:t}).then((T)=>{if(!IS(T))return T;return Promise.resolve(S.transform(T.value,f)).then((M)=>({status:n.value,value:M}))});Ao.assertNever(S)}}Kn.create=(o,n,t)=>{return new Kn({schema:o,typeName:e.ZodEffects,effect:n,...oo(t)})};Kn.createWithPreprocess=(o,n,t)=>{return new Kn({schema:n,effect:{type:"preprocess",transform:o},typeName:e.ZodEffects,...oo(t)})};class Vn extends no{_parse(o){if(this._getType(o)===B.undefined)return on(void 0);return this._def.innerType._parse(o)}unwrap(){return this._def.innerType}}Vn.create=(o,n)=>{return new Vn({innerType:o,typeName:e.ZodOptional,...oo(n)})};class Zn extends no{_parse(o){if(this._getType(o)===B.null)return on(null);return this._def.innerType._parse(o)}unwrap(){return this._def.innerType}}Zn.create=(o,n)=>{return new Zn({innerType:o,typeName:e.ZodNullable,...oo(n)})};class dt extends no{_parse(o){const{ctx:n}=this._processInputParams(o);let t=n.data;if(n.parsedType===B.undefined)t=this._def.defaultValue();return this._def.innerType._parse({data:t,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}dt.create=(o,n)=>{return new dt({innerType:o,typeName:e.ZodDefault,defaultValue:typeof n.default==="function"?n.default:()=>n.default,...oo(n)})};class ut extends no{_parse(o){const{ctx:n}=this._processInputParams(o),t={...n,common:{...n.common,issues:[]}},S=this._def.innerType._parse({data:t.data,path:t.path,parent:{...t}});if(jS(S))return S.then((f)=>{return{status:"valid",value:f.status==="valid"?f.value:this._def.catchValue({get error(){return new yn(t.common.issues)},input:t.data})}});else return{status:"valid",value:S.status==="valid"?S.value:this._def.catchValue({get error(){return new yn(t.common.issues)},input:t.data})}}removeCatch(){return this._def.innerType}}ut.create=(o,n)=>{return new ut({innerType:o,typeName:e.ZodCatch,catchValue:typeof n.catch==="function"?n.catch:()=>n.catch,...oo(n)})};class hS extends no{_parse(o){if(this._getType(o)!==B.nan){const t=this._getOrReturnCtx(o);return L(t,{code:z.invalid_type,expected:B.nan,received:t.parsedType}),d}return{status:"valid",value:o.data}}}hS.create=(o)=>{return new hS({typeName:e.ZodNaN,...oo(o)})};var hR=Symbol("zod_brand");class Pf extends no{_parse(o){const{ctx:n}=this._processInputParams(o),t=n.data;return this._def.type._parse({data:t,path:n.path,parent:n})}unwrap(){return this._def.type}}class xS extends no{_parse(o){const{status:n,ctx:t}=this._processInputParams(o);if(t.common.async)return(async()=>{const f=await this._def.in._parseAsync({data:t.data,path:t.path,parent:t});if(f.status==="aborted")return d;if(f.status==="dirty")return n.dirty(),ht(f.value);else return this._def.out._parseAsync({data:f.value,path:t.path,parent:t})})();else{const S=this._def.in._parseSync({data:t.data,path:t.path,parent:t});if(S.status==="aborted")return d;if(S.status==="dirty")return n.dirty(),{status:"dirty",value:S.value};else return this._def.out._parseSync({data:S.value,path:t.path,parent:t})}}static create(o,n){return new xS({in:o,out:n,typeName:e.ZodPipeline})}}class at extends no{_parse(o){const n=this._def.innerType._parse(o),t=(S)=>{if(IS(S))S.value=Object.freeze(S.value);return S};return jS(n)?n.then((S)=>t(S)):t(n)}unwrap(){return this._def.innerType}}at.create=(o,n)=>{return new at({innerType:o,typeName:e.ZodReadonly,...oo(n)})};var xR={object:Qo.lazycreate},e;(function(o){o.ZodString="ZodString",o.ZodNumber="ZodNumber",o.ZodNaN="ZodNaN",o.ZodBigInt="ZodBigInt",o.ZodBoolean="ZodBoolean",o.ZodDate="ZodDate",o.ZodSymbol="ZodSymbol",o.ZodUndefined="ZodUndefined",o.ZodNull="ZodNull",o.ZodAny="ZodAny",o.ZodUnknown="ZodUnknown",o.ZodNever="ZodNever",o.ZodVoid="ZodVoid",o.ZodArray="ZodArray",o.ZodObject="ZodObject",o.ZodUnion="ZodUnion",o.ZodDiscriminatedUnion="ZodDiscriminatedUnion",o.ZodIntersection="ZodIntersection",o.ZodTuple="ZodTuple",o.ZodRecord="ZodRecord",o.ZodMap="ZodMap",o.ZodSet="ZodSet",o.ZodFunction="ZodFunction",o.ZodLazy="ZodLazy",o.ZodLiteral="ZodLiteral",o.ZodEnum="ZodEnum",o.ZodEffects="ZodEffects",o.ZodNativeEnum="ZodNativeEnum",o.ZodOptional="ZodOptional",o.ZodNullable="ZodNullable",o.ZodDefault="ZodDefault",o.ZodCatch="ZodCatch",o.ZodPromise="ZodPromise",o.ZodBranded="ZodBranded",o.ZodPipeline="ZodPipeline",o.ZodReadonly="ZodReadonly"})(e||(e={}));var iR=(o,n={message:`Input not instance of ${o.name}`})=>tJ((t)=>t instanceof o,n),SJ=Dn.create,fJ=Tt.create,vR=hS.create,qR=Mt.create,TJ=vt.create,pR=_t.create,ZR=BS.create,PR=qt.create,gR=pt.create,lR=wt.create,eR=ft.create,dR=bn.create,uR=cS.create,aR=Un.create,iS=Qo.create,sR=Qo.strictCreate,o0=Zt.create,n0=Zf.create,t0=Pt.create,S0=Nn.create,f0=bS.create,T0=NS.create,M0=Kt.create,F0=xt.create,k0=gt.create,A0=lt.create,$0=Ft.create,J0=et.create,y0=Xt.create,e$=Kn.create,R0=Vn.create,O0=Zn.create,W0=Kn.createWithPreprocess,_0=xS.create,w0=()=>SJ().optional(),K0=()=>fJ().optional(),X0=()=>TJ().optional(),Y0={string:(o)=>Dn.create({...o,coerce:!0}),number:(o)=>Tt.create({...o,coerce:!0}),boolean:(o)=>vt.create({...o,coerce:!0}),bigint:(o)=>Mt.create({...o,coerce:!0}),date:(o)=>_t.create({...o,coerce:!0})},E0=d,Vo=Object.freeze({__proto__:null,defaultErrorMap:it,setErrorMap:GR,getErrorMap:vf,makeIssue:qf,EMPTY_PATH:zR,addIssueToContext:L,ParseStatus:lo,INVALID:d,DIRTY:ht,OK:on,isAborted:DM,isDirty:UM,isValid:IS,isAsync:jS,get util(){return Ao},get objectUtil(){return QM},ZodParsedType:B,getParsedType:St,ZodType:no,datetimeRegex:oJ,ZodString:Dn,ZodNumber:Tt,ZodBigInt:Mt,ZodBoolean:vt,ZodDate:_t,ZodSymbol:BS,ZodUndefined:qt,ZodNull:pt,ZodAny:wt,ZodUnknown:ft,ZodNever:bn,ZodVoid:cS,ZodArray:Un,ZodObject:Qo,ZodUnion:Zt,ZodDiscriminatedUnion:Zf,ZodIntersection:Pt,ZodTuple:Nn,ZodRecord:bS,ZodMap:NS,ZodSet:Kt,ZodFunction:xt,ZodLazy:gt,ZodLiteral:lt,ZodEnum:Ft,ZodNativeEnum:et,ZodPromise:Xt,ZodEffects:Kn,ZodTransformer:Kn,ZodOptional:Vn,ZodNullable:Zn,ZodDefault:dt,ZodCatch:ut,ZodNaN:hS,BRAND:hR,ZodBranded:Pf,ZodPipeline:xS,ZodReadonly:at,custom:tJ,Schema:no,ZodSchema:no,late:xR,get ZodFirstPartyTypeKind(){return e},coerce:Y0,any:lR,array:aR,bigint:qR,boolean:TJ,date:pR,discriminatedUnion:n0,effect:e$,enum:$0,function:F0,instanceof:iR,intersection:t0,lazy:k0,literal:A0,map:T0,nan:vR,nativeEnum:J0,never:dR,null:gR,nullable:O0,number:fJ,object:iS,oboolean:X0,onumber:K0,optional:R0,ostring:w0,pipeline:_0,preprocess:W0,promise:y0,record:f0,set:M0,strictObject:sR,string:SJ,symbol:ZR,transformer:e$,tuple:S0,undefined:PR,union:o0,unknown:eR,void:uR,NEVER:E0,ZodIssueCode:z,quotelessJson:ER,ZodError:yn});function MJ(o){const n=o.runtimeEnvStrict??o.runtimeEnv??process.env;if(o.emptyStringAsUndefined??!1){for(let[K,Q]of Object.entries(n))if(Q==="")delete n[K]}if(!!o.skipValidation)return n;const f=typeof o.client==="object"?o.client:{},T=typeof o.server==="object"?o.server:{},M=typeof o.shared==="object"?o.shared:{},F=iS(f),k=iS(T),A=iS(M),$=o.isServer??(typeof window==="undefined"||("Deno"in window)),O=F.merge(A),w=k.merge(A).merge(F),G=$?w.safeParse(n):O.safeParse(n),r=o.onValidationError??((K)=>{throw console.error("\u274C Invalid environment variables:",K.flatten().fieldErrors),new Error("Invalid environment variables")}),H=o.onInvalidAccess??((K)=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(G.success===!1)return r(G.error);const D=(K)=>{if(!o.clientPrefix)return!0;return!K.startsWith(o.clientPrefix)&&!(K in A.shape)},I=(K)=>{return $||!D(K)},v=(K)=>{return K==="__esModule"||K==="$$typeof"},N=(o.extends??[]).reduce((K,Q)=>{return Object.assign(K,Q)},{}),P=Object.assign(G.data,N);return new Proxy(P,{get(K,Q){if(typeof Q!=="string")return;if(v(Q))return;if(!I(Q))return H(Q);return Reflect.get(K,Q)}})}var Pn=MJ({isServer:typeof window==="undefined",server:{POSTGRES_USER:Vo.string(),POSTGRES_PASSWORD:Vo.string(),POSTGRES_DATABASE:Vo.string(),POSTGRES_HOST:Vo.string(),POSTGRES_PORT:Vo.string().transform((o)=>Number.parseInt(o,10)),BACKEND_PORT:Vo.string().transform((o)=>Number.parseInt(o,10)),RUN_WORKERS_FROM_SOURCE:Vo.union([Vo.literal("true"),Vo.literal("false")]).optional().transform((o)=>o==="true"),FRONTEND_PORT:Vo.string().transform((o)=>Number.parseInt(o,10)),FRONTEND_ORIGINS:Vo.string().transform((o)=>Uo(o)).pipe(Vo.array(Vo.string())),OPENAI_API_KEY:Vo.string().optional()},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:Vo.string()},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var CM={};Fy(CM,{users:()=>Yt,userChanges:()=>z0,untrackedUserColumnNames:()=>G0,twoFactorMethod:()=>$J,trackedUserColumnName:()=>AJ,trackableUserColumnNames:()=>kJ,role:()=>FJ,players:()=>rM,passwordResetAttempts:()=>m0,loginHistory:()=>H0,games:()=>gf,banishedIps:()=>vS});var FJ=kf("role",["admin","user"]),Yt=ot("users",{id:$n().primaryKey().defaultRandom(),username:io({length:16}).notNull(),email:io({length:254}).notNull(),hash:io({length:64}).notNull(),salt:io({length:36}).notNull(),createdAt:mn({withTimezone:!0}).notNull().defaultNow(),createdIp:io({length:45}).notNull(),isActive:XS().notNull().default(!1),verifiedAt:mn({withTimezone:!0}),userRole:FJ().default("user")},(o)=>({usersUsernameUnique:YM().on(o.username),usersEmailUnique:YM().on(o.email)})),G0=["id","createdAt","createdIp","isActive","salt","verifiedAt"],kJ=["username","email","hash","userRole"],AJ=kf("trackedUserColumnName",kJ),z0=ot("userChanges",{id:$n().primaryKey().defaultRandom(),userId:$n().notNull().references(()=>Yt.id),changedAt:mn({withTimezone:!0}).notNull().defaultNow(),changedIp:io({length:45}).notNull(),changedColumn:AJ().notNull(),oldValue:io({length:255}),newValue:io({length:255})}),gf=ot("games",{id:$n("id").primaryKey().defaultRandom()}),rM=ot("players",{userId:$n().notNull().references(()=>Yt.id),gameId:$n().notNull().references(()=>gf.id),score:_f().notNull()},(o)=>({pk:R$({columns:[o.userId,o.gameId]})})),H0=ot("loginHistory",{id:$n().primaryKey().defaultRandom(),userId:$n().references(()=>Yt.id),loginTime:mn({withTimezone:!0}).notNull().defaultNow(),ipAddress:io({length:45}).notNull(),userAgent:io({length:1024}),successful:XS().notNull().default(!1)}),$J=kf("twoFactorMethod",["email","phone"]),m0=ot("passwordResetAttempts",{id:$n().primaryKey().defaultRandom(),userId:$n().notNull().references(()=>Yt.id),requestedIp:io({length:45}).notNull(),requestedAt:mn({withTimezone:!0}).notNull().defaultNow(),succeededIp:io({length:45}),succeededAt:mn({withTimezone:!0}),verificationMethod:$J().notNull()}),vS=ot("banishedIps",{ip:io({length:45}).primaryKey(),reason:io({length:2048}).notNull(),banishedAt:mn({withTimezone:!0}).notNull().defaultNow(),banishedUntil:mn({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class LM{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(Q0.resolve(__dirname,"notify_update.sql"));const o=[Wn(Yt),Wn(gf),Wn(rM)];await this.sql`SELECT create_notify_triggers(${this.sql.array(o)})`,await this.sql.listen("table_update",(n)=>{const t=n.split(","),S=t[0],f=t[1],T=`${S}("${f}")`;if(this.observers.has(T))this.observers.get(T).next(T)})}constructor(o={host:Pn.POSTGRES_HOST,port:Pn.POSTGRES_PORT,user:Pn.POSTGRES_USER,password:Pn.POSTGRES_PASSWORD,database:Pn.POSTGRES_DATABASE}){this.options=o,this.sql=Bt(o),this.drizzle=xf(this.sql,{schema:CM})}observe(o,n){if(!this.observers.has(o))this.observers.set(o,new s);this.observers.get(o).subscribe("SINGLETON",n)}}var lf={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"},IM=PM(lf).map(([o])=>Vo.literal(Number(o))),D0=Vo.union([IM[0],IM[1],...IM]),JJ=Vo.tuple([D0,Vo.string()]);function BM(){Cn.logger.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}var Cn=new HT;Cn.logger.info(" ready");var jM=RJ(import.meta.dir,"..","app"),C0=new LM;r0({port:Pn.FRONTEND_PORT??3333,async fetch(o,n){try{const t=new Date,S=new URL(o.url),f=n.requestIP(o)?.address??"??";Cn.logger.info(t,f,o.method,S.pathname);const[T]=await C0.drizzle.select({banishedUntil:vS.banishedUntil}).from(vS).where(Ct(vS.ip,f)).limit(1),M=T?.banishedUntil===null,F=T?.banishedUntil&&T.banishedUntil>t;if(M||F)throw Cn.logger.info(`\uD83D\uDE45 request from banned ip ${f}`),[403,f];if(S.pathname==="/")return new Response(Bun.file(RJ(jM,"index.html")));if(S.pathname==="/index.html")return Response.redirect("/");const k=U0(jM,S.pathname),A=V0(k);if(!A.startsWith(jM))throw[403,"Access Denied"];if(!await yJ(A).exists())return Response.redirect("/");return new Response(yJ(A))}catch(t){const S=JJ.safeParse(t);if(S.success){const[f,T]=S.data,F=`${lf[f]}. ${T}`;return Cn.logger.info(`\u274C ${f}: ${F}`),new Response(F,{status:f})}if(t instanceof Error)Cn.logger.error(t.message);else{const f=Ut(t);Cn.logger.error("frontend server threw",f)}return new Response(lf[500],{status:500})}}});process.on("SIGINT",()=>{Cn.logger.info("\u2757 received SIGINT; exiting gracefully"),BM()});process.on("SIGTERM",()=>{Cn.logger.info("\u2757 received SIGTERM; exiting gracefully"),BM()});process.on("exit",()=>{Cn.logger.info("\u2757 received exit; exiting gracefully"),BM()});Cn.logger.info(`\uD83D\uDEEB frontend server running at http://localhost:${Pn.FRONTEND_PORT??3333}/`);
|
|
29
|
+
`;await n.execute(R`CREATE SCHEMA IF NOT EXISTS ${R.identifier(f)}`),await n.execute(T);const F=(await n.all(R`select id, hash, created_at from ${R.identifier(f)}.${R.identifier(S)} order by created_at desc limit 1`))[0];await n.transaction(async(k)=>{for await(let A of o)if(!F||Number(F.created_at)<A.folderMillis){for(let $ of A.sql)await k.execute(R.raw($));await k.execute(R`insert into ${R.identifier(f)}.${R.identifier(S)} ("hash", "created_at") values(${A.hash}, ${A.folderMillis})`)}})}escapeName(o){return`"${o}"`}escapeParam(o){return`\$${o+1}`}escapeString(o){return`'${o.replace(/'/g,"''")}'`}buildWithCTE(o){if(!o?.length)return;const n=[R`with `];for(let[t,S]of o.entries())if(n.push(R`${R.identifier(S._.alias)} as (${S._.sql})`),t<o.length-1)n.push(R`, `);return n.push(R` `),R.join(n)}buildDeleteQuery({table:o,where:n,returning:t,withList:S}){const f=this.buildWithCTE(S),T=t?R` returning ${this.buildSelection(t,{isSingleTable:!0})}`:void 0,M=n?R` where ${n}`:void 0;return R`${f}delete from ${o}${M}${T}`}buildUpdateSet(o,n){const t=o[h.Symbol.Columns],S=Object.keys(t).filter((T)=>n[T]!==void 0||t[T]?.onUpdateFn!==void 0),f=S.length;return R.join(S.flatMap((T,M)=>{const F=t[T],k=n[T]??R.param(F.onUpdateFn(),F),A=R`${R.identifier(this.casing.getColumnCasing(F))} = ${k}`;if(M<f-1)return[A,R.raw(", ")];return[A]}))}buildUpdateQuery({table:o,set:n,where:t,returning:S,withList:f}){const T=this.buildWithCTE(f),M=this.buildUpdateSet(o,n),F=S?R` returning ${this.buildSelection(S,{isSingleTable:!0})}`:void 0,k=t?R` where ${t}`:void 0;return R`${T}update ${o} set ${M}${k}${F}`}buildSelection(o,{isSingleTable:n=!1}={}){const t=o.length,S=o.flatMap(({field:f},T)=>{const M=[];if(Y(f,q.Aliased)&&f.isSelectionField)M.push(R.identifier(f.fieldAlias));else if(Y(f,q.Aliased)||Y(f,q)){const F=Y(f,q.Aliased)?f.sql:f;if(n)M.push(new q(F.queryChunks.map((k)=>{if(Y(k,C))return R.identifier(this.casing.getColumnCasing(k));return k})));else M.push(F);if(Y(f,q.Aliased))M.push(R` as ${R.identifier(f.fieldAlias)}`)}else if(Y(f,Xo))if(n)M.push(R.identifier(this.casing.getColumnCasing(f)));else M.push(f);if(T<t-1)M.push(R`, `);return M});return R.join(S)}buildSelectQuery({withList:o,fields:n,fieldsFlat:t,where:S,having:f,table:T,joins:M,orderBy:F,groupBy:k,limit:A,offset:$,lockingClause:O,distinct:K,setOperators:G}){const I=t??_n(n);for(let no of I)if(Y(no.field,Xo)&&Wn(no.field.table)!==(Y(T,xo)?T._.alias:Y(T,DS)?T[mo].name:Y(T,q)?void 0:Wn(T))&&!((So)=>M?.some(({alias:_o})=>_o===(So[h.Symbol.IsAlias]?Wn(So):So[h.Symbol.BaseName])))(no.field.table)){const So=Wn(no.field.table);throw new Error(`Your "${no.path.join("->")}" field references a column "${So}"."${no.field.name}", but the table "${So}" is not part of the query! Did you forget to join it?`)}const H=!M||M.length===0,V=this.buildWithCTE(o);let m;if(K)m=K===!0?R` distinct`:R` distinct on (${R.join(K.on,R`, `)})`;const j=this.buildSelection(I,{isSingleTable:H}),r=(()=>{if(Y(T,h)&&T[h.Symbol.OriginalName]!==T[h.Symbol.Name]){let no=R`${R.identifier(T[h.Symbol.OriginalName])}`;if(T[h.Symbol.Schema])no=R`${R.identifier(T[h.Symbol.Schema])}.${no}`;return R`${no} ${R.identifier(T[h.Symbol.Name])}`}return T})(),i=[];if(M)for(let[no,So]of M.entries()){if(no===0)i.push(R` `);const _o=So.table,Fn=So.lateral?R` lateral`:void 0;if(Y(_o,Qn)){const E=_o[Qn.Symbol.Name],p=_o[Qn.Symbol.Schema],To=_o[Qn.Symbol.OriginalName],Ro=E===To?void 0:So.alias;i.push(R`${R.raw(So.joinType)} join${Fn} ${p?R`${R.identifier(p)}.`:void 0}${R.identifier(To)}${Ro&&R` ${R.identifier(Ro)}`} on ${So.on}`)}else if(Y(_o,fn)){const E=_o[mo].name,p=_o[mo].schema,To=_o[mo].originalName,Ro=E===To?void 0:So.alias;i.push(R`${R.raw(So.joinType)} join${Fn} ${p?R`${R.identifier(p)}.`:void 0}${R.identifier(To)}${Ro&&R` ${R.identifier(Ro)}`} on ${So.on}`)}else i.push(R`${R.raw(So.joinType)} join${Fn} ${_o} on ${So.on}`);if(no<M.length-1)i.push(R` `)}const X=R.join(i),w=S?R` where ${S}`:void 0,z=f?R` having ${f}`:void 0;let B;if(F&&F.length>0)B=R` order by ${R.join(F,R`, `)}`;let N;if(k&&k.length>0)N=R` group by ${R.join(k,R`, `)}`;const _=typeof A==="object"||typeof A==="number"&&A>=0?R` limit ${A}`:void 0,c=$?R` offset ${$}`:void 0,U=R.empty();if(O){const no=R` for ${R.raw(O.strength)}`;if(O.config.of)no.append(R` of ${R.join(Array.isArray(O.config.of)?O.config.of:[O.config.of],R`, `)}`);if(O.config.noWait)no.append(R` no wait`);else if(O.config.skipLocked)no.append(R` skip locked`);U.append(no)}const l=R`${V}select${m} ${j} from ${r}${X}${w}${N}${z}${B}${_}${c}${U}`;if(G.length>0)return this.buildSetOperations(l,G);return l}buildSetOperations(o,n){const[t,...S]=n;if(!t)throw new Error("Cannot pass undefined values to any set operator");if(S.length===0)return this.buildSetOperationQuery({leftSelect:o,setOperator:t});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:o,setOperator:t}),S)}buildSetOperationQuery({leftSelect:o,setOperator:{type:n,isAll:t,rightSelect:S,limit:f,orderBy:T,offset:M}}){const F=R`(${o.getSQL()}) `,k=R`(${S.getSQL()})`;let A;if(T&&T.length>0){const G=[];for(let I of T)if(Y(I,C))G.push(R.identifier(I.name));else if(Y(I,q)){for(let H=0;H<I.queryChunks.length;H++){const V=I.queryChunks[H];if(Y(V,C))I.queryChunks[H]=R.identifier(V.name)}G.push(R`${I}`)}else G.push(R`${I}`);A=R` order by ${R.join(G,R`, `)} `}const $=typeof f==="object"||typeof f==="number"&&f>=0?R` limit ${f}`:void 0,O=R.raw(`${n} ${t?"all ":""}`),K=M?R` offset ${M}`:void 0;return R`${F}${O}${k}${A}${$}${K}`}buildInsertQuery({table:o,values:n,onConflict:t,returning:S,withList:f}){const T=[],M=o[h.Symbol.Columns],F=Object.entries(M).filter(([G,I])=>!I.shouldDisableInsert()),k=F.map(([,G])=>R.identifier(this.casing.getColumnCasing(G)));for(let[G,I]of n.entries()){const H=[];for(let[V,m]of F){const j=I[V];if(j===void 0||Y(j,An)&&j.value===void 0)if(m.defaultFn!==void 0){const r=m.defaultFn(),i=Y(r,q)?r:R.param(r,m);H.push(i)}else if(!m.default&&m.onUpdateFn!==void 0){const r=m.onUpdateFn(),i=Y(r,q)?r:R.param(r,m);H.push(i)}else H.push(R`default`);else H.push(j)}if(T.push(H),G<n.length-1)T.push(R`, `)}const A=this.buildWithCTE(f),$=R.join(T),O=S?R` returning ${this.buildSelection(S,{isSingleTable:!0})}`:void 0,K=t?R` on conflict ${t}`:void 0;return R`${A}insert into ${o} ${k} values ${$}${K}${O}`}buildRefreshMaterializedViewQuery({view:o,concurrently:n,withNoData:t}){const S=n?R` concurrently`:void 0,f=t?R` with no data`:void 0;return R`refresh materialized view${S} ${o}${f}`}prepareTyping(o){if(Y(o,Yf)||Y(o,Xf))return"json";else if(Y(o,Ef))return"decimal";else if(Y(o,Gf))return"time";else if(Y(o,zf)||Y(o,Hf))return"timestamp";else if(Y(o,_f)||Y(o,wf))return"date";else if(Y(o,mf))return"uuid";else return"none"}sqlToQuery(o,n){return o.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:n})}buildRelationalQueryWithoutPK({fullSchema:o,schema:n,tableNamesMap:t,table:S,tableConfig:f,queryConfig:T,tableAlias:M,nestedQueryRelation:F,joinOn:k}){let A=[],$,O,K=[],G;const I=[];if(T===!0)A=Object.entries(f.columns).map(([m,j])=>({dbKey:j.name,tsKey:m,field:Bn(j,M),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{const V=Object.fromEntries(Object.entries(f.columns).map(([w,z])=>[w,Bn(z,M)]));if(T.where){const w=typeof T.where==="function"?T.where(V,H$()):T.where;G=w&&wS(w,M)}const m=[];let j=[];if(T.columns){let w=!1;for(let[z,B]of Object.entries(T.columns)){if(B===void 0)continue;if(z in f.columns){if(!w&&B===!0)w=!0;j.push(z)}}if(j.length>0)j=w?j.filter((z)=>T.columns?.[z]===!0):Object.keys(f.columns).filter((z)=>!j.includes(z))}else j=Object.keys(f.columns);for(let w of j){const z=f.columns[w];m.push({tsKey:w,value:z})}let r=[];if(T.with)r=Object.entries(T.with).filter((w)=>!!w[1]).map(([w,z])=>({tsKey:w,queryConfig:z,relation:f.relations[w]}));let i;if(T.extras){i=typeof T.extras==="function"?T.extras(V,{sql:R}):T.extras;for(let[w,z]of Object.entries(i))m.push({tsKey:w,value:pT(z,M)})}for(let{tsKey:w,value:z}of m)A.push({dbKey:Y(z,q.Aliased)?z.fieldAlias:f.columns[w].name,tsKey:w,field:Y(z,Xo)?Bn(z,M):z,relationTableTsKey:void 0,isJson:!1,selection:[]});let X=typeof T.orderBy==="function"?T.orderBy(V,m$()):T.orderBy??[];if(!Array.isArray(X))X=[X];K=X.map((w)=>{if(Y(w,Xo))return Bn(w,M);return wS(w,M)}),$=T.limit,O=T.offset;for(let{tsKey:w,queryConfig:z,relation:B}of r){const N=D$(n,t,B),_=$t(B.referencedTable),c=t[_],U=`${M}_${w}`,l=KS(...N.fields.map((_o,Fn)=>Ct(Bn(N.references[Fn],U),Bn(_o,M)))),no=this.buildRelationalQueryWithoutPK({fullSchema:o,schema:n,tableNamesMap:t,table:o[c],tableConfig:n[c],queryConfig:Y(B,tt)?z===!0?{limit:1}:{...z,limit:1}:z,tableAlias:U,joinOn:l,nestedQueryRelation:B}),So=R`${R.identifier(U)}.${R.identifier("data")}`.as(w);I.push({on:R`true`,table:new xo(no.sql,{},U),alias:U,joinType:"left",lateral:!0}),A.push({dbKey:w,tsKey:w,field:So,relationTableTsKey:c,isJson:!0,selection:no.selection})}}if(A.length===0)throw new Of({message:`No fields selected for table "${f.tsName}" ("${M}")`});let H;if(G=KS(k,G),F){let V=R`json_build_array(${R.join(A.map(({field:r,tsKey:i,isJson:X})=>X?R`${R.identifier(`${M}_${i}`)}.${R.identifier("data")}`:Y(r,q.Aliased)?r.sql:r),R`, `)})`;if(Y(F,ES))V=R`coalesce(json_agg(${V}${K.length>0?R` order by ${R.join(K,R`, `)}`:void 0}), '[]'::json)`;const m=[{dbKey:"data",tsKey:"data",field:V.as("data"),isJson:!0,relationTableTsKey:f.tsName,selection:A}];if($!==void 0||O!==void 0||K.length>0)H=this.buildSelectQuery({table:Rf(S,M),fields:{},fieldsFlat:[{path:[],field:R.raw("*")}],where:G,limit:$,offset:O,orderBy:K,setOperators:[]}),G=void 0,$=void 0,O=void 0,K=[];else H=Rf(S,M);H=this.buildSelectQuery({table:Y(H,Qn)?H:new xo(H,{},M),fields:{},fieldsFlat:m.map(({field:r})=>({path:[],field:Y(r,Xo)?Bn(r,M):r})),joins:I,where:G,limit:$,offset:O,orderBy:K,setOperators:[]})}else H=this.buildSelectQuery({table:Rf(S,M),fields:{},fieldsFlat:A.map(({field:V})=>({path:[],field:Y(V,Xo)?Bn(V,M):V})),joins:I,where:G,limit:$,offset:O,orderBy:K,setOperators:[]});return{tableTsKey:f.tsName,sql:H,selection:A}}}class Mn{static[y]="SelectionProxyHandler";config;constructor(o){this.config={...o}}get(o,n){if(n==="_")return{...o._,selectedFields:new Proxy(o._.selectedFields,this)};if(n===mo)return{...o[mo],selectedFields:new Proxy(o[mo].selectedFields,this)};if(typeof n==="symbol")return o[n];const S=(Y(o,xo)?o._.selectedFields:Y(o,fn)?o[mo].selectedFields:o)[n];if(Y(S,q.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!S.isSelectionField)return S.sql;const f=S.clone();return f.isSelectionField=!0,f}if(Y(S,q)){if(this.config.sqlBehavior==="sql")return S;throw new Error(`You tried to reference "${n}" 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(Y(S,Xo)){if(this.config.alias)return new Proxy(S,new rt(new Proxy(S.table,new _S(this.config.alias,this.config.replaceOriginalName??!1))));return S}if(typeof S!=="object"||S===null)return S;return new Proxy(S,new Mn(this.config))}}class KM{static[y]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}function ct(o,n){return(t,S,...f)=>{const T=[S,...f].map((M)=>({type:o,isAll:n,rightSelect:M}));for(let M of T)if(!lT(t.getSelectedFields(),M.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return t.addSetOperators(T)}}class on{static[y]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(o){if(this.fields=o.fields,this.session=o.session,this.dialect=o.dialect,o.withList)this.withList=o.withList;this.distinct=o.distinct}from(o){const n=!!this.fields;let t;if(this.fields)t=this.fields;else if(Y(o,xo))t=Object.fromEntries(Object.keys(o._.selectedFields).map((S)=>[S,o[S]]));else if(Y(o,DS))t=o[mo].selectedFields;else if(Y(o,q))t={};else t=rk(o);return new XM({table:o,fields:t,isPartialSelect:n,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}}class d$ extends KM{static[y]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:o,fields:n,isPartialSelect:t,session:S,dialect:f,withList:T,distinct:M}){super();this.config={withList:T,table:o,fields:{...n},distinct:M,setOperators:[]},this.isPartialSelect=t,this.session=S,this.dialect=f,this._={selectedFields:n},this.tableName=eT(o),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(o){return(n,t)=>{const S=this.tableName,f=eT(n);if(typeof f==="string"&&this.config.joins?.some((T)=>T.alias===f))throw new Error(`Alias "${f}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof S==="string")this.config.fields={[S]:this.config.fields};if(typeof f==="string"&&!Y(n,q)){const T=Y(n,xo)?n._.selectedFields:Y(n,fn)?n[mo].selectedFields:n[h.Symbol.Columns];this.config.fields[f]=T}}if(typeof t==="function")t=t(new Proxy(this.config.fields,new Mn({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:t,table:n,joinType:o,alias:f}),typeof f==="string")switch(o){case"left":{this.joinsNotNullableMap[f]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([T])=>[T,!1])),this.joinsNotNullableMap[f]=!0;break}case"inner":{this.joinsNotNullableMap[f]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([T])=>[T,!1])),this.joinsNotNullableMap[f]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");createSetOperator(o,n){return(t)=>{const S=typeof t==="function"?t(ER()):t;if(!lT(this.getSelectedFields(),S.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:o,isAll:n,rightSelect:S}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);intersectAll=this.createSetOperator("intersect",!0);except=this.createSetOperator("except",!1);exceptAll=this.createSetOperator("except",!0);addSetOperators(o){return this.config.setOperators.push(...o),this}where(o){if(typeof o==="function")o=o(new Proxy(this.config.fields,new Mn({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=o,this}having(o){if(typeof o==="function")o=o(new Proxy(this.config.fields,new Mn({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=o,this}groupBy(...o){if(typeof o[0]==="function"){const n=o[0](new Proxy(this.config.fields,new Mn({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(n)?n:[n]}else this.config.groupBy=o;return this}orderBy(...o){if(typeof o[0]==="function"){const n=o[0](new Proxy(this.config.fields,new Mn({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),t=Array.isArray(n)?n:[n];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=t;else this.config.orderBy=t}else{const n=o;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=n;else this.config.orderBy=n}return this}limit(o){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=o;else this.config.limit=o;return this}offset(o){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=o;else this.config.offset=o;return this}for(o,n={}){return this.config.lockingClause={strength:o,config:n},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){const{typings:o,...n}=this.dialect.sqlToQuery(this.getSQL());return n}as(o){return new Proxy(new xo(this.getSQL(),this.config.fields,o),new Mn({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new Mn({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class XM extends d${static[y]="PgSelect";_prepare(o){const{session:n,config:t,dialect:S,joinsNotNullableMap:f}=this;if(!n)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return Wo.startActiveSpan("drizzle.prepareQuery",()=>{const T=_n(t.fields),M=n.prepareQuery(S.sqlToQuery(this.getSQL()),T,o,!0);return M.joinsNotNullableMap=f,M})}prepare(o){return this._prepare(o)}execute=(o)=>{return Wo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o)})}}Vk(XM,[so]);var ER=()=>({union:GR,unionAll:zR,intersect:HR,intersectAll:mR,except:QR,exceptAll:DR}),GR=ct("union",!1),zR=ct("union",!0),HR=ct("intersect",!1),mR=ct("intersect",!0),QR=ct("except",!1),DR=ct("except",!0);class YM{static[y]="PgQueryBuilder";dialect;dialectConfig;constructor(o){this.dialect=Y(o,Wt)?o:void 0,this.dialectConfig=Y(o,Wt)?void 0:o}$with(o){const n=this;return{as(t){if(typeof t==="function")t=t(n);return new Proxy(new WS(t.getSQL(),t.getSelectedFields(),o,!0),new Mn({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}with(...o){const n=this;function t(T){return new on({fields:T??void 0,session:void 0,dialect:n.getDialect(),withList:o})}function S(T){return new on({fields:T??void 0,session:void 0,dialect:n.getDialect(),distinct:!0})}function f(T,M){return new on({fields:M??void 0,session:void 0,dialect:n.getDialect(),distinct:{on:T}})}return{select:t,selectDistinct:S,selectDistinctOn:f}}select(o){return new on({fields:o??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(o){return new on({fields:o??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(o,n){return new on({fields:n??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:o}})}getDialect(){if(!this.dialect)this.dialect=new Wt(this.dialectConfig);return this.dialect}}class EM extends so{constructor(o,n,t){super();this.session=n,this.dialect=t,this.config={view:o}}static[y]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){const{typings:o,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(o){return Wo.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,o,!0)})}prepare(o){return this._prepare(o)}execute=(o)=>{return Wo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o)})}}class xf{constructor(o,n,t,S){this.table=o,this.session=n,this.dialect=t,this.withList=S}static[y]="PgUpdateBuilder";set(o){return new u$(this.table,Wf(this.table,o),this.session,this.dialect,this.withList)}}class u$ extends so{constructor(o,n,t,S,f){super();this.session=t,this.dialect=S,this.config={set:n,table:o,withList:f}}static[y]="PgUpdate";config;where(o){return this.config.where=o,this}returning(o=this.config.table[h.Symbol.Columns]){return this.config.returning=_n(o),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){const{typings:o,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(o){return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,o,!0)}prepare(o){return this._prepare(o)}execute=(o)=>{return this._prepare().execute(o)};$dynamic(){return this}}class US extends q{constructor(o){super(US.buildEmbeddedCount(o.source,o.filters).queryChunks);this.params=o,this.mapWith(Number),this.session=o.session,this.sql=US.buildCount(o.source,o.filters)}sql;static[y]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(o,n){return R`(select count(*) from ${o}${R.raw(" where ").if(n)}${n})`}static buildCount(o,n){return R`select count(*) as count from ${o}${R.raw(" where ").if(n)}${n};`}then(o,n){return Promise.resolve(this.session.count(this.sql)).then(o,n)}catch(o){return this.then(void 0,o)}finally(o){return this.then((n)=>{return o?.(),n},(n)=>{throw o?.(),n})}}class zM{constructor(o,n,t,S,f,T,M){this.fullSchema=o,this.schema=n,this.tableNamesMap=t,this.table=S,this.tableConfig=f,this.dialect=T,this.session=M}static[y]="PgRelationalQueryBuilder";findMany(o){return new GM(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?o:{},"many")}findFirst(o){return new GM(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?{...o,limit:1}:{limit:1},"first")}}class GM extends so{constructor(o,n,t,S,f,T,M,F,k){super();this.fullSchema=o,this.schema=n,this.tableNamesMap=t,this.table=S,this.tableConfig=f,this.dialect=T,this.session=M,this.config=F,this.mode=k}static[y]="PgRelationalQuery";_prepare(o){return Wo.startActiveSpan("drizzle.prepareQuery",()=>{const{query:n,builtQuery:t}=this._toSQL();return this.session.prepareQuery(t,void 0,o,!0,(S,f)=>{const T=S.map((M)=>Qf(this.schema,this.tableConfig,M,n.selection,f));if(this.mode==="first")return T[0];return T})})}prepare(o){return this._prepare(o)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){const o=this._getQuery(),n=this.dialect.sqlToQuery(o.sql);return{query:o,builtQuery:n}}toSQL(){return this._toSQL().builtQuery}execute(){return Wo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute()})}}class HM extends so{constructor(o,n,t,S){super();this.execute=o,this.sql=n,this.query=t,this.mapBatchResult=S}static[y]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(o,n){return n?this.mapBatchResult(o):o}_prepare(){return this}isResponseInArrayMode(){return!1}}class VS{constructor(o,n,t){if(this.dialect=o,this.session=n,this._=t?{schema:t.schema,fullSchema:t.fullSchema,tableNamesMap:t.tableNamesMap,session:n}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:n},this.query={},this._.schema)for(let[S,f]of Object.entries(this._.schema))this.query[S]=new zM(t.fullSchema,this._.schema,this._.tableNamesMap,t.fullSchema[S],f,o,n)}static[y]="PgDatabase";query;$with(o){const n=this;return{as(t){if(typeof t==="function")t=t(new YM(n.dialect));return new Proxy(new WS(t.getSQL(),t.getSelectedFields(),o,!0),new Mn({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}$count(o,n){return new US({source:o,filters:n,session:this.session})}with(...o){const n=this;function t(k){return new on({fields:k??void 0,session:n.session,dialect:n.dialect,withList:o})}function S(k){return new on({fields:k??void 0,session:n.session,dialect:n.dialect,withList:o,distinct:!0})}function f(k,A){return new on({fields:A??void 0,session:n.session,dialect:n.dialect,withList:o,distinct:{on:k}})}function T(k){return new xf(k,n.session,n.dialect,o)}function M(k){return new hf(k,n.session,n.dialect,o)}function F(k){return new Nf(k,n.session,n.dialect,o)}return{select:t,selectDistinct:S,selectDistinctOn:f,update:T,insert:M,delete:F}}select(o){return new on({fields:o??void 0,session:this.session,dialect:this.dialect})}selectDistinct(o){return new on({fields:o??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(o,n){return new on({fields:n??void 0,session:this.session,dialect:this.dialect,distinct:{on:o}})}update(o){return new xf(o,this.session,this.dialect)}insert(o){return new hf(o,this.session,this.dialect)}delete(o){return new Nf(o,this.session,this.dialect)}refreshMaterializedView(o){return new EM(o,this.session,this.dialect)}execute(o){const n=typeof o==="string"?R.raw(o):o.getSQL(),t=this.dialect.sqlToQuery(n),S=this.session.prepareQuery(t,void 0,void 0,!1);return new HM(()=>S.execute(),n,t,(f)=>S.mapResult(f,!0))}transaction(o,n){return this.session.transaction(o,n)}}function mM(o){return new a$(!0,o)}class a${constructor(o,n){this.unique=o,this.name=n}static[y]="PgIndexBuilderOn";on(...o){return new vf(o.map((n)=>{if(Y(n,q))return n;n=n;const t=new OS(n.name,!!n.keyAsName,n.columnType,n.indexConfig);return n.indexConfig=JSON.parse(JSON.stringify(n.defaultConfig)),t}),this.unique,!1,this.name)}onOnly(...o){return new vf(o.map((n)=>{if(Y(n,q))return n;n=n;const t=new OS(n.name,!!n.keyAsName,n.columnType,n.indexConfig);return n.indexConfig=n.defaultConfig,t}),this.unique,!0,this.name)}using(o,...n){return new vf(n.map((t)=>{if(Y(t,q))return t;t=t;const S=new OS(t.name,!!t.keyAsName,t.columnType,t.indexConfig);return t.indexConfig=JSON.parse(JSON.stringify(t.defaultConfig)),S}),this.unique,!0,this.name,o)}}class vf{static[y]="PgIndexBuilder";config;constructor(o,n,t,S,f="btree"){this.config={name:S,columns:o,unique:n,only:t,method:f}}concurrently(){return this.config.concurrently=!0,this}with(o){return this.config.with=o,this}where(o){return this.config.where=o,this}build(o){return new s$(this.config,o)}}class s${static[y]="PgIndex";config;constructor(o,n){this.config={...o,table:n}}}class QM{constructor(o){this.query=o}getQuery(){return this.query}mapResult(o,n){return o}static[y]="PgPreparedQuery";joinsNotNullableMap}class DM{constructor(o){this.dialect=o}static[y]="PgSession";execute(o){return Wo.startActiveSpan("drizzle.operation",()=>{return Wo.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(o),void 0,void 0,!1)}).execute()})}all(o){return this.prepareQuery(this.dialect.sqlToQuery(o),void 0,void 0,!1).all()}async count(o){const n=await this.execute(o);return Number(n[0].count)}}class UM extends VS{constructor(o,n,t,S=0){super(o,n,t);this.schema=t,this.nestedIndex=S}static[y]="PgTransaction";rollback(){throw new ZT}getTransactionConfigSQL(o){const n=[];if(o.isolationLevel)n.push(`isolation level ${o.isolationLevel}`);if(o.accessMode)n.push(o.accessMode);if(typeof o.deferrable==="boolean")n.push(o.deferrable?"deferrable":"not deferrable");return R.raw(n.join(" "))}setTransaction(o){return this.session.execute(R`set transaction ${this.getTransactionConfigSQL(o)}`)}}class oJ extends QM{constructor(o,n,t,S,f,T,M){super({sql:n,params:t});this.client=o,this.queryString=n,this.params=t,this.logger=S,this.fields=f,this._isResponseInArrayMode=T,this.customResultMapper=M}static[y]="PostgresJsPreparedQuery";async execute(o={}){return Wo.startActiveSpan("drizzle.execute",async(n)=>{const t=qT(this.params,o);n?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(t)}),this.logger.logQuery(this.queryString,t);const{fields:S,queryString:f,client:T,joinsNotNullableMap:M,customResultMapper:F}=this;if(!S&&!F)return Wo.startActiveSpan("drizzle.driver.execute",()=>{return T.unsafe(f,t)});const k=await Wo.startActiveSpan("drizzle.driver.execute",()=>{return n?.setAttributes({"drizzle.query.text":f,"drizzle.query.params":JSON.stringify(t)}),T.unsafe(f,t).values()});return Wo.startActiveSpan("drizzle.mapResponse",()=>{return F?F(k):k.map((A)=>Uk(S,A,M))})})}all(o={}){return Wo.startActiveSpan("drizzle.execute",async(n)=>{const t=qT(this.params,o);return n?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(t)}),this.logger.logQuery(this.queryString,t),Wo.startActiveSpan("drizzle.driver.execute",()=>{return n?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(t)}),this.client.unsafe(this.queryString,t)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class rS extends DM{constructor(o,n,t,S={}){super(n);this.client=o,this.schema=t,this.options=S,this.logger=S.logger??new gT}static[y]="PostgresJsSession";logger;prepareQuery(o,n,t,S,f){return new oJ(this.client,o.sql,o.params,this.logger,n,S,f)}query(o,n){return this.logger.logQuery(o,n),this.client.unsafe(o,n).values()}queryObjects(o,n){return this.client.unsafe(o,n)}transaction(o,n){return this.client.begin(async(t)=>{const S=new rS(t,this.dialect,this.schema,this.options),f=new VM(this.dialect,S,this.schema);if(n)await f.setTransaction(n);return o(f)})}}class VM extends UM{constructor(o,n,t,S=0){super(o,n,t,S);this.session=n}static[y]="PostgresJsTransaction";transaction(o){return this.session.client.savepoint((n)=>{const t=new rS(n,this.dialect,this.schema,this.session.options),S=new VM(this.dialect,t,this.schema);return o(S)})}}function bt(o,n={}){const t=(k)=>k;for(let k of["1184","1082","1083","1114"])o.options.parsers[k]=t,o.options.serializers[k]=t;o.options.serializers["114"]=t,o.options.serializers["3802"]=t;const S=new Wt({casing:n.casing});let f;if(n.logger===!0)f=new PT;else if(n.logger!==!1)f=n.logger;let T;if(n.schema){const k=Q$(n.schema,U$);T={fullSchema:n.schema,schema:k.tables,tableNamesMap:k.tableNamesMap}}const M=new rS(o,S,T,{logger:f}),F=new nJ(S,M,T);return F.$client=o,F}function qf(...o){if(typeof o[0]==="function")return bt(o[0],o[1]);if(typeof o[0]==="object"){const{connection:t,client:S,...f}=o[0];if(S)return bt(S,f);if(typeof t==="object"&&t.url!==void 0){const{url:M,...F}=t,k=Bt(M,F);return bt(k,f)}const T=Bt(t);return bt(T,f)}const n=Bt(o[0]);return bt(n,o[1])}class nJ extends VS{static[y]="PostgresJsDatabase"}((o)=>{function n(t){return bt({},t)}o.mock=n})(qf||(qf={}));function VR(o){fJ=o}function pf(){return fJ}function b(o,n){const t=pf(),S=Zf({issueData:n,data:o.data,path:o.path,errorMaps:[o.common.contextualErrorMap,o.schemaErrorMap,t,t===it?void 0:it].filter((f)=>!!f)});o.common.issues.push(S)}function Pf(o,n,t,S){if(t==="a"&&!S)throw new TypeError("Private accessor was defined without a getter");if(typeof n==="function"?o!==n||!S:!n.has(o))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?S:t==="a"?S.call(o):S?S.value:n.get(o)}function TJ(o,n,t,S,f){if(S==="m")throw new TypeError("Private method is not writable");if(S==="a"&&!f)throw new TypeError("Private accessor was defined without a setter");if(typeof n==="function"?o!==n||!f:!n.has(o))throw new TypeError("Cannot write private member to an object whose class did not declare it");return S==="a"?f.call(o,t):f?f.value=t:n.set(o,t),t}function oo(o){if(!o)return{};const{errorMap:n,invalid_type_error:t,required_error:S,description:f}=o;if(n&&(t||S))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(n)return{errorMap:n,description:f};return{errorMap:(M,F)=>{var k,A;const{message:$}=o;if(M.code==="invalid_enum_value")return{message:$!==null&&$!==void 0?$:F.defaultError};if(typeof F.data==="undefined")return{message:(k=$!==null&&$!==void 0?$:S)!==null&&k!==void 0?k:F.defaultError};if(M.code!=="invalid_type")return{message:F.defaultError};return{message:(A=$!==null&&$!==void 0?$:t)!==null&&A!==void 0?A:F.defaultError}},description:f}}function FJ(o){let n="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";if(o.precision)n=`${n}\\.\\d{${o.precision}}`;else if(o.precision==null)n=`${n}(\\.\\d+)?`;return n}function qR(o){return new RegExp(`^${FJ(o)}\$`)}function kJ(o){let n=`${MJ}T${FJ(o)}`;const t=[];if(t.push(o.local?"Z?":"Z"),o.offset)t.push("([+-]\\d{2}:?\\d{2})");return n=`${n}(${t.join("|")})`,new RegExp(`^${n}\$`)}function pR(o,n){if((n==="v4"||!n)&&hR.test(o))return!0;if((n==="v6"||!n)&&xR.test(o))return!0;return!1}function ZR(o,n){const t=(o.toString().split(".")[1]||"").length,S=(n.toString().split(".")[1]||"").length,f=t>S?t:S,T=parseInt(o.toFixed(f).replace(".","")),M=parseInt(n.toFixed(f).replace(".",""));return T%M/Math.pow(10,f)}function Nt(o){if(o instanceof Qo){const n={};for(let t in o.shape){const S=o.shape[t];n[t]=Vn.create(Nt(S))}return new Qo({...o._def,shape:()=>n})}else if(o instanceof Un)return new Un({...o._def,type:Nt(o.element)});else if(o instanceof Vn)return Vn.create(Nt(o.unwrap()));else if(o instanceof Pn)return Pn.create(Nt(o.unwrap()));else if(o instanceof Nn)return Nn.create(o.items.map((n)=>Nt(n)));else return o}function jM(o,n){const t=ft(o),S=ft(n);if(o===n)return{valid:!0,data:o};else if(t===x.object&&S===x.object){const f=Ao.objectKeys(n),T=Ao.objectKeys(o).filter((F)=>f.indexOf(F)!==-1),M={...o,...n};for(let F of T){const k=jM(o[F],n[F]);if(!k.valid)return{valid:!1};M[F]=k.data}return{valid:!0,data:M}}else if(t===x.array&&S===x.array){if(o.length!==n.length)return{valid:!1};const f=[];for(let T=0;T<o.length;T++){const M=o[T],F=n[T],k=jM(M,F);if(!k.valid)return{valid:!1};f.push(k.data)}return{valid:!0,data:f}}else if(t===x.date&&S===x.date&&+o===+n)return{valid:!0,data:o};else return{valid:!1}}function AJ(o,n){return new kt({values:o,typeName:d.ZodEnum,...oo(n)})}function $J(o,n={},t){if(o)return wt.create().superRefine((S,f)=>{var T,M;if(!o(S)){const F=typeof n==="function"?n(S):typeof n==="string"?{message:n}:n,k=(M=(T=F.fatal)!==null&&T!==void 0?T:t)!==null&&M!==void 0?M:!0,A=typeof F==="string"?{message:F}:F;f.addIssue({code:"custom",...A,fatal:k})}});return wt.create()}var Ao;(function(o){o.assertEqual=(f)=>f;function n(f){}o.assertIs=n;function t(f){throw new Error}o.assertNever=t,o.arrayToEnum=(f)=>{const T={};for(let M of f)T[M]=M;return T},o.getValidEnumValues=(f)=>{const T=o.objectKeys(f).filter((F)=>typeof f[f[F]]!=="number"),M={};for(let F of T)M[F]=f[F];return o.objectValues(M)},o.objectValues=(f)=>{return o.objectKeys(f).map(function(T){return f[T]})},o.objectKeys=typeof Object.keys==="function"?(f)=>Object.keys(f):(f)=>{const T=[];for(let M in f)if(Object.prototype.hasOwnProperty.call(f,M))T.push(M);return T},o.find=(f,T)=>{for(let M of f)if(T(M))return M;return},o.isInteger=typeof Number.isInteger==="function"?(f)=>Number.isInteger(f):(f)=>typeof f==="number"&&isFinite(f)&&Math.floor(f)===f;function S(f,T=" | "){return f.map((M)=>typeof M==="string"?`'${M}'`:M).join(T)}o.joinValues=S,o.jsonStringifyReplacer=(f,T)=>{if(typeof T==="bigint")return T.toString();return T}})(Ao||(Ao={}));var CM;(function(o){o.mergeShapes=(n,t)=>{return{...n,...t}}})(CM||(CM={}));var x=Ao.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ft=(o)=>{switch(typeof o){case"undefined":return x.undefined;case"string":return x.string;case"number":return isNaN(o)?x.nan:x.number;case"boolean":return x.boolean;case"function":return x.function;case"bigint":return x.bigint;case"symbol":return x.symbol;case"object":if(Array.isArray(o))return x.array;if(o===null)return x.null;if(o.then&&typeof o.then==="function"&&o.catch&&typeof o.catch==="function")return x.promise;if(typeof Map!=="undefined"&&o instanceof Map)return x.map;if(typeof Set!=="undefined"&&o instanceof Set)return x.set;if(typeof Date!=="undefined"&&o instanceof Date)return x.date;return x.object;default:return x.unknown}},Q=Ao.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),UR=(o)=>{return JSON.stringify(o,null,2).replace(/"([^"]+)":/g,"$1:")};class yn extends Error{constructor(o){super();this.issues=[],this.addIssue=(t)=>{this.issues=[...this.issues,t]},this.addIssues=(t=[])=>{this.issues=[...this.issues,...t]};const n=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,n);else this.__proto__=n;this.name="ZodError",this.issues=o}get errors(){return this.issues}format(o){const n=o||function(f){return f.message},t={_errors:[]},S=(f)=>{for(let T of f.issues)if(T.code==="invalid_union")T.unionErrors.map(S);else if(T.code==="invalid_return_type")S(T.returnTypeError);else if(T.code==="invalid_arguments")S(T.argumentsError);else if(T.path.length===0)t._errors.push(n(T));else{let M=t,F=0;while(F<T.path.length){const k=T.path[F];if(F!==T.path.length-1)M[k]=M[k]||{_errors:[]};else M[k]=M[k]||{_errors:[]},M[k]._errors.push(n(T));M=M[k],F++}}};return S(this),t}static assert(o){if(!(o instanceof yn))throw new Error(`Not a ZodError: ${o}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ao.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(o=(n)=>n.message){const n={},t=[];for(let S of this.issues)if(S.path.length>0)n[S.path[0]]=n[S.path[0]]||[],n[S.path[0]].push(o(S));else t.push(o(S));return{formErrors:t,fieldErrors:n}}get formErrors(){return this.flatten()}}yn.create=(o)=>{return new yn(o)};var it=(o,n)=>{let t;switch(o.code){case Q.invalid_type:if(o.received===x.undefined)t="Required";else t=`Expected ${o.expected}, received ${o.received}`;break;case Q.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(o.expected,Ao.jsonStringifyReplacer)}`;break;case Q.unrecognized_keys:t=`Unrecognized key(s) in object: ${Ao.joinValues(o.keys,", ")}`;break;case Q.invalid_union:t="Invalid input";break;case Q.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${Ao.joinValues(o.options)}`;break;case Q.invalid_enum_value:t=`Invalid enum value. Expected ${Ao.joinValues(o.options)}, received '${o.received}'`;break;case Q.invalid_arguments:t="Invalid function arguments";break;case Q.invalid_return_type:t="Invalid function return type";break;case Q.invalid_date:t="Invalid date";break;case Q.invalid_string:if(typeof o.validation==="object")if("includes"in o.validation){if(t=`Invalid input: must include "${o.validation.includes}"`,typeof o.validation.position==="number")t=`${t} at one or more positions greater than or equal to ${o.validation.position}`}else if("startsWith"in o.validation)t=`Invalid input: must start with "${o.validation.startsWith}"`;else if("endsWith"in o.validation)t=`Invalid input: must end with "${o.validation.endsWith}"`;else Ao.assertNever(o.validation);else if(o.validation!=="regex")t=`Invalid ${o.validation}`;else t="Invalid";break;case Q.too_small:if(o.type==="array")t=`Array must contain ${o.exact?"exactly":o.inclusive?"at least":"more than"} ${o.minimum} element(s)`;else if(o.type==="string")t=`String must contain ${o.exact?"exactly":o.inclusive?"at least":"over"} ${o.minimum} character(s)`;else if(o.type==="number")t=`Number must be ${o.exact?"exactly equal to ":o.inclusive?"greater than or equal to ":"greater than "}${o.minimum}`;else if(o.type==="date")t=`Date must be ${o.exact?"exactly equal to ":o.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(o.minimum))}`;else t="Invalid input";break;case Q.too_big:if(o.type==="array")t=`Array must contain ${o.exact?"exactly":o.inclusive?"at most":"less than"} ${o.maximum} element(s)`;else if(o.type==="string")t=`String must contain ${o.exact?"exactly":o.inclusive?"at most":"under"} ${o.maximum} character(s)`;else if(o.type==="number")t=`Number must be ${o.exact?"exactly":o.inclusive?"less than or equal to":"less than"} ${o.maximum}`;else if(o.type==="bigint")t=`BigInt must be ${o.exact?"exactly":o.inclusive?"less than or equal to":"less than"} ${o.maximum}`;else if(o.type==="date")t=`Date must be ${o.exact?"exactly":o.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(o.maximum))}`;else t="Invalid input";break;case Q.custom:t="Invalid input";break;case Q.invalid_intersection_types:t="Intersection results could not be merged";break;case Q.not_multiple_of:t=`Number must be a multiple of ${o.multipleOf}`;break;case Q.not_finite:t="Number must be finite";break;default:t=n.defaultError,Ao.assertNever(o)}return{message:t}},fJ=it,Zf=(o)=>{const{data:n,path:t,errorMaps:S,issueData:f}=o,T=[...t,...f.path||[]],M={...f,path:T};if(f.message!==void 0)return{...f,path:T,message:f.message};let F="";const k=S.filter((A)=>!!A).slice().reverse();for(let A of k)F=A(M,{data:n,defaultError:F}).message;return{...f,path:T,message:F}},rR=[];class lo{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(o,n){const t=[];for(let S of n){if(S.status==="aborted")return a;if(S.status==="dirty")o.dirty();t.push(S.value)}return{status:o.value,value:t}}static async mergeObjectAsync(o,n){const t=[];for(let S of n){const f=await S.key,T=await S.value;t.push({key:f,value:T})}return lo.mergeObjectSync(o,t)}static mergeObjectSync(o,n){const t={};for(let S of n){const{key:f,value:T}=S;if(f.status==="aborted")return a;if(T.status==="aborted")return a;if(f.status==="dirty")o.dirty();if(T.status==="dirty")o.dirty();if(f.value!=="__proto__"&&(typeof T.value!=="undefined"||S.alwaysSet))t[f.value]=T.value}return{status:o.value,value:t}}}var a=Object.freeze({status:"aborted"}),ht=(o)=>({status:"dirty",value:o}),nn=(o)=>({status:"valid",value:o}),LM=(o)=>o.status==="aborted",IM=(o)=>o.status==="dirty",IS=(o)=>o.status==="valid",jS=(o)=>typeof Promise!=="undefined"&&o instanceof Promise;var Z;(function(o){o.errToObj=(n)=>typeof n==="string"?{message:n}:n||{},o.toString=(n)=>typeof n==="string"?n:n===null||n===void 0?void 0:n.message})(Z||(Z={}));var CS,LS;class rn{constructor(o,n,t,S){this._cachedPath=[],this.parent=o,this.data=n,this._path=t,this._key=S}get path(){if(!this._cachedPath.length)if(this._key instanceof Array)this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var tJ=(o,n)=>{if(IS(n))return{success:!0,data:n.value};else{if(!o.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new yn(o.common.issues);return this._error=t,this._error}}}};class to{constructor(o){this.spa=this.safeParseAsync,this._def=o,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(o){return ft(o.data)}_getOrReturnCtx(o,n){return n||{common:o.parent.common,data:o.data,parsedType:ft(o.data),schemaErrorMap:this._def.errorMap,path:o.path,parent:o.parent}}_processInputParams(o){return{status:new lo,ctx:{common:o.parent.common,data:o.data,parsedType:ft(o.data),schemaErrorMap:this._def.errorMap,path:o.path,parent:o.parent}}}_parseSync(o){const n=this._parse(o);if(jS(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(o){const n=this._parse(o);return Promise.resolve(n)}parse(o,n){const t=this.safeParse(o,n);if(t.success)return t.data;throw t.error}safeParse(o,n){var t;const S={common:{issues:[],async:(t=n===null||n===void 0?void 0:n.async)!==null&&t!==void 0?t:!1,contextualErrorMap:n===null||n===void 0?void 0:n.errorMap},path:(n===null||n===void 0?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:o,parsedType:ft(o)},f=this._parseSync({data:o,path:S.path,parent:S});return tJ(S,f)}async parseAsync(o,n){const t=await this.safeParseAsync(o,n);if(t.success)return t.data;throw t.error}async safeParseAsync(o,n){const t={common:{issues:[],contextualErrorMap:n===null||n===void 0?void 0:n.errorMap,async:!0},path:(n===null||n===void 0?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:o,parsedType:ft(o)},S=this._parse({data:o,path:t.path,parent:t}),f=await(jS(S)?S:Promise.resolve(S));return tJ(t,f)}refine(o,n){const t=(S)=>{if(typeof n==="string"||typeof n==="undefined")return{message:n};else if(typeof n==="function")return n(S);else return n};return this._refinement((S,f)=>{const T=o(S),M=()=>f.addIssue({code:Q.custom,...t(S)});if(typeof Promise!=="undefined"&&T instanceof Promise)return T.then((F)=>{if(!F)return M(),!1;else return!0});if(!T)return M(),!1;else return!0})}refinement(o,n){return this._refinement((t,S)=>{if(!o(t))return S.addIssue(typeof n==="function"?n(t,S):n),!1;else return!0})}_refinement(o){return new Kn({schema:this,typeName:d.ZodEffects,effect:{type:"refinement",refinement:o}})}superRefine(o){return this._refinement(o)}optional(){return Vn.create(this,this._def)}nullable(){return Pn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Un.create(this,this._def)}promise(){return Xt.create(this,this._def)}or(o){return Zt.create([this,o],this._def)}and(o){return Pt.create(this,o,this._def)}transform(o){return new Kn({...oo(this._def),schema:this,typeName:d.ZodEffects,effect:{type:"transform",transform:o}})}default(o){const n=typeof o==="function"?o:()=>o;return new dt({...oo(this._def),innerType:this,defaultValue:n,typeName:d.ZodDefault})}brand(){return new lf({typeName:d.ZodBranded,type:this,...oo(this._def)})}catch(o){const n=typeof o==="function"?o:()=>o;return new ut({...oo(this._def),innerType:this,catchValue:n,typeName:d.ZodCatch})}describe(o){return new this.constructor({...this._def,description:o})}pipe(o){return xS.create(this,o)}readonly(){return at.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var CR=/^c[^\s-]{8,}$/i,LR=/^[0-9a-z]+$/,IR=/^[0-9A-HJKMNP-TV-Z]{26}$/,jR=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,BR=/^[a-z0-9_-]{21}$/i,cR=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,bR=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,NR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",rM,hR=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,xR=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,iR=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,MJ="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",vR=new RegExp(`^${MJ}\$`);class Dn extends to{_parse(o){if(this._def.coerce)o.data=String(o.data);if(this._getType(o)!==x.string){const f=this._getOrReturnCtx(o);return b(f,{code:Q.invalid_type,expected:x.string,received:f.parsedType}),a}const t=new lo;let S=void 0;for(let f of this._def.checks)if(f.kind==="min"){if(o.data.length<f.value)S=this._getOrReturnCtx(o,S),b(S,{code:Q.too_small,minimum:f.value,type:"string",inclusive:!0,exact:!1,message:f.message}),t.dirty()}else if(f.kind==="max"){if(o.data.length>f.value)S=this._getOrReturnCtx(o,S),b(S,{code:Q.too_big,maximum:f.value,type:"string",inclusive:!0,exact:!1,message:f.message}),t.dirty()}else if(f.kind==="length"){const T=o.data.length>f.value,M=o.data.length<f.value;if(T||M){if(S=this._getOrReturnCtx(o,S),T)b(S,{code:Q.too_big,maximum:f.value,type:"string",inclusive:!0,exact:!0,message:f.message});else if(M)b(S,{code:Q.too_small,minimum:f.value,type:"string",inclusive:!0,exact:!0,message:f.message});t.dirty()}}else if(f.kind==="email"){if(!bR.test(o.data))S=this._getOrReturnCtx(o,S),b(S,{validation:"email",code:Q.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="emoji"){if(!rM)rM=new RegExp(NR,"u");if(!rM.test(o.data))S=this._getOrReturnCtx(o,S),b(S,{validation:"emoji",code:Q.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="uuid"){if(!jR.test(o.data))S=this._getOrReturnCtx(o,S),b(S,{validation:"uuid",code:Q.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="nanoid"){if(!BR.test(o.data))S=this._getOrReturnCtx(o,S),b(S,{validation:"nanoid",code:Q.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="cuid"){if(!CR.test(o.data))S=this._getOrReturnCtx(o,S),b(S,{validation:"cuid",code:Q.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="cuid2"){if(!LR.test(o.data))S=this._getOrReturnCtx(o,S),b(S,{validation:"cuid2",code:Q.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="ulid"){if(!IR.test(o.data))S=this._getOrReturnCtx(o,S),b(S,{validation:"ulid",code:Q.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="url")try{new URL(o.data)}catch(T){S=this._getOrReturnCtx(o,S),b(S,{validation:"url",code:Q.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="regex"){if(f.regex.lastIndex=0,!f.regex.test(o.data))S=this._getOrReturnCtx(o,S),b(S,{validation:"regex",code:Q.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="trim")o.data=o.data.trim();else if(f.kind==="includes"){if(!o.data.includes(f.value,f.position))S=this._getOrReturnCtx(o,S),b(S,{code:Q.invalid_string,validation:{includes:f.value,position:f.position},message:f.message}),t.dirty()}else if(f.kind==="toLowerCase")o.data=o.data.toLowerCase();else if(f.kind==="toUpperCase")o.data=o.data.toUpperCase();else if(f.kind==="startsWith"){if(!o.data.startsWith(f.value))S=this._getOrReturnCtx(o,S),b(S,{code:Q.invalid_string,validation:{startsWith:f.value},message:f.message}),t.dirty()}else if(f.kind==="endsWith"){if(!o.data.endsWith(f.value))S=this._getOrReturnCtx(o,S),b(S,{code:Q.invalid_string,validation:{endsWith:f.value},message:f.message}),t.dirty()}else if(f.kind==="datetime"){if(!kJ(f).test(o.data))S=this._getOrReturnCtx(o,S),b(S,{code:Q.invalid_string,validation:"datetime",message:f.message}),t.dirty()}else if(f.kind==="date"){if(!vR.test(o.data))S=this._getOrReturnCtx(o,S),b(S,{code:Q.invalid_string,validation:"date",message:f.message}),t.dirty()}else if(f.kind==="time"){if(!qR(f).test(o.data))S=this._getOrReturnCtx(o,S),b(S,{code:Q.invalid_string,validation:"time",message:f.message}),t.dirty()}else if(f.kind==="duration"){if(!cR.test(o.data))S=this._getOrReturnCtx(o,S),b(S,{validation:"duration",code:Q.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="ip"){if(!pR(o.data,f.version))S=this._getOrReturnCtx(o,S),b(S,{validation:"ip",code:Q.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="base64"){if(!iR.test(o.data))S=this._getOrReturnCtx(o,S),b(S,{validation:"base64",code:Q.invalid_string,message:f.message}),t.dirty()}else Ao.assertNever(f);return{status:t.value,value:o.data}}_regex(o,n,t){return this.refinement((S)=>o.test(S),{validation:n,code:Q.invalid_string,...Z.errToObj(t)})}_addCheck(o){return new Dn({...this._def,checks:[...this._def.checks,o]})}email(o){return this._addCheck({kind:"email",...Z.errToObj(o)})}url(o){return this._addCheck({kind:"url",...Z.errToObj(o)})}emoji(o){return this._addCheck({kind:"emoji",...Z.errToObj(o)})}uuid(o){return this._addCheck({kind:"uuid",...Z.errToObj(o)})}nanoid(o){return this._addCheck({kind:"nanoid",...Z.errToObj(o)})}cuid(o){return this._addCheck({kind:"cuid",...Z.errToObj(o)})}cuid2(o){return this._addCheck({kind:"cuid2",...Z.errToObj(o)})}ulid(o){return this._addCheck({kind:"ulid",...Z.errToObj(o)})}base64(o){return this._addCheck({kind:"base64",...Z.errToObj(o)})}ip(o){return this._addCheck({kind:"ip",...Z.errToObj(o)})}datetime(o){var n,t;if(typeof o==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:o});return this._addCheck({kind:"datetime",precision:typeof(o===null||o===void 0?void 0:o.precision)==="undefined"?null:o===null||o===void 0?void 0:o.precision,offset:(n=o===null||o===void 0?void 0:o.offset)!==null&&n!==void 0?n:!1,local:(t=o===null||o===void 0?void 0:o.local)!==null&&t!==void 0?t:!1,...Z.errToObj(o===null||o===void 0?void 0:o.message)})}date(o){return this._addCheck({kind:"date",message:o})}time(o){if(typeof o==="string")return this._addCheck({kind:"time",precision:null,message:o});return this._addCheck({kind:"time",precision:typeof(o===null||o===void 0?void 0:o.precision)==="undefined"?null:o===null||o===void 0?void 0:o.precision,...Z.errToObj(o===null||o===void 0?void 0:o.message)})}duration(o){return this._addCheck({kind:"duration",...Z.errToObj(o)})}regex(o,n){return this._addCheck({kind:"regex",regex:o,...Z.errToObj(n)})}includes(o,n){return this._addCheck({kind:"includes",value:o,position:n===null||n===void 0?void 0:n.position,...Z.errToObj(n===null||n===void 0?void 0:n.message)})}startsWith(o,n){return this._addCheck({kind:"startsWith",value:o,...Z.errToObj(n)})}endsWith(o,n){return this._addCheck({kind:"endsWith",value:o,...Z.errToObj(n)})}min(o,n){return this._addCheck({kind:"min",value:o,...Z.errToObj(n)})}max(o,n){return this._addCheck({kind:"max",value:o,...Z.errToObj(n)})}length(o,n){return this._addCheck({kind:"length",value:o,...Z.errToObj(n)})}nonempty(o){return this.min(1,Z.errToObj(o))}trim(){return new Dn({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Dn({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Dn({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((o)=>o.kind==="datetime")}get isDate(){return!!this._def.checks.find((o)=>o.kind==="date")}get isTime(){return!!this._def.checks.find((o)=>o.kind==="time")}get isDuration(){return!!this._def.checks.find((o)=>o.kind==="duration")}get isEmail(){return!!this._def.checks.find((o)=>o.kind==="email")}get isURL(){return!!this._def.checks.find((o)=>o.kind==="url")}get isEmoji(){return!!this._def.checks.find((o)=>o.kind==="emoji")}get isUUID(){return!!this._def.checks.find((o)=>o.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((o)=>o.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((o)=>o.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((o)=>o.kind==="cuid2")}get isULID(){return!!this._def.checks.find((o)=>o.kind==="ulid")}get isIP(){return!!this._def.checks.find((o)=>o.kind==="ip")}get isBase64(){return!!this._def.checks.find((o)=>o.kind==="base64")}get minLength(){let o=null;for(let n of this._def.checks)if(n.kind==="min"){if(o===null||n.value>o)o=n.value}return o}get maxLength(){let o=null;for(let n of this._def.checks)if(n.kind==="max"){if(o===null||n.value<o)o=n.value}return o}}Dn.create=(o)=>{var n;return new Dn({checks:[],typeName:d.ZodString,coerce:(n=o===null||o===void 0?void 0:o.coerce)!==null&&n!==void 0?n:!1,...oo(o)})};class Mt extends to{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(o){if(this._def.coerce)o.data=Number(o.data);if(this._getType(o)!==x.number){const f=this._getOrReturnCtx(o);return b(f,{code:Q.invalid_type,expected:x.number,received:f.parsedType}),a}let t=void 0;const S=new lo;for(let f of this._def.checks)if(f.kind==="int"){if(!Ao.isInteger(o.data))t=this._getOrReturnCtx(o,t),b(t,{code:Q.invalid_type,expected:"integer",received:"float",message:f.message}),S.dirty()}else if(f.kind==="min"){if(f.inclusive?o.data<f.value:o.data<=f.value)t=this._getOrReturnCtx(o,t),b(t,{code:Q.too_small,minimum:f.value,type:"number",inclusive:f.inclusive,exact:!1,message:f.message}),S.dirty()}else if(f.kind==="max"){if(f.inclusive?o.data>f.value:o.data>=f.value)t=this._getOrReturnCtx(o,t),b(t,{code:Q.too_big,maximum:f.value,type:"number",inclusive:f.inclusive,exact:!1,message:f.message}),S.dirty()}else if(f.kind==="multipleOf"){if(ZR(o.data,f.value)!==0)t=this._getOrReturnCtx(o,t),b(t,{code:Q.not_multiple_of,multipleOf:f.value,message:f.message}),S.dirty()}else if(f.kind==="finite"){if(!Number.isFinite(o.data))t=this._getOrReturnCtx(o,t),b(t,{code:Q.not_finite,message:f.message}),S.dirty()}else Ao.assertNever(f);return{status:S.value,value:o.data}}gte(o,n){return this.setLimit("min",o,!0,Z.toString(n))}gt(o,n){return this.setLimit("min",o,!1,Z.toString(n))}lte(o,n){return this.setLimit("max",o,!0,Z.toString(n))}lt(o,n){return this.setLimit("max",o,!1,Z.toString(n))}setLimit(o,n,t,S){return new Mt({...this._def,checks:[...this._def.checks,{kind:o,value:n,inclusive:t,message:Z.toString(S)}]})}_addCheck(o){return new Mt({...this._def,checks:[...this._def.checks,o]})}int(o){return this._addCheck({kind:"int",message:Z.toString(o)})}positive(o){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Z.toString(o)})}negative(o){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Z.toString(o)})}nonpositive(o){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Z.toString(o)})}nonnegative(o){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Z.toString(o)})}multipleOf(o,n){return this._addCheck({kind:"multipleOf",value:o,message:Z.toString(n)})}finite(o){return this._addCheck({kind:"finite",message:Z.toString(o)})}safe(o){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Z.toString(o)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Z.toString(o)})}get minValue(){let o=null;for(let n of this._def.checks)if(n.kind==="min"){if(o===null||n.value>o)o=n.value}return o}get maxValue(){let o=null;for(let n of this._def.checks)if(n.kind==="max"){if(o===null||n.value<o)o=n.value}return o}get isInt(){return!!this._def.checks.find((o)=>o.kind==="int"||o.kind==="multipleOf"&&Ao.isInteger(o.value))}get isFinite(){let o=null,n=null;for(let t of this._def.checks)if(t.kind==="finite"||t.kind==="int"||t.kind==="multipleOf")return!0;else if(t.kind==="min"){if(n===null||t.value>n)n=t.value}else if(t.kind==="max"){if(o===null||t.value<o)o=t.value}return Number.isFinite(n)&&Number.isFinite(o)}}Mt.create=(o)=>{return new Mt({checks:[],typeName:d.ZodNumber,coerce:(o===null||o===void 0?void 0:o.coerce)||!1,...oo(o)})};class Ft extends to{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(o){if(this._def.coerce)o.data=BigInt(o.data);if(this._getType(o)!==x.bigint){const f=this._getOrReturnCtx(o);return b(f,{code:Q.invalid_type,expected:x.bigint,received:f.parsedType}),a}let t=void 0;const S=new lo;for(let f of this._def.checks)if(f.kind==="min"){if(f.inclusive?o.data<f.value:o.data<=f.value)t=this._getOrReturnCtx(o,t),b(t,{code:Q.too_small,type:"bigint",minimum:f.value,inclusive:f.inclusive,message:f.message}),S.dirty()}else if(f.kind==="max"){if(f.inclusive?o.data>f.value:o.data>=f.value)t=this._getOrReturnCtx(o,t),b(t,{code:Q.too_big,type:"bigint",maximum:f.value,inclusive:f.inclusive,message:f.message}),S.dirty()}else if(f.kind==="multipleOf"){if(o.data%f.value!==BigInt(0))t=this._getOrReturnCtx(o,t),b(t,{code:Q.not_multiple_of,multipleOf:f.value,message:f.message}),S.dirty()}else Ao.assertNever(f);return{status:S.value,value:o.data}}gte(o,n){return this.setLimit("min",o,!0,Z.toString(n))}gt(o,n){return this.setLimit("min",o,!1,Z.toString(n))}lte(o,n){return this.setLimit("max",o,!0,Z.toString(n))}lt(o,n){return this.setLimit("max",o,!1,Z.toString(n))}setLimit(o,n,t,S){return new Ft({...this._def,checks:[...this._def.checks,{kind:o,value:n,inclusive:t,message:Z.toString(S)}]})}_addCheck(o){return new Ft({...this._def,checks:[...this._def.checks,o]})}positive(o){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Z.toString(o)})}negative(o){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Z.toString(o)})}nonpositive(o){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Z.toString(o)})}nonnegative(o){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Z.toString(o)})}multipleOf(o,n){return this._addCheck({kind:"multipleOf",value:o,message:Z.toString(n)})}get minValue(){let o=null;for(let n of this._def.checks)if(n.kind==="min"){if(o===null||n.value>o)o=n.value}return o}get maxValue(){let o=null;for(let n of this._def.checks)if(n.kind==="max"){if(o===null||n.value<o)o=n.value}return o}}Ft.create=(o)=>{var n;return new Ft({checks:[],typeName:d.ZodBigInt,coerce:(n=o===null||o===void 0?void 0:o.coerce)!==null&&n!==void 0?n:!1,...oo(o)})};class vt extends to{_parse(o){if(this._def.coerce)o.data=Boolean(o.data);if(this._getType(o)!==x.boolean){const t=this._getOrReturnCtx(o);return b(t,{code:Q.invalid_type,expected:x.boolean,received:t.parsedType}),a}return nn(o.data)}}vt.create=(o)=>{return new vt({typeName:d.ZodBoolean,coerce:(o===null||o===void 0?void 0:o.coerce)||!1,...oo(o)})};class _t extends to{_parse(o){if(this._def.coerce)o.data=new Date(o.data);if(this._getType(o)!==x.date){const f=this._getOrReturnCtx(o);return b(f,{code:Q.invalid_type,expected:x.date,received:f.parsedType}),a}if(isNaN(o.data.getTime())){const f=this._getOrReturnCtx(o);return b(f,{code:Q.invalid_date}),a}const t=new lo;let S=void 0;for(let f of this._def.checks)if(f.kind==="min"){if(o.data.getTime()<f.value)S=this._getOrReturnCtx(o,S),b(S,{code:Q.too_small,message:f.message,inclusive:!0,exact:!1,minimum:f.value,type:"date"}),t.dirty()}else if(f.kind==="max"){if(o.data.getTime()>f.value)S=this._getOrReturnCtx(o,S),b(S,{code:Q.too_big,message:f.message,inclusive:!0,exact:!1,maximum:f.value,type:"date"}),t.dirty()}else Ao.assertNever(f);return{status:t.value,value:new Date(o.data.getTime())}}_addCheck(o){return new _t({...this._def,checks:[...this._def.checks,o]})}min(o,n){return this._addCheck({kind:"min",value:o.getTime(),message:Z.toString(n)})}max(o,n){return this._addCheck({kind:"max",value:o.getTime(),message:Z.toString(n)})}get minDate(){let o=null;for(let n of this._def.checks)if(n.kind==="min"){if(o===null||n.value>o)o=n.value}return o!=null?new Date(o):null}get maxDate(){let o=null;for(let n of this._def.checks)if(n.kind==="max"){if(o===null||n.value<o)o=n.value}return o!=null?new Date(o):null}}_t.create=(o)=>{return new _t({checks:[],coerce:(o===null||o===void 0?void 0:o.coerce)||!1,typeName:d.ZodDate,...oo(o)})};class BS extends to{_parse(o){if(this._getType(o)!==x.symbol){const t=this._getOrReturnCtx(o);return b(t,{code:Q.invalid_type,expected:x.symbol,received:t.parsedType}),a}return nn(o.data)}}BS.create=(o)=>{return new BS({typeName:d.ZodSymbol,...oo(o)})};class qt extends to{_parse(o){if(this._getType(o)!==x.undefined){const t=this._getOrReturnCtx(o);return b(t,{code:Q.invalid_type,expected:x.undefined,received:t.parsedType}),a}return nn(o.data)}}qt.create=(o)=>{return new qt({typeName:d.ZodUndefined,...oo(o)})};class pt extends to{_parse(o){if(this._getType(o)!==x.null){const t=this._getOrReturnCtx(o);return b(t,{code:Q.invalid_type,expected:x.null,received:t.parsedType}),a}return nn(o.data)}}pt.create=(o)=>{return new pt({typeName:d.ZodNull,...oo(o)})};class wt extends to{constructor(){super(...arguments);this._any=!0}_parse(o){return nn(o.data)}}wt.create=(o)=>{return new wt({typeName:d.ZodAny,...oo(o)})};class Tt extends to{constructor(){super(...arguments);this._unknown=!0}_parse(o){return nn(o.data)}}Tt.create=(o)=>{return new Tt({typeName:d.ZodUnknown,...oo(o)})};class bn extends to{_parse(o){const n=this._getOrReturnCtx(o);return b(n,{code:Q.invalid_type,expected:x.never,received:n.parsedType}),a}}bn.create=(o)=>{return new bn({typeName:d.ZodNever,...oo(o)})};class cS extends to{_parse(o){if(this._getType(o)!==x.undefined){const t=this._getOrReturnCtx(o);return b(t,{code:Q.invalid_type,expected:x.void,received:t.parsedType}),a}return nn(o.data)}}cS.create=(o)=>{return new cS({typeName:d.ZodVoid,...oo(o)})};class Un extends to{_parse(o){const{ctx:n,status:t}=this._processInputParams(o),S=this._def;if(n.parsedType!==x.array)return b(n,{code:Q.invalid_type,expected:x.array,received:n.parsedType}),a;if(S.exactLength!==null){const T=n.data.length>S.exactLength.value,M=n.data.length<S.exactLength.value;if(T||M)b(n,{code:T?Q.too_big:Q.too_small,minimum:M?S.exactLength.value:void 0,maximum:T?S.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:S.exactLength.message}),t.dirty()}if(S.minLength!==null){if(n.data.length<S.minLength.value)b(n,{code:Q.too_small,minimum:S.minLength.value,type:"array",inclusive:!0,exact:!1,message:S.minLength.message}),t.dirty()}if(S.maxLength!==null){if(n.data.length>S.maxLength.value)b(n,{code:Q.too_big,maximum:S.maxLength.value,type:"array",inclusive:!0,exact:!1,message:S.maxLength.message}),t.dirty()}if(n.common.async)return Promise.all([...n.data].map((T,M)=>{return S.type._parseAsync(new rn(n,T,n.path,M))})).then((T)=>{return lo.mergeArray(t,T)});const f=[...n.data].map((T,M)=>{return S.type._parseSync(new rn(n,T,n.path,M))});return lo.mergeArray(t,f)}get element(){return this._def.type}min(o,n){return new Un({...this._def,minLength:{value:o,message:Z.toString(n)}})}max(o,n){return new Un({...this._def,maxLength:{value:o,message:Z.toString(n)}})}length(o,n){return new Un({...this._def,exactLength:{value:o,message:Z.toString(n)}})}nonempty(o){return this.min(1,o)}}Un.create=(o,n)=>{return new Un({type:o,minLength:null,maxLength:null,exactLength:null,typeName:d.ZodArray,...oo(n)})};class Qo extends to{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const o=this._def.shape(),n=Ao.objectKeys(o);return this._cached={shape:o,keys:n}}_parse(o){if(this._getType(o)!==x.object){const k=this._getOrReturnCtx(o);return b(k,{code:Q.invalid_type,expected:x.object,received:k.parsedType}),a}const{status:t,ctx:S}=this._processInputParams(o),{shape:f,keys:T}=this._getCached(),M=[];if(!(this._def.catchall instanceof bn&&this._def.unknownKeys==="strip")){for(let k in S.data)if(!T.includes(k))M.push(k)}const F=[];for(let k of T){const A=f[k],$=S.data[k];F.push({key:{status:"valid",value:k},value:A._parse(new rn(S,$,S.path,k)),alwaysSet:k in S.data})}if(this._def.catchall instanceof bn){const k=this._def.unknownKeys;if(k==="passthrough")for(let A of M)F.push({key:{status:"valid",value:A},value:{status:"valid",value:S.data[A]}});else if(k==="strict"){if(M.length>0)b(S,{code:Q.unrecognized_keys,keys:M}),t.dirty()}else if(k==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const k=this._def.catchall;for(let A of M){const $=S.data[A];F.push({key:{status:"valid",value:A},value:k._parse(new rn(S,$,S.path,A)),alwaysSet:A in S.data})}}if(S.common.async)return Promise.resolve().then(async()=>{const k=[];for(let A of F){const $=await A.key,O=await A.value;k.push({key:$,value:O,alwaysSet:A.alwaysSet})}return k}).then((k)=>{return lo.mergeObjectSync(t,k)});else return lo.mergeObjectSync(t,F)}get shape(){return this._def.shape()}strict(o){return Z.errToObj,new Qo({...this._def,unknownKeys:"strict",...o!==void 0?{errorMap:(n,t)=>{var S,f,T,M;const F=(T=(f=(S=this._def).errorMap)===null||f===void 0?void 0:f.call(S,n,t).message)!==null&&T!==void 0?T:t.defaultError;if(n.code==="unrecognized_keys")return{message:(M=Z.errToObj(o).message)!==null&&M!==void 0?M:F};return{message:F}}}:{}})}strip(){return new Qo({...this._def,unknownKeys:"strip"})}passthrough(){return new Qo({...this._def,unknownKeys:"passthrough"})}extend(o){return new Qo({...this._def,shape:()=>({...this._def.shape(),...o})})}merge(o){return new Qo({unknownKeys:o._def.unknownKeys,catchall:o._def.catchall,shape:()=>({...this._def.shape(),...o._def.shape()}),typeName:d.ZodObject})}setKey(o,n){return this.augment({[o]:n})}catchall(o){return new Qo({...this._def,catchall:o})}pick(o){const n={};return Ao.objectKeys(o).forEach((t)=>{if(o[t]&&this.shape[t])n[t]=this.shape[t]}),new Qo({...this._def,shape:()=>n})}omit(o){const n={};return Ao.objectKeys(this.shape).forEach((t)=>{if(!o[t])n[t]=this.shape[t]}),new Qo({...this._def,shape:()=>n})}deepPartial(){return Nt(this)}partial(o){const n={};return Ao.objectKeys(this.shape).forEach((t)=>{const S=this.shape[t];if(o&&!o[t])n[t]=S;else n[t]=S.optional()}),new Qo({...this._def,shape:()=>n})}required(o){const n={};return Ao.objectKeys(this.shape).forEach((t)=>{if(o&&!o[t])n[t]=this.shape[t];else{let f=this.shape[t];while(f instanceof Vn)f=f._def.innerType;n[t]=f}}),new Qo({...this._def,shape:()=>n})}keyof(){return AJ(Ao.objectKeys(this.shape))}}Qo.create=(o,n)=>{return new Qo({shape:()=>o,unknownKeys:"strip",catchall:bn.create(),typeName:d.ZodObject,...oo(n)})};Qo.strictCreate=(o,n)=>{return new Qo({shape:()=>o,unknownKeys:"strict",catchall:bn.create(),typeName:d.ZodObject,...oo(n)})};Qo.lazycreate=(o,n)=>{return new Qo({shape:o,unknownKeys:"strip",catchall:bn.create(),typeName:d.ZodObject,...oo(n)})};class Zt extends to{_parse(o){const{ctx:n}=this._processInputParams(o),t=this._def.options;function S(f){for(let M of f)if(M.result.status==="valid")return M.result;for(let M of f)if(M.result.status==="dirty")return n.common.issues.push(...M.ctx.common.issues),M.result;const T=f.map((M)=>new yn(M.ctx.common.issues));return b(n,{code:Q.invalid_union,unionErrors:T}),a}if(n.common.async)return Promise.all(t.map(async(f)=>{const T={...n,common:{...n.common,issues:[]},parent:null};return{result:await f._parseAsync({data:n.data,path:n.path,parent:T}),ctx:T}})).then(S);else{let f=void 0;const T=[];for(let F of t){const k={...n,common:{...n.common,issues:[]},parent:null},A=F._parseSync({data:n.data,path:n.path,parent:k});if(A.status==="valid")return A;else if(A.status==="dirty"&&!f)f={result:A,ctx:k};if(k.common.issues.length)T.push(k.common.issues)}if(f)return n.common.issues.push(...f.ctx.common.issues),f.result;const M=T.map((F)=>new yn(F));return b(n,{code:Q.invalid_union,unionErrors:M}),a}}get options(){return this._def.options}}Zt.create=(o,n)=>{return new Zt({options:o,typeName:d.ZodUnion,...oo(n)})};var Zn=(o)=>{if(o instanceof gt)return Zn(o.schema);else if(o instanceof Kn)return Zn(o.innerType());else if(o instanceof lt)return[o.value];else if(o instanceof kt)return o.options;else if(o instanceof et)return Ao.objectValues(o.enum);else if(o instanceof dt)return Zn(o._def.innerType);else if(o instanceof qt)return[void 0];else if(o instanceof pt)return[null];else if(o instanceof Vn)return[void 0,...Zn(o.unwrap())];else if(o instanceof Pn)return[null,...Zn(o.unwrap())];else if(o instanceof lf)return Zn(o.unwrap());else if(o instanceof at)return Zn(o.unwrap());else if(o instanceof ut)return Zn(o._def.innerType);else return[]};class gf extends to{_parse(o){const{ctx:n}=this._processInputParams(o);if(n.parsedType!==x.object)return b(n,{code:Q.invalid_type,expected:x.object,received:n.parsedType}),a;const t=this.discriminator,S=n.data[t],f=this.optionsMap.get(S);if(!f)return b(n,{code:Q.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[t]}),a;if(n.common.async)return f._parseAsync({data:n.data,path:n.path,parent:n});else return f._parseSync({data:n.data,path:n.path,parent:n})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(o,n,t){const S=new Map;for(let f of n){const T=Zn(f.shape[o]);if(!T.length)throw new Error(`A discriminator value for key \`${o}\` could not be extracted from all schema options`);for(let M of T){if(S.has(M))throw new Error(`Discriminator property ${String(o)} has duplicate value ${String(M)}`);S.set(M,f)}}return new gf({typeName:d.ZodDiscriminatedUnion,discriminator:o,options:n,optionsMap:S,...oo(t)})}}class Pt extends to{_parse(o){const{status:n,ctx:t}=this._processInputParams(o),S=(f,T)=>{if(LM(f)||LM(T))return a;const M=jM(f.value,T.value);if(!M.valid)return b(t,{code:Q.invalid_intersection_types}),a;if(IM(f)||IM(T))n.dirty();return{status:n.value,value:M.data}};if(t.common.async)return Promise.all([this._def.left._parseAsync({data:t.data,path:t.path,parent:t}),this._def.right._parseAsync({data:t.data,path:t.path,parent:t})]).then(([f,T])=>S(f,T));else return S(this._def.left._parseSync({data:t.data,path:t.path,parent:t}),this._def.right._parseSync({data:t.data,path:t.path,parent:t}))}}Pt.create=(o,n,t)=>{return new Pt({left:o,right:n,typeName:d.ZodIntersection,...oo(t)})};class Nn extends to{_parse(o){const{status:n,ctx:t}=this._processInputParams(o);if(t.parsedType!==x.array)return b(t,{code:Q.invalid_type,expected:x.array,received:t.parsedType}),a;if(t.data.length<this._def.items.length)return b(t,{code:Q.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),a;if(!this._def.rest&&t.data.length>this._def.items.length)b(t,{code:Q.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty();const f=[...t.data].map((T,M)=>{const F=this._def.items[M]||this._def.rest;if(!F)return null;return F._parse(new rn(t,T,t.path,M))}).filter((T)=>!!T);if(t.common.async)return Promise.all(f).then((T)=>{return lo.mergeArray(n,T)});else return lo.mergeArray(n,f)}get items(){return this._def.items}rest(o){return new Nn({...this._def,rest:o})}}Nn.create=(o,n)=>{if(!Array.isArray(o))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Nn({items:o,typeName:d.ZodTuple,rest:null,...oo(n)})};class bS extends to{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(o){const{status:n,ctx:t}=this._processInputParams(o);if(t.parsedType!==x.object)return b(t,{code:Q.invalid_type,expected:x.object,received:t.parsedType}),a;const S=[],f=this._def.keyType,T=this._def.valueType;for(let M in t.data)S.push({key:f._parse(new rn(t,M,t.path,M)),value:T._parse(new rn(t,t.data[M],t.path,M)),alwaysSet:M in t.data});if(t.common.async)return lo.mergeObjectAsync(n,S);else return lo.mergeObjectSync(n,S)}get element(){return this._def.valueType}static create(o,n,t){if(n instanceof to)return new bS({keyType:o,valueType:n,typeName:d.ZodRecord,...oo(t)});return new bS({keyType:Dn.create(),valueType:o,typeName:d.ZodRecord,...oo(n)})}}class NS extends to{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(o){const{status:n,ctx:t}=this._processInputParams(o);if(t.parsedType!==x.map)return b(t,{code:Q.invalid_type,expected:x.map,received:t.parsedType}),a;const S=this._def.keyType,f=this._def.valueType,T=[...t.data.entries()].map(([M,F],k)=>{return{key:S._parse(new rn(t,M,t.path,[k,"key"])),value:f._parse(new rn(t,F,t.path,[k,"value"]))}});if(t.common.async){const M=new Map;return Promise.resolve().then(async()=>{for(let F of T){const k=await F.key,A=await F.value;if(k.status==="aborted"||A.status==="aborted")return a;if(k.status==="dirty"||A.status==="dirty")n.dirty();M.set(k.value,A.value)}return{status:n.value,value:M}})}else{const M=new Map;for(let F of T){const{key:k,value:A}=F;if(k.status==="aborted"||A.status==="aborted")return a;if(k.status==="dirty"||A.status==="dirty")n.dirty();M.set(k.value,A.value)}return{status:n.value,value:M}}}}NS.create=(o,n,t)=>{return new NS({valueType:n,keyType:o,typeName:d.ZodMap,...oo(t)})};class Kt extends to{_parse(o){const{status:n,ctx:t}=this._processInputParams(o);if(t.parsedType!==x.set)return b(t,{code:Q.invalid_type,expected:x.set,received:t.parsedType}),a;const S=this._def;if(S.minSize!==null){if(t.data.size<S.minSize.value)b(t,{code:Q.too_small,minimum:S.minSize.value,type:"set",inclusive:!0,exact:!1,message:S.minSize.message}),n.dirty()}if(S.maxSize!==null){if(t.data.size>S.maxSize.value)b(t,{code:Q.too_big,maximum:S.maxSize.value,type:"set",inclusive:!0,exact:!1,message:S.maxSize.message}),n.dirty()}const f=this._def.valueType;function T(F){const k=new Set;for(let A of F){if(A.status==="aborted")return a;if(A.status==="dirty")n.dirty();k.add(A.value)}return{status:n.value,value:k}}const M=[...t.data.values()].map((F,k)=>f._parse(new rn(t,F,t.path,k)));if(t.common.async)return Promise.all(M).then((F)=>T(F));else return T(M)}min(o,n){return new Kt({...this._def,minSize:{value:o,message:Z.toString(n)}})}max(o,n){return new Kt({...this._def,maxSize:{value:o,message:Z.toString(n)}})}size(o,n){return this.min(o,n).max(o,n)}nonempty(o){return this.min(1,o)}}Kt.create=(o,n)=>{return new Kt({valueType:o,minSize:null,maxSize:null,typeName:d.ZodSet,...oo(n)})};class xt extends to{constructor(){super(...arguments);this.validate=this.implement}_parse(o){const{ctx:n}=this._processInputParams(o);if(n.parsedType!==x.function)return b(n,{code:Q.invalid_type,expected:x.function,received:n.parsedType}),a;function t(M,F){return Zf({data:M,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,pf(),it].filter((k)=>!!k),issueData:{code:Q.invalid_arguments,argumentsError:F}})}function S(M,F){return Zf({data:M,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,pf(),it].filter((k)=>!!k),issueData:{code:Q.invalid_return_type,returnTypeError:F}})}const f={errorMap:n.common.contextualErrorMap},T=n.data;if(this._def.returns instanceof Xt){const M=this;return nn(async function(...F){const k=new yn([]),A=await M._def.args.parseAsync(F,f).catch((K)=>{throw k.addIssue(t(F,K)),k}),$=await Reflect.apply(T,this,A);return await M._def.returns._def.type.parseAsync($,f).catch((K)=>{throw k.addIssue(S($,K)),k})})}else{const M=this;return nn(function(...F){const k=M._def.args.safeParse(F,f);if(!k.success)throw new yn([t(F,k.error)]);const A=Reflect.apply(T,this,k.data),$=M._def.returns.safeParse(A,f);if(!$.success)throw new yn([S(A,$.error)]);return $.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...o){return new xt({...this._def,args:Nn.create(o).rest(Tt.create())})}returns(o){return new xt({...this._def,returns:o})}implement(o){return this.parse(o)}strictImplement(o){return this.parse(o)}static create(o,n,t){return new xt({args:o?o:Nn.create([]).rest(Tt.create()),returns:n||Tt.create(),typeName:d.ZodFunction,...oo(t)})}}class gt extends to{get schema(){return this._def.getter()}_parse(o){const{ctx:n}=this._processInputParams(o);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}gt.create=(o,n)=>{return new gt({getter:o,typeName:d.ZodLazy,...oo(n)})};class lt extends to{_parse(o){if(o.data!==this._def.value){const n=this._getOrReturnCtx(o);return b(n,{received:n.data,code:Q.invalid_literal,expected:this._def.value}),a}return{status:"valid",value:o.data}}get value(){return this._def.value}}lt.create=(o,n)=>{return new lt({value:o,typeName:d.ZodLiteral,...oo(n)})};class kt extends to{constructor(){super(...arguments);CS.set(this,void 0)}_parse(o){if(typeof o.data!=="string"){const n=this._getOrReturnCtx(o),t=this._def.values;return b(n,{expected:Ao.joinValues(t),received:n.parsedType,code:Q.invalid_type}),a}if(!Pf(this,CS,"f"))TJ(this,CS,new Set(this._def.values),"f");if(!Pf(this,CS,"f").has(o.data)){const n=this._getOrReturnCtx(o),t=this._def.values;return b(n,{received:n.data,code:Q.invalid_enum_value,options:t}),a}return nn(o.data)}get options(){return this._def.values}get enum(){const o={};for(let n of this._def.values)o[n]=n;return o}get Values(){const o={};for(let n of this._def.values)o[n]=n;return o}get Enum(){const o={};for(let n of this._def.values)o[n]=n;return o}extract(o,n=this._def){return kt.create(o,{...this._def,...n})}exclude(o,n=this._def){return kt.create(this.options.filter((t)=>!o.includes(t)),{...this._def,...n})}}CS=new WeakMap;kt.create=AJ;class et extends to{constructor(){super(...arguments);LS.set(this,void 0)}_parse(o){const n=Ao.getValidEnumValues(this._def.values),t=this._getOrReturnCtx(o);if(t.parsedType!==x.string&&t.parsedType!==x.number){const S=Ao.objectValues(n);return b(t,{expected:Ao.joinValues(S),received:t.parsedType,code:Q.invalid_type}),a}if(!Pf(this,LS,"f"))TJ(this,LS,new Set(Ao.getValidEnumValues(this._def.values)),"f");if(!Pf(this,LS,"f").has(o.data)){const S=Ao.objectValues(n);return b(t,{received:t.data,code:Q.invalid_enum_value,options:S}),a}return nn(o.data)}get enum(){return this._def.values}}LS=new WeakMap;et.create=(o,n)=>{return new et({values:o,typeName:d.ZodNativeEnum,...oo(n)})};class Xt extends to{unwrap(){return this._def.type}_parse(o){const{ctx:n}=this._processInputParams(o);if(n.parsedType!==x.promise&&n.common.async===!1)return b(n,{code:Q.invalid_type,expected:x.promise,received:n.parsedType}),a;const t=n.parsedType===x.promise?n.data:Promise.resolve(n.data);return nn(t.then((S)=>{return this._def.type.parseAsync(S,{path:n.path,errorMap:n.common.contextualErrorMap})}))}}Xt.create=(o,n)=>{return new Xt({type:o,typeName:d.ZodPromise,...oo(n)})};class Kn extends to{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===d.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(o){const{status:n,ctx:t}=this._processInputParams(o),S=this._def.effect||null,f={addIssue:(T)=>{if(b(t,T),T.fatal)n.abort();else n.dirty()},get path(){return t.path}};if(f.addIssue=f.addIssue.bind(f),S.type==="preprocess"){const T=S.transform(t.data,f);if(t.common.async)return Promise.resolve(T).then(async(M)=>{if(n.value==="aborted")return a;const F=await this._def.schema._parseAsync({data:M,path:t.path,parent:t});if(F.status==="aborted")return a;if(F.status==="dirty")return ht(F.value);if(n.value==="dirty")return ht(F.value);return F});else{if(n.value==="aborted")return a;const M=this._def.schema._parseSync({data:T,path:t.path,parent:t});if(M.status==="aborted")return a;if(M.status==="dirty")return ht(M.value);if(n.value==="dirty")return ht(M.value);return M}}if(S.type==="refinement"){const T=(M)=>{const F=S.refinement(M,f);if(t.common.async)return Promise.resolve(F);if(F instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return M};if(t.common.async===!1){const M=this._def.schema._parseSync({data:t.data,path:t.path,parent:t});if(M.status==="aborted")return a;if(M.status==="dirty")n.dirty();return T(M.value),{status:n.value,value:M.value}}else return this._def.schema._parseAsync({data:t.data,path:t.path,parent:t}).then((M)=>{if(M.status==="aborted")return a;if(M.status==="dirty")n.dirty();return T(M.value).then(()=>{return{status:n.value,value:M.value}})})}if(S.type==="transform")if(t.common.async===!1){const T=this._def.schema._parseSync({data:t.data,path:t.path,parent:t});if(!IS(T))return T;const M=S.transform(T.value,f);if(M instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:M}}else return this._def.schema._parseAsync({data:t.data,path:t.path,parent:t}).then((T)=>{if(!IS(T))return T;return Promise.resolve(S.transform(T.value,f)).then((M)=>({status:n.value,value:M}))});Ao.assertNever(S)}}Kn.create=(o,n,t)=>{return new Kn({schema:o,typeName:d.ZodEffects,effect:n,...oo(t)})};Kn.createWithPreprocess=(o,n,t)=>{return new Kn({schema:n,effect:{type:"preprocess",transform:o},typeName:d.ZodEffects,...oo(t)})};class Vn extends to{_parse(o){if(this._getType(o)===x.undefined)return nn(void 0);return this._def.innerType._parse(o)}unwrap(){return this._def.innerType}}Vn.create=(o,n)=>{return new Vn({innerType:o,typeName:d.ZodOptional,...oo(n)})};class Pn extends to{_parse(o){if(this._getType(o)===x.null)return nn(null);return this._def.innerType._parse(o)}unwrap(){return this._def.innerType}}Pn.create=(o,n)=>{return new Pn({innerType:o,typeName:d.ZodNullable,...oo(n)})};class dt extends to{_parse(o){const{ctx:n}=this._processInputParams(o);let t=n.data;if(n.parsedType===x.undefined)t=this._def.defaultValue();return this._def.innerType._parse({data:t,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}dt.create=(o,n)=>{return new dt({innerType:o,typeName:d.ZodDefault,defaultValue:typeof n.default==="function"?n.default:()=>n.default,...oo(n)})};class ut extends to{_parse(o){const{ctx:n}=this._processInputParams(o),t={...n,common:{...n.common,issues:[]}},S=this._def.innerType._parse({data:t.data,path:t.path,parent:{...t}});if(jS(S))return S.then((f)=>{return{status:"valid",value:f.status==="valid"?f.value:this._def.catchValue({get error(){return new yn(t.common.issues)},input:t.data})}});else return{status:"valid",value:S.status==="valid"?S.value:this._def.catchValue({get error(){return new yn(t.common.issues)},input:t.data})}}removeCatch(){return this._def.innerType}}ut.create=(o,n)=>{return new ut({innerType:o,typeName:d.ZodCatch,catchValue:typeof n.catch==="function"?n.catch:()=>n.catch,...oo(n)})};class hS extends to{_parse(o){if(this._getType(o)!==x.nan){const t=this._getOrReturnCtx(o);return b(t,{code:Q.invalid_type,expected:x.nan,received:t.parsedType}),a}return{status:"valid",value:o.data}}}hS.create=(o)=>{return new hS({typeName:d.ZodNaN,...oo(o)})};var PR=Symbol("zod_brand");class lf extends to{_parse(o){const{ctx:n}=this._processInputParams(o),t=n.data;return this._def.type._parse({data:t,path:n.path,parent:n})}unwrap(){return this._def.type}}class xS extends to{_parse(o){const{status:n,ctx:t}=this._processInputParams(o);if(t.common.async)return(async()=>{const f=await this._def.in._parseAsync({data:t.data,path:t.path,parent:t});if(f.status==="aborted")return a;if(f.status==="dirty")return n.dirty(),ht(f.value);else return this._def.out._parseAsync({data:f.value,path:t.path,parent:t})})();else{const S=this._def.in._parseSync({data:t.data,path:t.path,parent:t});if(S.status==="aborted")return a;if(S.status==="dirty")return n.dirty(),{status:"dirty",value:S.value};else return this._def.out._parseSync({data:S.value,path:t.path,parent:t})}}static create(o,n){return new xS({in:o,out:n,typeName:d.ZodPipeline})}}class at extends to{_parse(o){const n=this._def.innerType._parse(o),t=(S)=>{if(IS(S))S.value=Object.freeze(S.value);return S};return jS(n)?n.then((S)=>t(S)):t(n)}unwrap(){return this._def.innerType}}at.create=(o,n)=>{return new at({innerType:o,typeName:d.ZodReadonly,...oo(n)})};var gR={object:Qo.lazycreate},d;(function(o){o.ZodString="ZodString",o.ZodNumber="ZodNumber",o.ZodNaN="ZodNaN",o.ZodBigInt="ZodBigInt",o.ZodBoolean="ZodBoolean",o.ZodDate="ZodDate",o.ZodSymbol="ZodSymbol",o.ZodUndefined="ZodUndefined",o.ZodNull="ZodNull",o.ZodAny="ZodAny",o.ZodUnknown="ZodUnknown",o.ZodNever="ZodNever",o.ZodVoid="ZodVoid",o.ZodArray="ZodArray",o.ZodObject="ZodObject",o.ZodUnion="ZodUnion",o.ZodDiscriminatedUnion="ZodDiscriminatedUnion",o.ZodIntersection="ZodIntersection",o.ZodTuple="ZodTuple",o.ZodRecord="ZodRecord",o.ZodMap="ZodMap",o.ZodSet="ZodSet",o.ZodFunction="ZodFunction",o.ZodLazy="ZodLazy",o.ZodLiteral="ZodLiteral",o.ZodEnum="ZodEnum",o.ZodEffects="ZodEffects",o.ZodNativeEnum="ZodNativeEnum",o.ZodOptional="ZodOptional",o.ZodNullable="ZodNullable",o.ZodDefault="ZodDefault",o.ZodCatch="ZodCatch",o.ZodPromise="ZodPromise",o.ZodBranded="ZodBranded",o.ZodPipeline="ZodPipeline",o.ZodReadonly="ZodReadonly"})(d||(d={}));var lR=(o,n={message:`Input not instance of ${o.name}`})=>$J((t)=>t instanceof o,n),JJ=Dn.create,yJ=Mt.create,eR=hS.create,dR=Ft.create,RJ=vt.create,uR=_t.create,aR=BS.create,sR=qt.create,o0=pt.create,n0=wt.create,t0=Tt.create,S0=bn.create,f0=cS.create,T0=Un.create,iS=Qo.create,M0=Qo.strictCreate,F0=Zt.create,k0=gf.create,A0=Pt.create,$0=Nn.create,J0=bS.create,y0=NS.create,R0=Kt.create,O0=xt.create,W0=gt.create,_0=lt.create,w0=kt.create,K0=et.create,X0=Xt.create,SJ=Kn.create,Y0=Vn.create,E0=Pn.create,G0=Kn.createWithPreprocess,z0=xS.create,H0=()=>JJ().optional(),m0=()=>yJ().optional(),Q0=()=>RJ().optional(),D0={string:(o)=>Dn.create({...o,coerce:!0}),number:(o)=>Mt.create({...o,coerce:!0}),boolean:(o)=>vt.create({...o,coerce:!0}),bigint:(o)=>Ft.create({...o,coerce:!0}),date:(o)=>_t.create({...o,coerce:!0})},U0=a,ro=Object.freeze({__proto__:null,defaultErrorMap:it,setErrorMap:VR,getErrorMap:pf,makeIssue:Zf,EMPTY_PATH:rR,addIssueToContext:b,ParseStatus:lo,INVALID:a,DIRTY:ht,OK:nn,isAborted:LM,isDirty:IM,isValid:IS,isAsync:jS,get util(){return Ao},get objectUtil(){return CM},ZodParsedType:x,getParsedType:ft,ZodType:to,datetimeRegex:kJ,ZodString:Dn,ZodNumber:Mt,ZodBigInt:Ft,ZodBoolean:vt,ZodDate:_t,ZodSymbol:BS,ZodUndefined:qt,ZodNull:pt,ZodAny:wt,ZodUnknown:Tt,ZodNever:bn,ZodVoid:cS,ZodArray:Un,ZodObject:Qo,ZodUnion:Zt,ZodDiscriminatedUnion:gf,ZodIntersection:Pt,ZodTuple:Nn,ZodRecord:bS,ZodMap:NS,ZodSet:Kt,ZodFunction:xt,ZodLazy:gt,ZodLiteral:lt,ZodEnum:kt,ZodNativeEnum:et,ZodPromise:Xt,ZodEffects:Kn,ZodTransformer:Kn,ZodOptional:Vn,ZodNullable:Pn,ZodDefault:dt,ZodCatch:ut,ZodNaN:hS,BRAND:PR,ZodBranded:lf,ZodPipeline:xS,ZodReadonly:at,custom:$J,Schema:to,ZodSchema:to,late:gR,get ZodFirstPartyTypeKind(){return d},coerce:D0,any:n0,array:T0,bigint:dR,boolean:RJ,date:uR,discriminatedUnion:k0,effect:SJ,enum:w0,function:O0,instanceof:lR,intersection:A0,lazy:W0,literal:_0,map:y0,nan:eR,nativeEnum:K0,never:S0,null:o0,nullable:E0,number:yJ,object:iS,oboolean:Q0,onumber:m0,optional:Y0,ostring:H0,pipeline:z0,preprocess:G0,promise:X0,record:J0,set:R0,strictObject:M0,string:JJ,symbol:aR,transformer:SJ,tuple:$0,undefined:sR,union:F0,unknown:t0,void:f0,NEVER:U0,ZodIssueCode:Q,quotelessJson:UR,ZodError:yn});function OJ(o){const n=o.runtimeEnvStrict??o.runtimeEnv??process.env;if(o.emptyStringAsUndefined??!1){for(let[w,z]of Object.entries(n))if(z==="")delete n[w]}if(!!o.skipValidation)return n;const f=typeof o.client==="object"?o.client:{},T=typeof o.server==="object"?o.server:{},M=typeof o.shared==="object"?o.shared:{},F=iS(f),k=iS(T),A=iS(M),$=o.isServer??(typeof window==="undefined"||("Deno"in window)),O=F.merge(A),K=k.merge(A).merge(F),G=$?K.safeParse(n):O.safeParse(n),I=o.onValidationError??((w)=>{throw console.error("\u274C Invalid environment variables:",w.flatten().fieldErrors),new Error("Invalid environment variables")}),H=o.onInvalidAccess??((w)=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(G.success===!1)return I(G.error);const V=(w)=>{if(!o.clientPrefix)return!0;return!w.startsWith(o.clientPrefix)&&!(w in A.shape)},m=(w)=>{return $||!V(w)},j=(w)=>{return w==="__esModule"||w==="$$typeof"},r=(o.extends??[]).reduce((w,z)=>{return Object.assign(w,z)},{}),i=Object.assign(G.data,r);return new Proxy(i,{get(w,z){if(typeof z!=="string")return;if(j(z))return;if(!m(z))return H(z);return Reflect.get(w,z)}})}var gn=OJ({isServer:typeof window==="undefined",server:{POSTGRES_USER:ro.string(),POSTGRES_PASSWORD:ro.string(),POSTGRES_DATABASE:ro.string(),POSTGRES_HOST:ro.string(),POSTGRES_PORT:ro.string().transform((o)=>Number.parseInt(o,10)),BACKEND_PORT:ro.string().transform((o)=>Number.parseInt(o,10)),RUN_WORKERS_FROM_SOURCE:ro.union([ro.literal("true"),ro.literal("false")]).optional().transform((o)=>o==="true"),FRONTEND_PORT:ro.string().transform((o)=>Number.parseInt(o,10)),FRONTEND_ORIGINS:ro.string().transform((o)=>JSON.parse(o)).pipe(ro.array(ro.string())),OPENAI_API_KEY:ro.string().optional()},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:ro.string()},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var cM={};Ky(cM,{users:()=>Yt,userChanges:()=>r0,untrackedUserColumnNames:()=>V0,twoFactorMethod:()=>KJ,trackedUserColumnName:()=>wJ,trackableUserColumnNames:()=>_J,role:()=>WJ,players:()=>BM,passwordResetAttempts:()=>L0,loginHistory:()=>C0,games:()=>ef,banishedIps:()=>vS});var WJ=$f("role",["admin","user"]),Yt=nt("users",{id:$n().primaryKey().defaultRandom(),username:io({length:16}).notNull(),email:io({length:254}).notNull(),hash:io({length:64}).notNull(),salt:io({length:36}).notNull(),createdAt:mn({withTimezone:!0}).notNull().defaultNow(),createdIp:io({length:45}).notNull(),isActive:XS().notNull().default(!1),verifiedAt:mn({withTimezone:!0}),userRole:WJ().default("user")},(o)=>({usersUsernameUnique:mM().on(o.username),usersEmailUnique:mM().on(o.email)})),V0=["id","createdAt","createdIp","isActive","salt","verifiedAt"],_J=["username","email","hash","userRole"],wJ=$f("trackedUserColumnName",_J),r0=nt("userChanges",{id:$n().primaryKey().defaultRandom(),userId:$n().notNull().references(()=>Yt.id),changedAt:mn({withTimezone:!0}).notNull().defaultNow(),changedIp:io({length:45}).notNull(),changedColumn:wJ().notNull(),oldValue:io({length:255}),newValue:io({length:255})}),ef=nt("games",{id:$n("id").primaryKey().defaultRandom()}),BM=nt("players",{userId:$n().notNull().references(()=>Yt.id),gameId:$n().notNull().references(()=>ef.id),score:Kf().notNull()},(o)=>({pk:E$({columns:[o.userId,o.gameId]})})),C0=nt("loginHistory",{id:$n().primaryKey().defaultRandom(),userId:$n().references(()=>Yt.id),loginTime:mn({withTimezone:!0}).notNull().defaultNow(),ipAddress:io({length:45}).notNull(),userAgent:io({length:1024}),successful:XS().notNull().default(!1)}),KJ=$f("twoFactorMethod",["email","phone"]),L0=nt("passwordResetAttempts",{id:$n().primaryKey().defaultRandom(),userId:$n().notNull().references(()=>Yt.id),requestedIp:io({length:45}).notNull(),requestedAt:mn({withTimezone:!0}).notNull().defaultNow(),succeededIp:io({length:45}),succeededAt:mn({withTimezone:!0}),verificationMethod:KJ().notNull()}),vS=nt("banishedIps",{ip:io({length:45}).primaryKey(),reason:io({length:2048}).notNull(),banishedAt:mn({withTimezone:!0}).notNull().defaultNow(),banishedUntil:mn({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class bM{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(I0.resolve(__dirname,"notify_update.sql"));const o=[Wn(Yt),Wn(ef),Wn(BM)];await this.sql`SELECT create_notify_triggers(${this.sql.array(o)})`,await this.sql.listen("table_update",(n)=>{const t=n.split(","),S=t[0],f=t[1],T=`${S}("${f}")`;if(this.observers.has(T))this.observers.get(T).next(T)})}constructor(o={host:gn.POSTGRES_HOST,port:gn.POSTGRES_PORT,user:gn.POSTGRES_USER,password:gn.POSTGRES_PASSWORD,database:gn.POSTGRES_DATABASE}){this.options=o,this.sql=Bt(o),this.drizzle=qf(this.sql,{schema:cM})}observe(o,n){if(!this.observers.has(o))this.observers.set(o,new s);this.observers.get(o).subscribe("SINGLETON",n)}}var df={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"},NM=uM(df).map(([o])=>ro.literal(Number(o))),j0=ro.union([NM[0],NM[1],...NM]),XJ=ro.tuple([j0,ro.string()]);function xM(){Cn.logger.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}var Cn=new UT;Cn.logger.info(" ready");var hM=EJ(import.meta.dir,"..","app"),N0=new bM;b0({port:gn.FRONTEND_PORT??3333,async fetch(o,n){try{const t=new Date,S=new URL(o.url),f=n.requestIP(o)?.address??"??";Cn.logger.info(t,f,o.method,S.pathname);const[T]=await N0.drizzle.select({banishedUntil:vS.banishedUntil}).from(vS).where(Ct(vS.ip,f)).limit(1),M=T?.banishedUntil===null,F=T?.banishedUntil&&T.banishedUntil>t;if(M||F)throw Cn.logger.info(`\uD83D\uDE45 request from banned ip ${f}`),[403,f];if(S.pathname==="/")return new Response(Bun.file(EJ(hM,"index.html")));if(S.pathname==="/index.html")return Response.redirect("/");const k=B0(hM,S.pathname),A=c0(k);if(!A.startsWith(hM))throw[403,"Access Denied"];if(!await YJ(A).exists())return Response.redirect("/");return new Response(YJ(A))}catch(t){const S=XJ.safeParse(t);if(S.success){const[f,T]=S.data,F=`${df[f]}. ${T}`;return Cn.logger.info(`\u274C ${f}: ${F}`),new Response(F,{status:f})}if(t instanceof Error)Cn.logger.error(t.message);else{const f=Ut(t);Cn.logger.error("frontend server threw",f)}return new Response(df[500],{status:500})}}});process.on("SIGINT",()=>{Cn.logger.info("\u2757 received SIGINT; exiting gracefully"),xM()});process.on("SIGTERM",()=>{Cn.logger.info("\u2757 received SIGTERM; exiting gracefully"),xM()});process.on("exit",()=>{Cn.logger.info("\u2757 received exit; exiting gracefully"),xM()});Cn.logger.info(`\uD83D\uDEEB frontend server running at http://localhost:${gn.FRONTEND_PORT??3333}/`);
|