tempest.games 0.1.19 → 0.1.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/app/assets/index-DDZoOz6S.js +55 -0
- package/app/index.html +1 -1
- package/bin/backend.bun.js +32 -15
- package/bin/backend.worker.game.bun.js +7 -1
- package/bin/backend.worker.tribunal.bun.js +52 -13
- package/bin/frontend.bun.js +13 -6
- package/bin/setup-db.bun.js +409 -233
- package/package.json +26 -26
- package/app/assets/index-BAiC1k6g.js +0 -46
package/bin/frontend.bun.js
CHANGED
|
@@ -1,16 +1,23 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var QJ=Object.create;var{getPrototypeOf:DJ,defineProperty:nf,getOwnPropertyNames:UJ}=Object;var VJ=Object.prototype.hasOwnProperty;var oW=(o,n,t)=>{t=o!=null?QJ(DJ(o)):{};let T=n||!o||!o.__esModule?nf(t,"default",{value:o,enumerable:!0}):t;for(let S of UJ(o))if(!VJ.call(T,S))nf(T,S,{get:()=>o[S],enumerable:!0});return T};var nW=(o,n)=>()=>(n||o((n={exports:{}}).exports,n),n.exports);var rJ=(o,n)=>{for(var t in n)nf(o,t,{get:n[t],enumerable:!0,configurable:!0,set:(T)=>n[t]=()=>T})};import{join as d0,normalize as u0,resolve as L$}from"path";function zt(o=Math.random){return o().toString(36).slice(2)}class TT extends Promise{fate;resolve;reject;done=!1;constructor(o){let n,t;super((T,S)=>{n=T,t=S});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){let 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 oA(o){return Object.entries(o)}var nA=(o,n,t=yo.STORE)=>{return zn(t,{key:`${o.key}:JSON`,get:({get:T})=>n.toJson(T(o)),set:({set:T},S)=>{T(o,n.fromJson(S))}})};function D(o){while(o.child!==null)o=o.child;return o}function tA(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){let n=this.subscribers.values();for(let t of n)t(o)}}class tf extends s{state;constructor(o){super();this.state=o}next(o){this.state=o,super.next(o)}}function jn(o,n,t){let T={key:n.key,type:"atom_family"},S=o.families.get(n.key);if(S)o.logger.error("\u2757","atom_family",n.key,`Overwriting an existing ${Hn(S)} "${S.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let f=new s,A=Object.assign((M)=>{let F=l(M),k={key:n.key,subKey:F},W=`${n.key}(${F})`,O=D(o),E=n.default,Q={key:W,default:E instanceof Function?E(M):E};if(n.effects)Q.effects=n.effects(M);let z=Tn(O,Q,k);return f.next({type:"state_creation",token:z}),z},T,{subject:f,install:(M)=>jn(M,n),internalRoles:t});return o.families.set(n.key,A),o.defaults.set(n.key,n.default),T}function TA(o,n){if("mutable"in n)return ST(o,n);return jn(o,n)}function xn(o,n,t){let T={key:n.key,type:"readonly_selector_family"},S=o.families.get(n.key);if(S)o.logger.error("\u2757","readonly_selector_family",n.key,`Overwriting an existing ${Hn(S)} "${S.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let f=new s,A=Object.assign((M)=>{let F=l(M),k={key:n.key,subKey:F},W=`${n.key}(${F})`,O=D(o),E=fT(O,{key:W,get:n.get(M)},k);return f.next({type:"state_creation",token:E}),E},T,{internalRoles:t,subject:f,install:(M)=>xn(M,n),default:(M)=>{return n.get(M)({get:(...k)=>Mo(o,...k),find:(k,W)=>ko(o,k,W),seek:(k,W)=>Go(o,k,W),json:(k)=>ro(o,k)})}});return o.families.set(n.key,A),T}function yT(o,n){if("set"in n)return AT(o,n);return xn(o,n)}var BJ={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function Ht(o,n){let t=l(n),T=`${o.key}(${t})`,S=BJ[o.type],f={key:T,type:S};if(S==="molecule")Object.assign(f,{key:n,family:o});else Object.assign(f,{family:{key:o.key,subKey:t}});return Object.assign(f,{counterfeit:!0}),f}function Po(o){let n={key:o.key,type:o.type};if("family"in o)n.family=o.family;return n}var LW=Symbol("provenance");function Tf(o,n,t){let T=l(t);try{let S=[],f;if(n==="root")S.push(o.molecules.get('"root"')),f="all";else if(typeof n==="string"&&n.startsWith(CJ)){f="any";let k=l(n),W=o.molecules.get(k);if(!W)throw new Error(`Molecule ${k} not found in store "${o.config.name}"`);S.push(W)}else if(t.startsWith("T$--")){f="all";for(let W of n){let O=l(W),E=o.molecules.get(O);if(!E)throw new Error(`Molecule ${O} not found in store "${o.config.name}"`);S.push(E)}}else{f="any";let W=l(n),O=o.molecules.get(W);if(!O)throw new Error(`Molecule ${W} not found in store "${o.config.name}"`);S.push(O)}let y=new mt(S,t);y._dependsOn=f,o.molecules.set(T,y);for(let k of S)k.below.set(y.stringKey,y);let A={type:"molecule_creation",subType:"modern",key:y.key,provenance:n},M=D(o);if(Fo(M)&&M.transactionMeta.phase==="building")M.transactionMeta.update.updates.push(A);else M.on.moleculeCreationStart.next(A)}catch(S){if(S instanceof Error)o.logger.error("\u274C","molecule",T,"allocation failed:",S.message)}return t}function MT(o,n){let t=l(n),T=o.molecules.get(t);if(!T)throw new Error(`Molecule ${t} not found in store "${o.config.name}"`);for(let F of T.joins.values())F.relations.delete(T.key),F.molecules.delete(T.stringKey);let S;if(T.above.size===1)S=T.above.values().next().value.key;else S=[...T.above.values()].map(({key:F})=>F);let f=[];for(let F of T.tokens.values()){let k=F.family;f.push([k.key,o.valueMap.get(F.key)])}for(let F of T.tokens.values())ao(o,F);for(let F of T.below.values())if(F.dependsOn==="all")MT(o,F.key);else if(F.above.delete(T.stringKey),F.above.size===0)MT(o,F.key);T.below.clear();let y={type:"molecule_disposal",subType:"modern",key:T.key,values:f,provenance:S},A=D(o);if(Fo(A)&&A.transactionMeta.phase==="building")A.transactionMeta.update.updates.push(y);else A.on.moleculeDisposal.next(y);A.molecules.delete(T.stringKey);for(let F of T.above.values())F.below.delete(T.stringKey)}var CJ="T$";function Qt(o){return SA(yo.STORE,o)}function Ft(o){return TA(yo.STORE,o)}function Sf(...o){if(o.length===2)return Mo(yo.STORE,...o);return Mo(yo.STORE,...o)}var ff=(o)=>(n,t,T,S,...f)=>{console[o](`${n} ${t} "${T}" ${S}`,...f)},LJ={error:ff("error"),info:ff("info"),warn:ff("warn")};class yf{o;n;t;constructor(o,n,t=LJ){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 PT(o){return yT(yo.STORE,o)}function FT(o){return Af(o,yo.STORE)}class Fn{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(o,n)=>`${o}:${n}`;warn;getRelatedKeys(o){return this.relations.get(o)}addRelation(o,n){let t=this.relations.get(o),T=this.relations.get(n);if(t)t.add(n);else t=new Set([n]),this.relations.set(o,t);if(T)T.add(o);else T=new Set([o]),this.relations.set(n,T)}deleteRelation(o,n){let t=this.relations.get(o);if(t){if(t.delete(n),t.size===0)this.relations.delete(o);let T=this.relations.get(n);if(T){if(T.delete(o),T.size===0)this.relations.delete(n)}}}replaceRelationsUnsafely(o,n){this.relations.set(o,new Set(n));for(let t of n){let T=new Set().add(o);this.relations.set(t,T)}}replaceRelationsSafely(o,n){let t=this.relations.get(o),T=this.isAType?.(o)?o:void 0,S=T===void 0?o:void 0;if(t)for(let f of t){T??=f,S??=f;let y=this.relations.get(f);if(y){if(y.size===1)this.relations.delete(f);else y.delete(o);this.contents.delete(this.makeContentKey(T,S))}}this.relations.set(o,new Set(n));for(let f of n){let y=this.relations.get(f);if(y)y.add(o);else y=new Set().add(o),this.relations.set(f,y)}}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,T])=>[t,new Set(T)])),this.contents=new Map(o.contents);if(this.isAType=n?.isAType??null,this.isBType=n?.isBType??null,this.isContent=n?.isContent??null,n?.makeContentKey)this.makeContentKey=n.makeContentKey;if(n?.externalStore){let t=n.externalStore;if(this.has=(T,S)=>t.has(T,S),this.addRelation=(T,S)=>{t.addRelation(T,S)},this.deleteRelation=(T,S)=>{t.deleteRelation(T,S)},this.replaceRelationsSafely=(T,S)=>{t.replaceRelationsSafely(T,S)},this.replaceRelationsUnsafely=(T,S)=>{t.replaceRelationsUnsafely(T,S)},this.getRelatedKeys=(T)=>t.getRelatedKeys(T),t.getContent)this.getContentInternal=(T)=>{return t.getContent(T)},this.setContent=(T,S)=>{t.setContent(T,S)},this.deleteContent=(T)=>{t.deleteContent(T)};for(let[T,S]of o.relations??[]){let f=this.isAType?.(T)?T:void 0,y=f===void 0?T:void 0;for(let A of S)f??=A,y??=A,this.addRelation(f,y)}for(let[T,S]of o.contents??[])this.setContent(T,S)}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){let t=typeof n[0]==="string"?n[0]:o[this.b],T=n[1]??typeof n[0]==="string"?void 0:n[0];switch(o=typeof o==="string"?o:o[this.a],this.cardinality){case"1:1":{let S=this.getRelatedKey(o);if(S&&S!==t)this.delete(o,S)}case"1:n":{let S=this.getRelatedKey(t);if(S&&S!==o)this.delete(S,t)}}if(T){let S=this.makeContentKey(o,t);this.setContent(S,T)}return this.addRelation(o,t),this}delete(o,n){n=typeof n==="string"?n:o[this.b];let t=typeof o==="string"?o:o[this.a];if(t===void 0&&typeof n==="string"){let T=this.getRelatedKeys(n);if(T)for(let S of T)this.delete(S,n)}if(typeof t==="string"&&n===void 0){let T=this.getRelatedKeys(t);if(T)for(let S of T)this.delete(t,S)}if(typeof t==="string"&&typeof n==="string"){this.deleteRelation(t,n);let T=this.makeContentKey(t,n);this.deleteContent(T)}return this}getRelatedKey(o){let 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.`);let t;for(let T of n){t=T;break}return t}}replaceRelations(o,n,t){let T=!Array.isArray(n),S=T?Object.keys(n):n;if(t?.reckless)this.replaceRelationsUnsafely(o,S);else this.replaceRelationsSafely(o,S);if(T)for(let f of S){let y=this.makeContentKey(o,f),A=n[f];this.setContent(y,A)}return this}getContent(o,n){let t=this.makeContentKey(o,n);return this.getContentInternal(t)}getRelationEntries(o){let n=o[this.a],t=o[this.b];if(n!==void 0&&t===void 0){let T=this.getRelatedKeys(n);if(T)return[...T].map((S)=>{return[S,this.getContent(n,S)]})}if(n===void 0&&t!==void 0){let T=this.getRelatedKeys(t);if(T)return[...T].map((S)=>{return[S,this.getContent(S,t)]})}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 yA=(o)=>{let n=D(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};var IJ=(o)=>o[0].toUpperCase()+o.slice(1);function Hn(o){return o.type.split("_").map(IJ).join(" ")}class Sn extends Error{constructor(...o){let n=o[0],t=o.length===2?o[1]:o[2];if(o.length===2)super(`${Hn(n)} ${l(n.key)} not found in store "${t.config.name}".`);else{let T=o[1];super(`${Hn(n)} "${n.key}" member ${l(T)} not found in store "${t.config.name}".`)}}}function dn(o,n,t){return(...T)=>{let S=d(o,t);if(S)return S.run(T,n);throw new Sn(o,t)}}var eT=(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"),AA(o,n);if(o.type==="selector"||o.type==="readonly_selector")return n.logger.info("\uD83E\uDDEE",o.type,o.key,"computing value"),o.get();let 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 MA=(o,n)=>{if(o.operation.open){let 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}"`}`)},FA=(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)},kA=(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)},Dt=(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 $A=(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 Mf=(o,n)=>{let t=D(n),T=t.selectorAtoms.getRelatedKeys(o.key);if(t.logger.info("\uD83E\uDDF9",o.type,o.key,T?`evicting ${T.size} states downstream:`:"no downstream states",T??"to evict"),T){if(t.operation.open)t.logger.info("\uD83E\uDDF9",o.type,o.key,`[ ${[...t.operation.done].join(", ")} ] already done`);for(let S of T){if(kA(t,S))continue;JA(S,t),Dt(t,S)}}};function jJ(o,n){if(WA(n.newValue))return!1;if(o.includes("\uD83D\uDD0D"))return!1;return!0}var RA=(o,n,t)=>{let{key:T}=o,S=D(t);if(!Fo(S)||S.transactionMeta.phase!=="building"){t.logger.error("\uD83D\uDC1E","atom",T,"stowUpdate called outside of a transaction. This is probably a bug.");return}if(!jJ(T,n))return;let y={type:"atom_update",key:T,...n};if(o.family)y.family=o.family;S.transactionMeta.update.updates.push(y),t.logger.info("\uD83D\uDCC1","atom",T,"stowed (",n.oldValue,"->",n.newValue,")")};var OA=(o,n,t)=>{let T=un(o,t),S=T;if(o.type==="mutable_atom"&&Fo(t)){let{parent:y}=t;S=kT(o,y,t)}if(S=eT(n)(S),t.logger.info("\uD83D\uDCDD","atom",o.key,"set to",S),S=Wn(o.key,S,o.subject,t),_A(o.key,t))wA(o.key,t);Dt(t,o.key),Mf(o,t);let f={oldValue:T,newValue:S};if(Bo(t))$A(o,f,t);else if(t.parent){if(t.on.transactionApplying.state===null)RA(o,f,t);else if(o.key.startsWith("*")){let y=o.key.slice(1),A=t.atoms.get(y),M=t.valueMap.get(y);if(A.type==="mutable_atom"&&Fo(t)){let{parent:k}=t;M=kT(A,k,t)}if(M.do(f.newValue)===null)Mf(A,t)}}};var lT=(o,n,t)=>{switch(o.type){case"atom":case"mutable_atom":OA(o,n,t);break;case"selector":o.set(n);break}};function gT(o,n){if(n.family){let t=o.families.get(n.family.key);if(t)return t}}function Qo(o,...n){let t,T,S,f;if(n.length===2){if(t=n[0],f=n[1],T=gT(o,t)??null,T)S=t.family?bo(t.family.subKey):null,t=ko(o,T,S)}else T=n[0],S=n[1],f=n[2],t=ko(o,T,S);if("counterfeit"in t){let M=o.disposalTraces.buffer.find((F)=>F?.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}".`,M?`This state was previously disposed:\n${M.trace}`:"No previous disposal trace was found.");return}let y=MA(o,t);if(y){let M=o.on.operationClose.subscribe(`waiting to set "${t.key}" at T-${y}`,()=>{M(),o.logger.info("\uD83D\uDFE2",t.type,t.key,`resuming deferred setState from T-${y}`),Qo(o,t,f)});return}let A=d(t,o);lT(A,f,o),FA(o)}function dT(o,n,t){let{key:T,newValue:S,oldValue:f}=n,y=o==="newValue"?S:f,A={key:T,type:"atom"};if(n.family)Object.assign(A,{family:n.family});Qo(t,A,y)}function KA(o,n){let t=new s,T={type:"molecule_family",key:n.key,dependsOn:n.dependsOn??"all"},S={...T,subject:t,new:n.new};return o.moleculeFamilies.set(n.key,S),T}function mn(o,n,t){let T=vn(t,n,o.key);o.tokens.set(T.key,T);let S=Fo(t)&&t.transactionMeta.phase==="building",f=t.moleculeInProgress===o.key;if(!S&&!f)o.subject.next({type:"state_creation",token:T});return T}class No extends Set{mode="record";subject=new s;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(o,n=0){super(o);if(o instanceof No)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){let n=new No(o.members,o.cacheLimit);return n.cache=o.cache,n.cacheIdx=o.cacheIdx,n.cacheUpdateNumber=o.cacheUpdateNumber,n}add(o){let n=super.add(o);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${l(o)}`);return n}clear(){let o=this.mode==="record"?[...this]:null;if(super.clear(),o)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(o)}`)}delete(o){let 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 No(this);let n=this.child._subscribe("transaction",(t)=>{this.transactionUpdates?.push(t)});try{if(o(this.child)){for(let T of this.transactionUpdates)this.doStep(T);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){let n=o.indexOf(":"),t=o.substring(0,n),T=o.substring(n+1);switch(t){case"add":this.add(JSON.parse(T));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(T));break;case"tx":for(let S of T.split(";"))this.doStep(S)}}getUpdateNumber(o){let n=o.indexOf("=");return Number(o.substring(0,n))}do(o){let n=o.indexOf("="),t=Number(o.substring(0,n)),T=t-this.cacheUpdateNumber;if(T>0){if(T===1){this.mode="playback";let f=o.substring(n+1);return this.doStep(f),this.mode="record",this.cacheUpdateNumber=t,null}return this.cacheUpdateNumber+1}if(Math.abs(T)<this.cacheLimit){let f=this.cacheIdx+T;if(this.cache[f]===o)return null;this.mode="playback";let A=!1;while(!A){this.cacheIdx%=this.cacheLimit;let F=this.cache[this.cacheIdx];if(this.cacheIdx--,!F)return"OUT_OF_RANGE";this.undo(F),A=this.cacheIdx===f-1}let M=o.substring(n+1);return this.doStep(M),this.mode="record",this.cacheUpdateNumber=t,null}return"OUT_OF_RANGE"}undoStep(o){let n=o.indexOf(":"),t=o.substring(0,n),T=o.substring(n+1);switch(t){case"add":this.delete(JSON.parse(T));break;case"del":this.add(JSON.parse(T));break;case"clear":{let S=JSON.parse(T);for(let f of S)this.add(f);break}case"tx":{let S=T.split(";");for(let f=S.length-1;f>=0;f--)this.undoStep(S[f])}}}undo(o){let n=o.indexOf("=");if(Number(o.substring(0,n))===this.cacheUpdateNumber){this.mode="playback";let T=o.substring(n+1);return this.undoStep(T),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function Ho(o){return o[0].toUpperCase()+o.slice(1)}class $f{options;defaultContent;toolkit;retrieve;molecules=new Map;relations;states;core;transact(o,n){let t=this.toolkit;this.toolkit=o,n(this),this.toolkit=t}store;alternates;[Symbol.dispose](){this.alternates.delete(this.store.config.name)}in(o){let n=o.config.name,t=this.alternates.get(n);if(t)return t;let T=new $f(this.options,this.defaultContent,o);return this.alternates.set(n,T),T.alternates=this.alternates,T}constructor(o,n,t=yo.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)=>{let U=this.toolkit.seek(Y,K);if(U)return U;let p=this.store.molecules.get(l(K));if(p){let b=d(Y,t);return mn(p,b,t)}if(t.config.lifespan==="immortal")throw new Sn(Y,K,t);return vn(t,Y,K)},this.toolkit={get:(...Y)=>Mo(t,...Y),set:(...Y)=>{Qo(t,...Y)},find:this.retrieve,seek:(...Y)=>Go(t,...Y),json:(Y)=>ro(t,Y),dispose:(...Y)=>{ao(t,...Y)}};let T=o.between[0],S=o.between[1],f=ST(t,{key:`${o.key}/relatedKeys`,default:()=>new No,mutable:!0,fromJson:(Y)=>No.fromJSON(Y),toJson:(Y)=>Y.toJSON()},["join","relations"]);this.core={findRelatedKeysState:f};let y=({get:Y},K)=>Y(this.retrieve(f,K)),A=(Y,K,U)=>{let{set:p}=Y,b=this.retrieve(f,K),w=this.retrieve(f,U);p(b,(v)=>v.add(U)),p(w,(v)=>v.add(K))},M=(Y,K,U)=>{let{set:p}=Y,b=this.retrieve(f,K),w=this.retrieve(f,U),v,j;p(b,(a)=>{if(a.delete(U),a.size===0)v=`"${K}"`;return a}),p(w,(a)=>{if(a.delete(K),a.size===0)j=`"${U}"`;return a})},F=(Y,K,U)=>{let{get:p,set:b}=Y,w=this.retrieve(f,K),v=p(w);for(let j of v){if(U.includes(j))continue;let oo=this.retrieve(f,j);b(oo,(no)=>{return no.delete(K),no})}b(w,(j)=>{return j.transaction((a)=>{a.clear();for(let oo of U){let no=y(Y,oo),_o=no.has(K);if(this.relations.cardinality==="1:n"){let Mn=[];for(let H of no){if(H===K)continue;let i=y(Y,H);if(i.delete(oo),i.size===0)Mn.push(H)}if(!_o&&no.size>0)no.clear();for(let H of Mn){let i=[oo,H].sort(),fo=`"${i[0]}:${i[1]}"`;this.molecules.delete(fo)}}if(!_o)no.add(K);a.add(oo)}return!0}),j})},k=(Y,K,U)=>{let{set:p}=Y,b=this.retrieve(f,K);p(b,(w)=>{return w.transaction((v)=>{for(let j of U)v.add(j);return!0}),w});for(let w of U){let v=this.retrieve(f,w);p(v,(j)=>{return j.add(K),j})}return!0},W=(Y,K,U)=>{let p=y(Y,K);return U?p.has(U):p.size>0},O={getRelatedKeys:(Y)=>y(this.toolkit,Y),addRelation:(Y,K)=>{A(this.toolkit,Y,K)},deleteRelation:(Y,K)=>{M(this.toolkit,Y,K)},replaceRelationsSafely:(Y,K)=>{F(this.toolkit,Y,K)},replaceRelationsUnsafely:(Y,K)=>{k(this.toolkit,Y,K)},has:(Y,K)=>W(this.toolkit,Y,K)},E,Q,z;if(n){Q=jn(t,{key:`${o.key}/content`,default:n},["join","content"]),z=KA(t,{key:`${o.key}/content-molecules`,new:class b{v;constructor(w,v){this.key=v}}});let Y=({get:b},w)=>b(this.retrieve(Q,w)),K=({set:b},w,v)=>{b(this.retrieve(Q,w),v)},U=(b,w)=>{let v=t.molecules.get(`"${w}"`);if(v)this.toolkit.dispose(v),this.molecules.delete(`"${w}"`)};E=Object.assign(O,{getContent:(b)=>{return Y(this.toolkit,b)},setContent:(b,w)=>{K(this.toolkit,b,w)},deleteContent:(b)=>{U(this.toolkit,b)}})}else E=O;let G=new Fn(o,{externalStore:E,isAType:o.isAType,isBType:o.isBType,makeContentKey:(...Y)=>{let K=Y.sort(),U=`${K[0]}:${K[1]}`,[p,b]=K.map((w)=>this.molecules.get(l(w)));if(t.config.lifespan==="immortal"&&p&&b){let w=D(t),v=pn(w,[p,b],z,U);this.molecules.set(`"${U}"`,d(v,w))}return U}}),V=()=>xn(t,{key:`${o.key}/singleRelatedKey`,get:(Y)=>({get:K})=>{let U=this.retrieve(f,Y),p=K(U);for(let b of p)return b;return null}},["join","keys"]),x=()=>{return xn(t,{key:`${o.key}/multipleRelatedKeys`,get:(Y)=>({get:K})=>{let U=kf(f,t),p=this.retrieve(U,Y);return K(p).members}},["join","keys"])},c=()=>xn(t,{key:`${o.key}/singleRelatedEntry`,get:(Y)=>({get:K})=>{let U=this.retrieve(f,Y),p=K(U);for(let b of p){let w=G.isAType?.(Y)?Y:void 0,v=w===void 0?Y:void 0;w??=b,v??=b;let j=G.makeContentKey(w,v),a=this.retrieve(Q,j),oo=K(a);return[b,oo]}return null}},["join","entries"]),P=()=>xn(t,{key:`${o.key}/multipleRelatedEntries`,get:(Y)=>({get:K})=>{let U=kf(f,t),p=this.retrieve(U,Y);return K(p).members.map((w)=>{let v=G.isAType?.(Y)?Y:void 0,j=v===void 0?Y:void 0;v??=w,j??=w;let a=G.makeContentKey(v,j),oo=this.retrieve(Q,a),no=K(oo);return[w,no]})}},["join","entries"]);switch(o.cardinality){case"1:1":{let Y=V(),K=`${T}KeyOf${Ho(S)}`,U=`${S}KeyOf${Ho(T)}`,p={[K]:Y,[U]:Y},b;if(n){let w=c(),v=`${T}EntryOf${Ho(S)}`,j=`${S}EntryOf${Ho(T)}`,a={[v]:w,[j]:w};b=Object.assign(p,a)}else b=p;this.relations=G,this.states=b;break}case"1:n":{let Y=V(),K=x(),U=`${T}KeyOf${Ho(S)}`,p=`${S}KeysOf${Ho(T)}`,b={[U]:Y,[p]:K},w;if(n){let v=c(),j=P(),a=`${T}EntryOf${Ho(S)}`,oo=`${S}EntriesOf${Ho(T)}`,no={[a]:v,[oo]:j};w=Object.assign(b,no)}else w=b;this.relations=G,this.states=w;break}default:{let Y=x(),K=`${T}KeysOf${Ho(S)}`,U=`${S}KeysOf${Ho(T)}`,p={[K]:Y,[U]:Y},b;if(n){let w=P(),v=`${T}EntriesOf${Ho(S)}`,j=`${S}EntriesOf${Ho(T)}`,a={[v]:w,[j]:w};b=Object.assign(p,a)}else b=p;this.relations=G,this.states=b}}}}function uT(o,n,t=yo.STORE){return Ff(t).set(o.key,new $f(o,n,t)),{key:o.key,type:"join",a:o.between[0],b:o.between[1],cardinality:o.cardinality}}function Ff(o){if("joins"in o&&o.joins instanceof Map)return o.joins;let n=new Map;return o.joins=n,n}function $T(o,n){let t=Ff(n),T=t.get(o.key);if(T===void 0){if(T=Ff(yo.STORE).get(o.key)?.in(n),T===void 0)throw new Error(`Join "${o.key}" not found in store "${n.config.name}"`);t.set(o.key,T)}return T}function aT(o,n,t){let T=$T(o,t),S;switch(o.cardinality){case"1:1":{let f=`${o.a}KeyOf${Ho(o.b)}`,y=`${o.b}KeyOf${Ho(o.a)}`;S={get[f](){let M=T.states[f];return T.retrieve(M,n)},get[y](){let M=T.states[y];return T.retrieve(M,n)}};let A=`${o.a}EntryOf${Ho(o.b)}`;if(A in T.states){let M=`${o.b}EntryOf${Ho(o.a)}`;Object.assign(S,{get[A](){let F=T.states[A];return T.retrieve(F,n)},get[M](){let F=T.states[M];return T.retrieve(F,n)}})}break}case"1:n":{let f=`${o.a}KeyOf${Ho(o.b)}`,y=`${o.b}KeysOf${Ho(o.a)}`;S={get[f](){let M=T.states[f];return T.retrieve(M,n)},get[y](){let M=T.states[y];return T.retrieve(M,n)}};let A=`${o.a}EntryOf${Ho(o.b)}`;if(A in T.states){let M=`${o.b}EntriesOf${Ho(o.a)}`;Object.assign(S,{get[A](){let F=T.states[A];return T.retrieve(F,n)},get[M](){let F=T.states[M];return T.retrieve(F,n)}})}break}case"n:n":{let f=`${o.a}KeysOf${Ho(o.b)}`,y=`${o.b}KeysOf${Ho(o.a)}`;S={get[f](){let M=T.states[f];return T.retrieve(M,n)},get[y](){let M=T.states[y];return T.retrieve(M,n)}};let A=`${o.a}EntriesOf${Ho(o.b)}`;if(A in T.states){let M=`${o.b}EntriesOf${Ho(o.a)}`;Object.assign(S,{get[A](){let F=T.states[A];return T.retrieve(F,n)},get[M](){let F=T.states[M];return T.retrieve(F,n)}})}}}return S}function XA(o,n){return aT(o,n,yo.STORE)}function sT(o,n,t){let T=$T(o,t),S=D(t);if(Fo(S)){let{toolkit:f}=S.transactionMeta;T.transact(f,({relations:y})=>{n(y)})}else n(T.relations)}function bJ(o,n){return $T(o,n).core.findRelatedKeysState}function EA(o){return bJ(o,yo.STORE)}function oS(o){return{store:o}}function Mo(o,...n){let t,T,S;if(n.length===1){if(t=n[0],t.type!=="molecule"){if(T=gT(o,t)??null,T)S=t.family?bo(t.family.subKey):null,t=ko(o,T,S)}}else{T=n[0],S=n[1];let f;if(T.type==="molecule_family")f=Go(o,T,S)??Ht(T,S);else f=ko(o,T,S);t=f}if("counterfeit"in t&&"family"in t){T=t.type==="molecule"?d(t.family,o):o.families.get(t.family.key);let f=t.type==="molecule"?t.key:t.family.subKey,y=o.disposalTraces.buffer.find((A)=>A?.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}".`,y?`This state was previously disposed:\n${y.trace}`:"No previous disposal trace was found."),T.type){case"atom_family":case"mutable_atom_family":return o.defaults.get(T.key);case"selector_family":case"readonly_selector_family":{if(o.defaults.has(T.key))return o.defaults.get(t.family.key);let A=d(T,o).default(f);return o.defaults.set(T.key,A),A}case"molecule_family":throw new Sn(T,f,o)}}switch(t.type){case"atom":case"mutable_atom":case"selector":case"readonly_selector":return un(d(t,o),o);case"molecule":return d(t,o).instance}}class mt{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 T of o)this.above.set(T.stringKey,T)}}function YA(o){return o[0].toUpperCase()+o.slice(1)}function pn(o,n,t,T,...S){let f=tA(o),y=D(o),A=l(T);y.moleculeInProgress=A;let M=Array.isArray(n)?n:[n],F=M.map((G)=>{if(G instanceof mt)return G;let V=l(G.key),x=o.molecules.get(V);if(!x)throw new Error(`Molecule ${V} not found in store "${o.config.name}"`);return x}),k=new mt(F,T,t);y.molecules.set(A,k);for(let G of F)G.below.set(k.stringKey,k);let W={get:(...G)=>Mo(D(f),...G),set:(...G)=>{Qo(D(f),...G)},seek:(G,V)=>Go(D(f),G,V),json:(G)=>ro(D(f),G),run:(G,V=zt())=>dn(G,V,D(o)),make:(G,V,x,...c)=>pn(D(f),G,V,x,...c),dispose:(G)=>{ao(D(f),G)},env:()=>oS(D(f)),bond:(G,V)=>{if(G.type==="join"){let{as:x}=V,c=$T(G,f);c.molecules.set(A,k),k.joins.set(G.key,c);let P=O.subject.subscribe(`join:${G.key}-${A}`,(w)=>{if(w.type==="molecule_disposal"){if(l(w.token.key)===A)P(),c.molecules.delete(A)}});if(x===null)return;let Y=G.a===x?G.b:G.a,K=XA(G,T),U=K[`${Y}KeysOf${YA(x)}`],p=K[`${Y}EntriesOf${YA(x)}`],b={relatedKeys:U};if(p)b=Object.assign(b,{relatedEntries:p});return b}return mn(k,d(G,f),D(f))},claim:(G,V)=>{let{exclusive:x}=V,c=D(o).molecules.get(l(G.key));if(c)if(x){for(let P of c.above.values())P.below.delete(c.stringKey);c.above.clear(),c.above.set(k.stringKey,k),k.below.set(c.stringKey,c)}else c.above.set(k.stringKey,k),k.below.set(c.stringKey,c)},spawn:(G,V,...x)=>pn(D(o),[k],d(G,o),V,...x)},O=d(t,o),E=O.new;k.instance=new E(W,T,...S);let Q={type:"molecule",key:T,family:t},z={type:"molecule_creation",subType:"classic",token:Q,family:t,context:M,params:S};if(Bo(y))O.subject.next(z);else if(Fo(y)&&y.on.transactionApplying.state===null)y.transactionMeta.update.updates.push(z);return y.moleculeInProgress=null,Q}function Jf(o,n,t){switch(n){case"newValue":{GA(o,t);break}case"oldValue":{ao(t,o.token);break}}}function Rf(o,n,t){switch(n){case"newValue":{ao(t,o.token);break}case"oldValue":{GA(o,t),t.valueMap.set(o.token.key,o.value);break}}}function GA(o,n){let{family:t}=o.token;if(t){let T=n.families.get(t.key);if(T)ko(n,T,bo(t.subKey))}}function Wf(o,n,t){switch(n){case"newValue":switch(o.subType){case"classic":pn(t,o.context,o.family,o.token.key,...o.params);break;case"modern":Tf(t,o.provenance,o.key);break}break;case"oldValue":switch(o.subType){case"classic":ao(t,o.token);break;case"modern":MT(t,o.key);break}break}}function Of(o,n,t){switch(n){case"newValue":switch(o.subType){case"classic":ao(t,o.token);break;case"modern":MT(t,o.key);break}break;case"oldValue":switch(o.subType){case"classic":{let T=pn(t,o.context,o.family,o.token.key);for(let[S,f]of o.values){let y=`${S}(${l(T.key)})`,A=d(T,t),M=A.tokens.has(y),F=t.families.get(S);if(F&&!M)mn(A,F,t);t.valueMap.set(y,f)}}break;case"modern":{Tf(t,o.provenance,o.key);for(let[T,S]of o.values){let f=t.families.get(T);if(f){ko(t,f,o.key);let y=`${T}(${l(o.key)})`;t.valueMap.set(y,S)}}}}break}}function nS(o,n,t){let T=o==="newValue"?n.updates:[...n.updates].reverse();for(let S of T)switch(S.type){case"atom_update":case"selector_update":dT(o,S,t);break;case"state_creation":Jf(S,o,t);break;case"state_disposal":Rf(S,o,t);break;case"molecule_creation":Wf(S,o,t);break;case"molecule_disposal":Of(S,o,t);break;case"transaction_update":nS(o,S,t);break}}function zA(o,n,t){if(Bo(t)&&o)t.transactionMeta.epoch.set(o,n)}function HA(o,n,t){if(!Bo(t))return;let S=t.transactionMeta.actionContinuities.getRelatedKey(o);if(S!==void 0)t.transactionMeta.epoch.set(S,n)}var mA=(o,n)=>{let t=D(n),{parent:T}=t;if(T===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,T.child=null,T.on.transactionApplying.next(t.transactionMeta);let{updates:S}=t.transactionMeta.update;if(n.logger.info("\uD83D\uDEC4","transaction",t.transactionMeta.update.key,`Applying transaction with ${S.length} updates:`,S),nS("newValue",t.transactionMeta.update,T),Bo(T))HA(t.transactionMeta.update.key,t.transactionMeta.update.epoch,T),d({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(T))T.transactionMeta.update.updates.push(t.transactionMeta.update);T.on.transactionApplying.next(null)};function QA(o,n,t){if(!Bo(t))return;let{epoch:S,actionContinuities:f}=t.transactionMeta;if(f.set(o,n),!S.has(o))S.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 DA=(o,n,t,T)=>{let S=D(t),f={parent:S,child:null,on:S.on,loggers:S.loggers,logger:S.logger,config:S.config,atoms:new On(S.atoms),atomsThatAreDefault:new Set(S.atomsThatAreDefault),families:new On(S.families),operation:{open:!1},readonlySelectors:new On(S.readonlySelectors),timelines:new On(S.timelines),timelineTopics:new Fn(S.timelineTopics.toJSON()),trackers:new Map,transactions:new On(S.transactions),selectorAtoms:new Fn(S.selectorAtoms.toJSON()),selectorGraph:new Fn(S.selectorGraph.toJSON(),{makeContentKey:(...F)=>F.sort().join(":")}),selectors:new On(S.selectors),valueMap:new On(S.valueMap),defaults:S.defaults,disposalTraces:t.disposalTraces.copy(),molecules:new On(S.molecules),moleculeFamilies:new On(S.moleculeFamilies),moleculeInProgress:S.moleculeInProgress,miscResources:new On(S.miscResources)},y=UA(o,t),A={phase:"building",update:{type:"transaction_update",key:o,id:T,epoch:y===void 0?Number.NaN:y+1,updates:[],params:n,output:void 0},toolkit:{get:(...F)=>Mo(M,...F),set:(...F)=>{Qo(M,...F)},run:(F,k=zt())=>dn(F,k,M),find:(F,k)=>ko(M,F,k),seek:(F,k)=>Go(M,F,k),json:(F)=>ro(M,F),make:(F,k,W,...O)=>pn(M,F,k,W,...O),dispose:(...F)=>{ao(M,...F)},env:()=>oS(M)}},M=Object.assign(f,{transactionMeta:A});return S.child=M,t.logger.info("\uD83D\uDEEB","transaction",o,"Building transaction with params:",n),M};function Af(o,n){let t={key:o.key,type:"transaction",run:(f,y)=>{let A=DA(o.key,f,n,y);try{let M=D(n),{toolkit:F}=A.transactionMeta,k=o.do(F,...f);return mA(k,M),k}catch(M){throw yA(T),n.logger.warn("\uD83D\uDCA5","transaction",o.key,"caught:",M),M}},install:(f)=>Af(o,f),subject:new s},T=D(n);T.transactions.set(t.key,t);let S=Po(t);return n.on.transactionCreation.next(S),S}function UA(o,n){let t=Bo(n),T=t?n.transactionMeta.actionContinuities.getRelatedKey(o):void 0;return t&&T!==void 0?n.transactionMeta.epoch.get(T):void 0}class tS{_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(){let o=new tS([...this._buffer]);return o._index=this._index,o}}class VA{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 tS(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 tf(null),operationClose:new s,moleculeCreationStart:new s,moleculeCreationDone:new s,moleculeDisposal:new s};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new yf("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[,T]of n.families){if(T.internalRoles?.includes("mutable")||T.internalRoles?.includes("join"))continue;T.install(this)}let t=new Set;for(let[,T]of n.atoms){if(t.has(T.key))continue;if(T.install(this),T.type==="mutable_atom"){let S=ro(n,T),f=qn(T);t.add(S.key),t.add(f.key)}}for(let[,T]of n.readonlySelectors)T.install(this);for(let[,T]of n.selectors){if(t.has(T.key))continue;T.install(this)}for(let[,T]of n.transactions)T.install(this);for(let[,T]of n.timelines)T.install(this)}}}var yo={get STORE(){if(!globalThis.ATOM_IO_IMPLICIT_STORE)globalThis.ATOM_IO_IMPLICIT_STORE=new VA({name:"IMPLICIT_STORE",lifespan:"ephemeral"});return globalThis.ATOM_IO_IMPLICIT_STORE}};function d(o,n){let t,T=n;while(T!==null){switch(o.type){case"atom":case"mutable_atom":t=T.atoms.get(o.key);break;case"selector":t=T.selectors.get(o.key);break;case"readonly_selector":t=T.readonlySelectors.get(o.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":t=T.families.get(o.key);break;case"timeline":t=T.timelines.get(o.key);break;case"transaction":t=T.transactions.get(o.key);break;case"molecule":t=T.molecules.get(l(o.key));break;case"molecule_family":t=T.moleculeFamilies.get(o.key);break}if(t)return t;T=T.child}throw new Sn(o,n)}function TS(o,n){let t;t=d(o,n);let{family:T}=o;for(let y of t.joins.values())y.relations.delete(t.key),y.molecules.delete(t.stringKey);let S=[];for(let y of t.above.values())S.push(Po(y));let f=[];for(let y of t.tokens.values()){let A=y.family;f.push([A.key,n.valueMap.get(y.key)])}if(T){let y=d(T,n),A={type:"molecule_disposal",subType:"classic",token:o,family:T,context:S,values:f};if(o.family)A.family=o.family;for(let F of t.tokens.values())ao(n,F);for(let F of t.below.values())if(F.dependsOn==="all")TS(F,n);else if(F.above.delete(t.stringKey),F.above.size===0)TS(F,n);if(t.below.clear(),Fo(n)&&n.transactionMeta.phase==="building")n.transactionMeta.update.updates.push(A);else y.subject.next(A);n.molecules.delete(t.stringKey)}for(let y of t.above.values())y.below.delete(t.stringKey)}function vn(o,n,t){let T=o.families.get(n.key);if(T===void 0)throw new Sn(n,o);let S=T(t),f=D(o);if(S.family&&f.moleculeInProgress===null){if(Bo(f))switch(S.type){case"atom":case"mutable_atom":o.on.atomCreation.next(S);break;case"selector":case"readonly_selector":o.on.selectorCreation.next(S);break}else if(Fo(f)&&f.on.transactionApplying.state===null)f.transactionMeta.update.updates.push({type:"state_creation",token:S})}return S}function Go(o,n,t){let T=l(t),S=`${n.key}(${T})`,f=D(o),y;switch(n.type){case"atom_family":case"mutable_atom_family":y=f.atoms.get(S);break;case"selector_family":y=f.selectors.get(S);break;case"readonly_selector_family":y=f.readonlySelectors.get(S);break;case"molecule_family":y=f.molecules.get(l(t))}if(y)return Po(y);return y}function ko(o,n,t){let T=Go(o,n,t);if(T)return T;let S=o.molecules.get(l(t));if(S)return mn(S,n,o);if(o.config.lifespan==="immortal"){let f=Ht(n,t);return o.logger.error("\u274C",f.type,f.key,`was not found in store "${o.config.name}"; returned a counterfeit token.`),f}return T=vn(o,n,t),T}function ao(o,...n){let t,T;if(n.length===1)t=n[0],T=t.key;else{let f=n[0],y=n[1];t=f.type==="molecule_family"?Go(o,f,y)??Ht(f,y):ko(o,f,y)}try{d(t,o)}catch(f){let y=o.disposalTraces.buffer.find((A)=>A?.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}".`,y?`\n This state was most recently disposed\n${y.trace}`:"No previous disposal trace was found.");return}switch(t.type){case"atom":case"mutable_atom":_f(t,o);break;case"selector":case"readonly_selector":rA(t,o);break;case"molecule":TS(t,o);break}let{stack:S}=new Error;if(S){let f=S?.split("\n")?.slice(3)?.join("\n");o.disposalTraces.add({key:t.key,trace:f})}}var SS=(o,n)=>D(n).atoms.has(o),NJ=(o,n)=>D(n).selectors.has(o),hJ=(o,n)=>D(n).readonlySelectors.has(o),BA=(o,n)=>SS(o,n)||NJ(o,n)||hJ(o,n);var fS=(o,n)=>{return D(n).selectorGraph.getRelationEntries({downstreamSelectorKey:o}).filter(([T,{source:S}])=>S!==o).map(([T,{source:S}])=>S).filter((T)=>BA(T,n))};var wf=(o,n,t)=>{let T=[],S=fS(o,t);while(S.length>0){let f=S.shift();if(n.has(f))continue;if(n.add(f),!SS(f,t))S.push(...fS(f,t));else if(!T.includes(f))T.push(f)}return T},CA=(o,n)=>{let t=o.key,T=fS(t,n),S=new Set;return T.flatMap((f)=>SS(f,n)?f:wf(f,S,n))};var LA=(o,n,t,T)=>{let S=D(T);if(n.type==="atom"||n.type==="mutable_atom")S.selectorAtoms.set({selectorKey:o,atomKey:n.key}),T.logger.info("\uD83D\uDD0D","selector",o,`discovers root atom "${n.key}"`);else{let f=wf(n.key,t,T);T.logger.info("\uD83D\uDD0D","selector",o,`discovers root atoms: [ ${f.map((y)=>`"${y}"`).join(", ")} ]`);for(let y of f)S.selectorAtoms=S.selectorAtoms.set({selectorKey:o,atomKey:y})}t.add(n.key)};var yS=(o,n,t)=>({get:(...T)=>{let S=D(t),f;if(T.length===2){let[M,F]=T;switch(M.type){case"molecule_family":return Mo(t,M,F);default:if(t.config.lifespan==="ephemeral")f=ko(t,M,F);else{let k=Go(t,M,F);if(k)f=k;else throw new Sn(M,F,t)}}}else[f]=T;if(f.type==="molecule")return Mo(t,f);let y=d(f,t),A=un(y,t);return t.logger.info("\uD83D\uDD0C","selector",o,`registers dependency ( "${f.key}" =`,A,")"),S.selectorGraph.set({upstreamSelectorKey:f.key,downstreamSelectorKey:o},{source:f.key}),LA(o,f,n,t),A},set:(...T)=>{let S,f;if(T.length===2)S=T[0],f=T[1];else{let M=T[0],F=T[1];f=T[2];let k=t.config.lifespan==="ephemeral"?ko(t,M,F):Go(t,M,F);if(!k)throw new Sn(M,F,t);S=k}let y=D(t),A=d(S,y);lT(A,f,y)},find:(T,S)=>ko(t,T,S),seek:(T,S)=>Go(t,T,S),json:(T)=>ro(t,T)});var fT=(o,n,t)=>{let T=D(o),S=new s,f=new Set,{get:y,find:A,seek:M,json:F}=yS(n.key,f,T),k=()=>{let Q=n.get({get:y,find:A,seek:M,json:F});return Wn(n.key,Q,S,D(o)),f.clear(),Q},W={...n,subject:S,install:(Q)=>fT(Q,n,t),get:k,type:"readonly_selector",...t&&{family:t}};T.readonlySelectors.set(n.key,W);let O=k();o.logger.info("\u2728",W.type,W.key,"=",O);let E={key:n.key,type:"readonly_selector"};if(t)E.family=t;return E};var JT=(o,n,t)=>{let T=D(o),S=new s,f=new Set,y=yS(n.key,f,T),{find:A,get:M,seek:F,json:k}=y,W={find:A,get:M,seek:F,json:k},O=(V=n.get,x=D(o))=>{let c=V(W);return Wn(n.key,c,S,x),f.clear(),c},Q={...n,subject:S,install:(V)=>JT(V,n,t),get:O,set:(V)=>{let x=D(o),c=O(n.get,x),P=eT(V)(c);if(o.logger.info("\uD83D\uDCDD","selector",n.key,"set (",c,"->",P,")"),Wn(n.key,P,S,x),Dt(x,n.key),Bo(x))S.next({newValue:P,oldValue:c});n.set(y,P)},type:"selector",...t&&{family:t}};T.selectors.set(n.key,Q);let z=O();o.logger.info("\u2728",Q.type,Q.key,"=",z);let G={key:n.key,type:"selector"};if(t)G.family=t;return G};function zn(o,n){if("set"in n){let S=JT(o,n,void 0);return o.on.selectorCreation.next(S),S}let T=fT(o,n,void 0);return o.on.selectorCreation.next(T),T}function rA(o,n){let t=D(n),{key:T}=o,S=d(o,t);if(!S.family)n.logger.error("\u274C","selector",T,"Standalone selectors cannot be disposed.");else{let f=t.molecules.get(S.family.subKey);if(f)f.tokens.delete(T);switch(o.type){case"selector":t.selectors.delete(T),d({key:S.family.key,type:"selector_family"},n).subject.next({type:"state_disposal",token:o});break;case"readonly_selector":t.readonlySelectors.delete(T),d({key:S.family.key,type:"readonly_selector_family"},n).subject.next({type:"state_disposal",token:o});break}if(t.valueMap.delete(T),t.selectorAtoms.delete(T),t.selectorGraph.delete(T),n.logger.info("\uD83D\uDD25",o.type,T,"deleted"),Fo(t)&&t.transactionMeta.phase==="building")t.transactionMeta.update.updates.push({type:"state_disposal",token:o});else n.on.selectorDisposal.next(o)}}function AT(o,n,t){let T={key:n.key,type:"selector_family"},S=o.families.get(n.key);if(S)o.logger.error("\u2757","selector_family",n.key,`Overwriting an existing ${Hn(S)} "${S.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let f=new s,A=Object.assign((M)=>{let F=l(M),k={key:n.key,subKey:F},W=`${n.key}(${F})`,O=D(o),E=JT(O,{key:W,get:n.get(M),set:n.set(M)},k);return f.next({type:"state_creation",token:E}),E},T,{internalRoles:t,subject:f,install:(M)=>AT(M,n),default:(M)=>{return n.get(M)({get:(...k)=>Mo(o,...k),find:(k,W)=>ko(o,k,W),seek:(k,W)=>Go(o,k,W),json:(k)=>ro(o,k)})}});return o.families.set(n.key,A),T}function IA(o,n,t=yo.STORE){let T=AT(t,{key:`${o.key}:JSON`,get:(f)=>({seek:y,get:A})=>{let M=y(o,f);if(M)return n.toJson(A(M));let F=l(f),k=t.molecules.get(F);if(k){let O=mn(k,o,t);return n.toJson(A(O))}if(t.config.lifespan==="immortal")throw new Error(`No molecule found for key "${F}"`);let W=vn(t,o,f);return n.toJson(A(W))},set:(f)=>({seek:y,set:A},M)=>{let F=y(o,f);if(F)A(F,n.fromJson(M));else{let k=l(f),W=t.molecules.get(k);if(W){let O=mn(W,o,t);A(O,n.fromJson(M))}else{if(t.config.lifespan==="immortal")throw new Error(`No molecule found for key "${k}"`);A(vn(t,o,f),n.fromJson(M))}}}},["mutable","json"]);return d(o,t).subject.subscribe(`store=${t.config.name}::json-selector-family`,(f)=>{if(f.token.family)Go(t,T,bo(f.token.family.subKey))}),T}var bo=(o)=>JSON.parse(o),l=(o)=>JSON.stringify(o),oK=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var jA=(o,n)=>{let t=D(n);if(t.operation.open)return t.operation.prev.get(o.key);return t.valueMap.get(o.key)};var Ef=(o,n)=>{let t=D(n);return CA(o,n).map((S)=>{let f=t.atoms.get(S);if(f===void 0)throw new Error(`Atom "${S}", a dependency of selector "${o.key}", not found in store "${n.config.name}".`);return f.subject.subscribe(`${o.type}:${o.key}`,(y)=>{n.logger.info("\uD83D\uDCE2",o.type,o.key,"root",S,"went",y.oldValue,"->",y.newValue);let A=jA(o,t),M=un(o,t);n.logger.info("\u2728",o.type,o.key,"went",A,"->",M),o.subject.next({newValue:M,oldValue:A})})})};function eo(o,n,t,T){function S(W){if(T.operation.open){let O=T.on.operationClose.subscribe(`state subscription ${t}`,()=>{O(),n(W)})}else n(W)}let f=d(o,T);T.logger.info("\uD83D\uDC40",f.type,f.key,`Adding subscription "${t}"`);let y=f.type==="selector"||f.type==="readonly_selector",A=null,M=S;if(y)A=Ef(f,T),M=(W)=>{if(A)A.length=0,A.push(...Ef(f,T));S(W)};let F=f.subject.subscribe(t,M);return()=>{if(T.logger.info("\uD83D\uDE48",f.type,f.key,`Removing subscription "${t}"`),F(),A)for(let W of A)W()}}var Kf=(o,n,t,T)=>{let S=d(o,T);T.logger.info("\uD83D\uDC40","timeline",o.key,`Adding subscription "${t}"`);let f=S.subject.subscribe(t,n);return()=>{T.logger.info("\uD83D\uDE48","timeline",o.key,`Removing subscription "${t}" from timeline`),f()}};var Xf=(o,n,t,T)=>{let S=d(o,T);T.logger.info("\uD83D\uDC40","transaction",o.key,`Adding subscription "${t}"`);let f=S.subject.subscribe(t,n);return()=>{T.logger.info("\uD83D\uDE48","transaction",o.key,`Removing subscription "${t}"`),f()}};class an{Update;initializeState(o,n){let t=`*${o.key}`;n.atoms.delete(t),n.valueMap.delete(t);let T=o.family?{key:`*${o.family.key}`,subKey:o.family.subKey}:void 0,S=Tn(n,{key:t,default:null},T);if(n.parent?.valueMap.has(t)){let f=n.parent.valueMap.get(t);n.valueMap.set(t,f)}return S}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(o,n,t){let T=`tracker:${t.config.name}:${Fo(t)?t.transactionMeta.update.key:"main"}:${o.key}`,S=Mo(t,o);this.unsubscribeFromInnerValue=S.subscribe(T,(f)=>{Qo(t,n,f)}),this.unsubscribeFromState=eo(o,(f)=>{if(f.newValue!==f.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=f.newValue.subscribe(T,(y)=>{Qo(t,n,y)})},T,t)}updateCore(o,n,t){let T=`tracker:${t.config.name}:${Fo(t)?t.transactionMeta.update.key:"main"}:${o.key}`;eo(n,({newValue:S,oldValue:f})=>{let y=t.timelineTopics.getRelatedKey(n.key);if(y){if(t.timelines.get(y)?.timeTraveling){let F=Kf({key:y,type:"timeline"},(k)=>{F(),Qo(t,o,(W)=>{if(k==="redo"&&S)W.do(S);else if(k==="undo"&&f)W.undo(f);return W})},T,t);return}}let A=t.on.operationClose.subscribe(T,()=>{A();let M=Mo(t,o),F=S===null?-1:M.getUpdateNumber(S),k=F-M.cacheUpdateNumber;if(S&&k===1)Qo(t,o,(W)=>(W.do(S),W));else t.logger.info("\u274C","mutable_atom",o.key,`could not be updated. Expected update number ${M.cacheUpdateNumber+1}, but got ${F}`)})},T,t)}mutableState;latestUpdateState;dispose;constructor(o,n){this.mutableState=o;let 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 RT(o,n,t){o.logger.info("\uD83D\uDD28","atom",n.key,`creating in store "${o.config.name}"`);let T=D(o),S=T.atoms.get(n.key);if(S&&S.type==="mutable_atom")return o.logger.error("\u274C","atom",n.key,"Tried to create atom, but it already exists in the store."),Po(S);let f=new s,y={...n,type:"mutable_atom",install:(F)=>{return F.logger.info("\uD83D\uDEE0\uFE0F","atom",n.key,`installing in store "${F.config.name}"`),RT(F,n,t)},subject:f};if(t)y.family=t;let A=n.default();T.atoms.set(y.key,y),AS(n.key,o),Wn(n.key,A,f,T);let M=Po(y);if(n.effects){let F=0,k=[];for(let W of n.effects){let O=W({setSelf:(E)=>{Qo(o,M,E)},onSet:(E)=>eo(M,E,`effect[${F}]`,o)});if(O)k.push(O);++F}y.cleanup=()=>{for(let W of k)W()}}if(new an(M,o),!t)nA(M,n,o);return M}class Yf{Update;latestUpdateAtoms;mutableAtoms;constructor(o,n){let t=jn(n,{key:`*${o.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=d(t,n),this.mutableAtoms=o,this.mutableAtoms.subject.subscribe(`store=${n.config.name}::tracker-atom-family`,(T)=>{if(T.token.family){let S=bo(T.token.family.subKey);Go(n,this.latestUpdateAtoms,S),new an(T.token,n)}}),this.latestUpdateAtoms.subject.subscribe(`store=${n.config.name}::tracker-atom-family`,(T)=>{if(T.token.family){let S=bo(T.token.family.subKey),f=Go(n,this.mutableAtoms,S);if(f)new an(f,n)}})}}function ST(o,n,t){let T={key:n.key,type:"mutable_atom_family"},S=o.families.get(n.key);if(S)o.logger.error("\u2757","mutable_atom_family",n.key,`Overwriting an existing ${Hn(S)} "${S.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let f=new s,A=Object.assign((M)=>{let F=l(M),k={key:n.key,subKey:F},W=`${n.key}(${F})`,O=D(o),E={key:W,default:()=>n.default(M),toJson:n.toJson,fromJson:n.fromJson,mutable:!0};if(n.effects)E.effects=n.effects(M);let Q=RT(O,E,k);return f.next({type:"state_creation",token:Q}),Q},T,{subject:f,install:(M)=>ST(M,n),toJson:n.toJson,fromJson:n.fromJson,internalRoles:t});return o.families.set(n.key,A),IA(A,n,o),new Yf(A,o),T}var kf=(o,n)=>{let t=D(n),T=`${o.key}:JSON`;return t.families.get(T)};var ro=(o,n)=>{if(n.family){let T=D(o),f={key:`${n.family.key}:JSON`,type:"selector_family"},y=d(f,T),A=JSON.parse(n.family.subKey);return ko(o,y,A)}return{type:"selector",key:`${n.key}:JSON`}};var qn=(o)=>{let t={type:"atom",key:`*${o.key}`};if(o.family)t.family={key:`*${o.family.key}`,subKey:o.family.subKey};return t};function WA(o){return typeof o==="object"&&o!==null&&"do"in o&&"undo"in o&&"subscribe"in o}function kT(o,n,t){let T=n.valueMap.get(o.key),S=t.valueMap.get(o.key);if(T===S){if(T===void 0)return typeof o.default==="function"?o.default():o.default;n.logger.info("\uD83D\uDCC3","atom",o.key,"copying");let f=o.toJson(T),y=o.fromJson(f);return t.valueMap.set(o.key,y),new an(o,n),y}return S}function Wn(o,n,t,T){let S=T.valueMap.get(o);if(S instanceof TT)S.use(n);if(n instanceof Promise){let f=new TT(n);return T.valueMap.set(o,f),f.then((y)=>{Wn(o,y,t,T),t.next({newValue:y,oldValue:f})}).catch((y)=>{T.logger.error("\uD83D\uDCA5","state",o,"rejected:",y)}),f}return T.valueMap.set(o,n),n}var AA=(o,n)=>{let t=n.valueMap.get(o.key);if(o.type==="mutable_atom"&&Fo(n)){let{parent:T}=n;t=kT(o,T,n)}return t},JA=(o,n)=>{let t=n.valueMap.get(o);if(t instanceof TT){let T=t,S=n.selectors.get(o)??n.readonlySelectors.get(o);if(S)T.use(S.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 _A=(o,n)=>{return D(n).atomsThatAreDefault.has(o)},AS=(o,n)=>{let t=D(n);t.atomsThatAreDefault=new Set(t.atomsThatAreDefault).add(o)},wA=(o,n)=>{let 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}"`);let T=D(o),S=T.atoms.get(n.key);if(S&&S.type==="atom")return o.logger.error("\u274C","atom",n.key,"Tried to create atom, but it already exists in the store."),Po(S);let f=new s,y={...n,type:"atom",install:(F)=>{return F.logger.info("\uD83D\uDEE0\uFE0F","atom",n.key,`installing in store "${F.config.name}"`),Tn(F,n,t)},subject:f};if(t)y.family=t;let A=n.default;if(n.default instanceof Function)A=n.default();T.atoms.set(y.key,y),AS(n.key,o),Wn(n.key,A,f,T);let M=Po(y);if(n.effects){let F=0,k=[];for(let W of n.effects){let O=W({setSelf:(E)=>{Qo(o,M,E)},onSet:(E)=>eo(M,E,`effect[${F}]`,o)});if(O)k.push(O);++F}y.cleanup=()=>{for(let W of k)W()}}return M}function SA(o,n){if("mutable"in n){let S=RT(o,n,void 0);return o.on.atomCreation.next(S),S}let T=Tn(o,n,void 0);return o.on.atomCreation.next(T),T}function _f(o,n){let t=D(n),{key:T}=o,S=d(o,t);if(!S.family)n.logger.error("\u274C","atom",T,"Standalone atoms cannot be disposed.");else{S.cleanup?.();let f=n.valueMap.get(S.key);d({key:S.family.key,type:"atom_family"},n).subject.next({type:"state_disposal",token:o,value:f});let A=t.molecules.get(S.family.subKey);if(A)A.tokens.delete(T);if(t.atoms.delete(T),t.valueMap.delete(T),t.selectorAtoms.delete(T),t.atomsThatAreDefault.delete(T),n.timelineTopics.delete(T),o.type==="mutable_atom"){let M=qn(o);_f(M,n),n.trackers.delete(T)}if(n.logger.info("\uD83D\uDD25","atom",T,"deleted"),Fo(t)&&t.transactionMeta.phase==="building")t.transactionMeta.update.updates.push({type:"state_disposal",token:o});else n.on.atomDisposal.next(o)}}var Gf=(o)=>{let n=Tn(o,{key:"\uD83D\uDD0D Atom Token Index (Internal)",default:()=>{let t=new Map;for(let[T,S]of o.atoms)if(!T.includes("\uD83D\uDD0D")){let f=Po(S);if(S.family){let y=t.get(S.family.key);if(!y||!("familyMembers"in y))y={key:S.family.key,familyMembers:new Map},t.set(S.family.key,y);y.familyMembers.set(S.family.subKey,f)}else t.set(T,f)}return t},effects:[({setSelf:t})=>{o.on.atomCreation.subscribe("introspection",(T)=>{if(T.key.includes("\uD83D\uDD0D"))return;t((S)=>{if(T.family){let{key:f,subKey:y}=T.family,A=S.get(f);if(A===void 0||!("familyMembers"in A))A={key:f,familyMembers:new Map},S.set(f,A);A.familyMembers.set(y,T)}else S.set(T.key,T);return S})}),o.on.atomDisposal.subscribe("introspection",(T)=>{t((S)=>{if(T.family){let{key:f,subKey:y}=T.family,A=S.get(f);if(A&&"familyMembers"in A){if(A.familyMembers.delete(y),A.familyMembers.size===0)S.delete(f)}}else S.delete(T.key);return S})})}]},void 0);return zn(o,{key:"\uD83D\uDD0D Atom Token Index",get:({get:t})=>t(n)})};var zf=(o)=>{let n=Tn(o,{key:"\uD83D\uDD0D Selector Token Index (Internal)",default:()=>{let t=new Map;for(let T of[o.readonlySelectors,o.selectors])for(let[S,f]of T)if(!S.includes("\uD83D\uDD0D")){let y=Po(f);if(f.family){let A=t.get(f.family.key);if(!A||!("familyMembers"in A))A={key:f.family.key,familyMembers:new Map},t.set(f.family.key,A);A.familyMembers.set(f.family.subKey,y)}else t.set(S,y)}return t},effects:[({setSelf:t})=>{o.on.selectorCreation.subscribe("introspection",(T)=>{if(T.key.includes("\uD83D\uDD0D"))return;t((S)=>{if(T.family){let{key:f,subKey:y}=T.family,A=S.get(f);if(A===void 0||!("familyMembers"in A))A={key:f,familyMembers:new Map},S.set(f,A);A.familyMembers.set(y,T)}else S.set(T.key,T);return S})}),o.on.selectorDisposal.subscribe("introspection",(T)=>{t((S)=>{if(T.family){let{key:f,subKey:y}=T.family,A=S.get(f);if(A&&"familyMembers"in A){if(A.familyMembers.delete(y),A.familyMembers.size===0)S.delete(f)}}else S.delete(T.key);return S})})}]},void 0);return zn(o,{key:"\uD83D\uDD0D Selector Token Index",get:({get:t})=>t(n)})};class MS{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(T){try{if(o instanceof t)return{type:n,data:o}}catch(S){}}return null}}var Hf=new MS({number:(o)=>typeof o==="number",string:(o)=>typeof o==="string",boolean:(o)=>typeof o==="boolean",null:(o)=>o===null});function mf(o){if(!o)return!1;return Object.getPrototypeOf(o)===Object.prototype}var Qf=new MS({object:mf,array:(o)=>Array.isArray(o)}),cJ=new MS({...Hf.supported,...Qf.supported}),Ut=(o)=>{if(o===void 0)return"undefined";let n=cJ.refine(o);if(n)return n.type;return Object.getPrototypeOf(o).constructor.name};class bA{o;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(o=yo.STORE){this.store=o;this.atomIndex=Gf(this.store),this.selectorIndex=zf(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=bA.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");let n=Sf(this.atomIndex),t=Sf(this.selectorIndex),T=[...n.values()].filter((A)=>("familyMembers"in A)),S=[...t.values()].filter((A)=>("familyMembers"in A)),f=performance.now(),y=[];if(o.atomFamilies)for(let A of T){let M=A.familyMembers.values();for(let F of M){let W=this.statesCreatedAt.get(F.key)??this.auditorCreatedAt,O=f-W;y.push([F,O])}}if(o.selectorFamilies)for(let A of S){let M=A.familyMembers.values();for(let F of M){let W=this.statesCreatedAt.get(F.key)??this.auditorCreatedAt,O=f-W;y.push([F,O])}}return y}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}}var Df=(o,n)=>{let t=(T,S)=>{let y=((M,F)=>{let k=n(M,F);if(k)return k;return null})(T,S);if(y?.jobComplete??y?.pathComplete)return y;let A=Array.isArray(S)?S.map((M,F)=>[F,M]):mf(S)?Object.entries(S):[];for(let[M,F]of A){let k=t([...T,M],F);if(k?.jobComplete)return k}return{}};t([],o)};function xJ(o,n){return{summary:`${o<n?"+":"-"}${Math.abs(o-n)} (${o} \u2192 ${n})`}}function iJ(o,n){return{summary:`${o.length<n.length?"+":"-"}${Math.abs(o.length-n.length)} ("${o}" \u2192 "${n}")`}}function vJ(o,n){return{summary:`${o} \u2192 ${n}`}}function NA(o,n,t){let T="",S=[],f=[],y=[];return Df(o,(A,M)=>{let F;for(F of A){let k=n[F];if(k===void 0)f.push([F,JSON.stringify(M)]);else{let W=t(M,k);if(W.summary!=="No Change")y.push([F,W])}}}),Df(n,(A,M)=>{let F;for(F of A)if(o[F]===void 0)S.push([F,JSON.stringify(M)])}),T=`\uFF5E${y.length} \uFF0B${S.length} \uFF0D${f.length}`,{summary:T,added:S,removed:f,changed:y}}function pJ(o,n,t){return NA(o,n,t)}class hA{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(o,n,t){this.leafRefinery=o,this.treeRefinery=n,this.leafDiffers={},this.treeDiffers={};for(let T of Object.keys(o.supported)){let S=t[T];this.leafDiffers[T]=S}for(let T of Object.keys(n.supported)){let S=t[T];this.treeDiffers[T]=S}}diff(o,n){if(o===n)return{summary:"No Change"};let t=this.leafRefinery.refine(o)??this.treeRefinery.refine(o),T=this.leafRefinery.refine(n)??this.treeRefinery.refine(n);if(t!==null&&T!==null){if(t.type===T.type){if(t.type in this.leafDiffers)return this.leafDiffers[t.type](t.data,T.data);if(t.type in this.treeDiffers)return this.treeDiffers[t.type](t.data,T.data,(A,M)=>this.diff(A,M))}}let S=Ut(o),f=Ut(n);if(S===f)return{summary:`${S} \u2192 ${f}`};return{summary:`Type change: ${S} \u2192 ${f}`}}}var $8=new hA(Hf,Qf,{number:xJ,string:iJ,boolean:vJ,null:()=>({summary:"No Change"}),object:NA,array:pJ});class cA 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 FS{o;type="continuity";globals=[];actions=[];perspectives=[];constructor(o){this.key=o}static existing=new cA;static create(o,n){let t=new FS(o),{type:T,globals:S,actions:f,perspectives:y}=n(t),A={type:T,key:o,globals:S,actions:f,perspectives:y};return FS.existing.set(o,A),A}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":{let[t,T]=o;this.perspectives.push({type:"realtime_perspective",resourceAtoms:t,viewAtoms:T})}break}return this}}function E8(o){let{key:n,config:t}=o,T=FS.create(n,t),{actions:S}=T;for(let f of S)QA(n,f.key,yo.STORE);return zA(n,-1,yo.STORE),T}var m8=Qt({key:"usersInRoomIndex",mutable:!0,default:()=>new No,toJson:(o)=>o.toJSON(),fromJson:(o)=>No.fromJSON(o)}),Uf=Qt({key:"roomIndex",default:()=>new No,mutable:!0,toJson:(o)=>o.toJSON(),fromJson:(o)=>No.fromJSON(o)}),qJ={enteredAtEpoch:0},WT=uT({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(o)=>typeof o==="string",isBType:(o)=>typeof o==="string"},qJ),Q8=PT({key:"usersInMyRoomView",get:(o)=>({find:n})=>{let t=EA(WT);return[n(t,o)]}});import{spawn as ZJ}from"child_process";class Vt{o;listeners;globalListeners;handleEvent(o,...n){for(let T of this.globalListeners)T(o,...n);let t=this.listeners.get(o);if(t)for(let T of t)T(...n)}id="no_id_retrieved";constructor(o){this.emit=o;this.listeners=new Map,this.globalListeners=new Set}on(o,n){let 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){let 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 Vf extends Vt{o;n;t;incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";handleLog(o){if(Array.isArray(o)){let[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((T,...S)=>{let f=JSON.stringify([T,...S])+"\x03",y=(A)=>{if(A.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",y)};return this.process.stdin.once("error",y),this.process.stdin.write(f),this});this.process=o;this.key=n;this.logger=t;if(this.process=o,this.process.stdout.on("data",(T)=>{let S=T.toString();if(S==="\u2728")return;this.unprocessedEvents.push(...S.split("\x03"));let f=this.unprocessedEvents.shift();this.incompleteData+=f??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let y=bo(this.incompleteData);this.handleEvent(...y);while(this.unprocessedEvents.length>0){let A=this.unprocessedEvents.shift();if(A){if(this.unprocessedEvents.length===0)this.incompleteData=A;y=bo(A),this.handleEvent(...y)}}this.incompleteData=""}catch(y){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error(y)}}),this.process.stderr.on("data",(T)=>{let S=T.toString();this.unprocessedLogs.push(...S.split("\x03"));let f=this.unprocessedLogs.shift();this.incompleteLog+=f??"";try{let y=bo(this.incompleteLog);this.handleLog(y);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)y=bo(this.incompleteLog),this.handleLog(y)}catch(y){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error(y),console.error("\u274C\u274C\u274C\uFE0F")}}),o.pid)this.id=o.pid.toString()}}class xA 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 rf extends Vt{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...o){this.process.stderr.write(l(o.map((n)=>n instanceof No?`{ ${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)=>{let 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)=>{let n=o.toString();this.unprocessedEvents.push(...n.split("\x03"));let t=this.unprocessedEvents.shift();this.incompleteData+=t??"";try{let T=bo(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",T),this.handleEvent(...T);while(this.unprocessedEvents.length>0){let S=this.unprocessedEvents.shift();if(S){if(this.unprocessedEvents.length===0)this.incompleteData=S;let f=bo(S);this.handleEvent(...f)}}this.incompleteData=""}catch(T){if(T instanceof Error)this.logger.error("\u2757",T.message,T.cause,T.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");let n=new xA(`user:${o}`);this.relays.set(o,n),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let t of this.relayServices){let T=t(n);if(T)n.disposalFunctions.push(T)}this.on(`user:${o}`,(...t)=>{n.in.next(t)}),n.out.subscribe("socket",(t)=>{this.emit(...t)})}),this.on("user-leaves",(o)=>{let 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)}}var Bf=Ft({key:"roomArguments",default:["echo",["Hello World!"]]}),iA=PT({key:"room",get:(o)=>async({get:n,find:t})=>{let T=t(Bf,o),S=n(T),[f,y]=S,A=await new Promise((M)=>{let F=ZJ(f,y,{env:process.env}),k=(W)=>{if(W.toString()==="\u2728")F.stdout.off("data",k),M(F)};F.stdout.on("data",k)});return new Vf(A,o)}});var o5=FT({key:"createRoom",do:({get:o,set:n,find:t},T,S,f)=>{let y=f?[S,f]:[S],A=t(Bf,T);n(A,y),n(Uf,(k)=>k.add(T));let M=t(iA,T);return o(M)}}),n5=FT({key:"joinRoom",do:(o,n,t,T)=>{let S={enteredAtEpoch:T};return sT(WT,(f)=>{f.set({room:n,user:t},S)},o.env().store),S}}),t5=FT({key:"leaveRoom",do:(o,n,t)=>{sT(WT,(T)=>{T.delete({room:n,user:t})},o.env().store)}}),T5=FT({key:"destroyRoom",do:(o,n)=>{sT(WT,(t)=>{t.delete({room:n})},o.env().store),o.set(Uf,(t)=>(t.delete(n),t))}});function Cf(o,n){return n.map((t)=>{switch(t.type){case"transaction_update":{let T=Cf(o,t.updates);return{...t,updates:T}}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 y5=Ft({key:"redactor",default:{occlude:(o)=>o}}),rt=Ft({key:"unacknowledgedUpdates",default:()=>[]});var vA=Ft({key:"sockets",default:null}),$5=Qt({key:"socketsIndex",mutable:!0,default:()=>new No,toJson:(o)=>o.toJSON(),fromJson:(o)=>No.fromJSON(o)}),J5=Qt({key:"usersIndex",mutable:!0,default:()=>new No,toJson:(o)=>o.toJSON(),fromJson:(o)=>No.fromJSON(o)}),Lf=uT({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(o)=>o.startsWith("user::"),isBType:(o)=>o.startsWith("socket::")});function pA(o,n,t,T){let S=n.key;return function f(){let y=[];for(let M of n.globals){let F=M.type==="mutable_atom"?ro(o,M):M,k=Mo(o,F);y.push(F,k)}for(let M of n.perspectives){let{viewAtoms:F,resourceAtoms:k}=M,W=ko(o,F,t),O=Mo(o,W);o.logger.info("\uD83D\uDC41","atom",k.key,`${t} can see`,{viewAtoms:F,resourceAtoms:k,userView:O});for(let E of O){let Q=E.type==="mutable_atom"?ro(o,E):E,z=Mo(o,Q);y.push(Q,z)}}let A=Bo(o)?o.transactionMeta.epoch.get(S)??null:null;T?.emit(`continuity-init:${S}`,A,y)}}function qA(o,n,t){let T=n.key;return function S(f){o.logger.info("\uD83D\uDECE\uFE0F","continuity",T,"received",f);let{key:y,id:A}=f,M=`tx-run:${y}:${A}`,F=`${M}:start`,k=`${M}:end`;performance.mark(F);try{dn({type:"transaction",key:y},A,o)(...f.params)}catch(O){if(O instanceof Error)o.logger.error("\u274C","continuity",T,`failed to run transaction ${y} from ${t} with update ${A}`,O.message)}performance.mark(k);let W=performance.measure(M,F,k);o?.logger.info("\uD83D\uDE80","transaction",y,A,t,W.duration)}}function ZA(o,n,t,T){let S=n.key;return function f(y){if(o.logger.info("\uD83D\uDC4D","continuity",S,`${t} acknowledged epoch ${y}`),T[0]?.epoch===y)Qo(o,rt,t,(M)=>{return M.shift(),o.logger.info("\uD83D\uDC4D","continuity",S,`${t} unacknowledged update queue now has`,M.length,"items"),M})}}function PA(o,n,t,T){let S=n.key,f=[];for(let y of n.actions){let A=Xf(y,(M)=>{try{let F=n.globals.map((O)=>{if(O.type==="atom")return O.key;return qn(O).key}).concat(n.perspectives.flatMap((O)=>{let{viewAtoms:E}=O,Q=ko(o,E,t);return Mo(o,Q).map((G)=>{return G.type==="mutable_atom"?"*"+G.key:G.key})})),k=Cf(F,M.updates),W={...M,updates:k};Qo(o,rt,t,(O)=>{if(W)O.push(W),O.sort((E,Q)=>E.epoch-Q.epoch),o.logger.info("\uD83D\uDC4D","continuity",S,`${t} unacknowledged update queue now has`,O.length,"items");return O}),T?.emit(`tx-new:${S}`,W)}catch(F){if(F instanceof Error)o.logger.error("\u274C","continuity",S,`${t} failed to send update from transaction ${y.key} to ${t}`,F.message)}},`sync-continuity:${S}:${t}`,o);f.push(A)}return f}function eA(o,n,t,T){let S=n.key,f=[];for(let y of n.perspectives){let{viewAtoms:A}=y,M=ko(o,A,t),F=eo(M,({oldValue:k,newValue:W})=>{let O=k.map((G)=>G.key),E=W.map((G)=>G.key),Q=k.filter((G)=>!E.includes(G.key)),z=W.filter((G)=>!O.includes(G.key)).flatMap((G)=>{let V=G.type==="mutable_atom"?ro(o,G):G,x=Mo(o,V);return[V,x]});if(o.logger.info("\uD83D\uDC41","atom",y.resourceAtoms.key,`${t} has a new perspective`,{oldKeys:O,newKeys:E,revealed:z,concealed:Q}),z.length>0)T?.emit(`reveal:${S}`,z);if(Q.length>0)T?.emit(`conceal:${S}`,Q)},`sync-continuity:${S}:${t}:perspective:${y.resourceAtoms.key}`,o);f.push(F)}return f}function v5({socket:o,store:n=yo.STORE}){return function t(T){let S=o,f=T.key,y=aT(Lf,`socket::${S.id}`,n).userKeyOfSocket,A=Mo(n,y);if(!A)return n.logger.error("\u274C","continuity",f,`Tried to create a synchronizer for a socket (${S.id}) that is not connected to a user.`),()=>{};let M=aT(Lf,A,n).socketKeyOfUser,F=eo(M,({newValue:V})=>{if(n.logger.info("\uD83D\uDC4B","continuity",f,`seeing ${A} on new socket ${V}`),V===null){n.logger.warn("\u274C","continuity",f,`User (${A}) is not connected to a socket, waiting for them to reappear.`);return}let x=ko(n,vA,V);S=Mo(n,x);for(let P of k)S?.emit(`tx-new:${f}`,P)},`sync-continuity:${f}:${A}`,n),k=Mo(n,rt,A),W=[],O=eA(n,T,A,S),E=PA(n,T,A,S);W.push(...O,...E);let Q=pA(n,T,A,o);S.off(`get:${f}`,Q),S.on(`get:${f}`,Q);let z=qA(n,T,A);S.off(`tx-run:${f}`,z),S.on(`tx-run:${f}`,z);let G=ZA(n,T,A,k);return S?.on(`ack:${f}`,G),()=>{for(let V of W)V();S?.off(`ack:${f}`,G),S?.off(`get:${f}`,Q),S?.off(`tx-run:${f}`,z)}}}var{file:C$,serve:a0}=globalThis.Bun;var J=Symbol.for("drizzle:entityKind"),WE=Symbol.for("drizzle:hasOwnEntityKind");function X(o,n){if(!o||typeof o!=="object")return!1;if(o instanceof n)return!0;if(!Object.prototype.hasOwnProperty.call(n,J))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(J in t&&t[J]===n[J])return!0;t=Object.getPrototypeOf(t)}return!1}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[J]="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 If{static[J]="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 Qn=Symbol.for("drizzle:Name");class jf{static[J]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(o,n){if(this.reference=()=>{let{name:t,columns:T,foreignColumns:S}=o();return{name:t,columns:T,foreignTable:S[0].table,foreignColumns:S}},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 lA(o,this)}}class lA{constructor(o,n){this.table=o,this.reference=n.reference,this.onUpdate=n._onUpdate,this.onDelete=n._onDelete}static[J]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:o,columns:n,foreignColumns:t}=this.reference(),T=n.map((y)=>y.name),S=t.map((y)=>y.name),f=[this.table[Qn],...T,t[0].table[Qn],...S];return o??`${f.join("_")}_fk`}}function kS(o,...n){return o(...n)}function gA(o,n){return`${o[Qn]}_${n.join("_")}_unique`}function dA(o,n,t){for(let T=n;T<o.length;T++){let S=o[T];if(S==="\\"){T++;continue}if(S==='"')return[o.slice(n,T).replace(/\\/g,""),T+1];if(t)continue;if(S===","||S==="}")return[o.slice(n,T).replace(/\\/g,""),T]}return[o.slice(n).replace(/\\/g,""),o.length]}function uA(o,n=0){let t=[],T=n,S=!1;while(T<o.length){let f=o[T];if(f===","){if(S||T===n)t.push("");S=!0,T++;continue}if(S=!1,f==="\\"){T+=2;continue}if(f==='"'){let[M,F]=dA(o,T+1,!0);t.push(M),T=F;continue}if(f==="}")return[t,T+1];if(f==="{"){let[M,F]=uA(o,T+1);t.push(M),T=F;continue}let[y,A]=dA(o,T,!1);t.push(y),T=A}return[t,T]}function aA(o){let[n]=uA(o,1);return n}function bf(o){return`{${o.map((n)=>{if(Array.isArray(n))return bf(n);if(typeof n==="string")return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`;return`${n}`}).join(",")}}`}class N extends If{foreignKeyConfigs=[];static[J]="PgColumnBuilder";array(o){return new oM(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:T})=>{return kS((S,f)=>{let y=new jf(()=>{let A=S();return{columns:[o],foreignColumns:[A]}});if(f.onUpdate)y.onUpdate(f.onUpdate);if(f.onDelete)y.onDelete(f.onDelete);return y.build(n)},t,T)})}buildExtraConfigColumn(o){return new sA(o,this.config)}}class r extends Xo{constructor(o,n){if(!n.uniqueName)n.uniqueName=gA(o,[n.name]);super(o,n);this.table=o}static[J]="PgColumn"}class sA extends r{static[J]="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 OT{static[J]="IndexedColumn";constructor(o,n,t,T){this.name=o,this.keyAsName=n,this.type=t,this.indexConfig=T}name;keyAsName;type;indexConfig}class oM extends N{static[J]="PgArrayBuilder";constructor(o,n,t){super(o,"array","PgArray");this.config.baseBuilder=n,this.config.size=t}build(o){let n=this.config.baseBuilder.build(o);return new Nf(o,this.config,n)}}class Nf extends r{constructor(o,n,t,T){super(o,n);this.baseColumn=t,this.range=T,this.size=n.size}size;static[J]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(o){if(typeof o==="string")o=aA(o);return o.map((n)=>this.baseColumn.mapFromDriverValue(n))}mapToDriverValue(o,n=!1){let t=o.map((T)=>T===null?null:X(this.baseColumn,Nf)?this.baseColumn.mapToDriverValue(T,!0):this.baseColumn.mapToDriverValue(T));if(n)return t;return bf(t)}}var hf=Symbol.for("drizzle:isPgEnum");function nM(o){return!!o&&typeof o==="function"&&hf in o&&o[hf]===!0}class tM extends N{static[J]="PgEnumColumnBuilder";constructor(o,n){super(o,"string","PgEnumColumn");this.config.enum=n}build(o){return new TM(o,this.config)}}class TM extends r{static[J]="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}}function $S(o,n){return PJ(o,n,void 0)}function PJ(o,n,t){let T=Object.assign((S)=>new tM(S??"",T),{enumName:o,enumValues:n,schema:t,[hf]:!0});return T}class xo{static[J]="Subquery";constructor(o,n,t,T=!1){this._={brand:"Subquery",sql:o,selectedFields:n,alias:t,isWith:T}}}class _T extends xo{static[J]="WithSubquery"}var SM="0.36.1";var cf,xf,Oo={startActiveSpan(o,n){if(!cf)return n();if(!xf)xf=cf.trace.getTracer("drizzle-orm",SM);return kS((t,T)=>T.startActiveSpan(o,(S)=>{try{return n(S)}catch(f){throw S.setStatus({code:t.SpanStatusCode.ERROR,message:f instanceof Error?f.message:"Unknown error"}),f}finally{S.end()}}),cf,xf)}};var Do=Symbol.for("drizzle:ViewBaseConfig");var JS=Symbol.for("drizzle:Schema"),fM=Symbol.for("drizzle:Columns"),yM=Symbol.for("drizzle:ExtraConfigColumns"),vf=Symbol.for("drizzle:OriginalName"),pf=Symbol.for("drizzle:BaseName"),AM=Symbol.for("drizzle:IsAlias"),MM=Symbol.for("drizzle:ExtraConfigBuilder"),eJ=Symbol.for("drizzle:IsDrizzleTable");class L{static[J]="Table";static Symbol={Name:Qn,Schema:JS,OriginalName:vf,Columns:fM,ExtraConfigColumns:yM,BaseName:pf,IsAlias:AM,ExtraConfigBuilder:MM};[Qn];[vf];[JS];[fM];[yM];[pf];[AM]=!1;[eJ]=!0;[MM]=void 0;constructor(o,n,t){this[Qn]=this[vf]=o,this[JS]=n,this[pf]=t}}function _n(o){return o[Qn]}function kt(o){return`${o[JS]??"public"}.${o[Qn]}`}function qf(o){return o!==null&&o!==void 0&&typeof o.getSQL==="function"}function lJ(o){let 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}class ho{static[J]="StringChunk";value;constructor(o){this.value=Array.isArray(o)?o:[o]}getSQL(){return new h([this])}}class h{constructor(o){this.queryChunks=o}static[J]="SQL";decoder=kM;shouldInlineParams=!1;append(o){return this.queryChunks.push(...o.queryChunks),this}toQuery(o){return Oo.startActiveSpan("drizzle.buildSQL",(n)=>{let 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){let t=Object.assign({},n,{inlineParams:n.inlineParams||this.shouldInlineParams,paramStartIndex:n.paramStartIndex||{value:0}}),{casing:T,escapeName:S,escapeParam:f,prepareTyping:y,inlineParams:A,paramStartIndex:M}=t;return lJ(o.map((F)=>{if(X(F,ho))return{sql:F.value.join(""),params:[]};if(X(F,RS))return{sql:S(F.value),params:[]};if(F===void 0)return{sql:"",params:[]};if(Array.isArray(F)){let k=[new ho("(")];for(let[W,O]of F.entries())if(k.push(O),W<F.length-1)k.push(new ho(", "));return k.push(new ho(")")),this.buildQueryFromSourceParams(k,t)}if(X(F,h))return this.buildQueryFromSourceParams(F.queryChunks,{...t,inlineParams:A||F.shouldInlineParams});if(X(F,L)){let k=F[L.Symbol.Schema],W=F[L.Symbol.Name];return{sql:k===void 0?S(W):S(k)+"."+S(W),params:[]}}if(X(F,Xo)){let k=T.getColumnCasing(F);if(n.invokeSource==="indexes")return{sql:S(k),params:[]};return{sql:S(F.table[L.Symbol.Name])+"."+S(k),params:[]}}if(X(F,fn)){let k=F[Do].schema,W=F[Do].name;return{sql:k===void 0?S(W):S(k)+"."+S(W),params:[]}}if(X(F,kn)){if(X(F.value,sn))return{sql:f(M.value++,F),params:[F],typings:["none"]};let k=F.value===null?null:F.encoder.mapToDriverValue(F.value);if(X(k,h))return this.buildQueryFromSourceParams([k],t);if(A)return{sql:this.mapInlineParam(k,t),params:[]};let W=["none"];if(y)W=[y(F.encoder)];return{sql:f(M.value++,k),params:[k],typings:W}}if(X(F,sn))return{sql:f(M.value++,F),params:[F],typings:["none"]};if(X(F,h.Aliased)&&F.fieldAlias!==void 0)return{sql:S(F.fieldAlias),params:[]};if(X(F,xo)){if(F._.isWith)return{sql:S(F._.alias),params:[]};return this.buildQueryFromSourceParams([new ho("("),F._.sql,new ho(") "),new RS(F._.alias)],t)}if(nM(F)){if(F.schema)return{sql:S(F.schema)+"."+S(F.enumName),params:[]};return{sql:S(F.enumName),params:[]}}if(qf(F)){if(F.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([F.getSQL()],t);return this.buildQueryFromSourceParams([new ho("("),F.getSQL(),new ho(")")],t)}if(A)return{sql:this.mapInlineParam(F,t),params:[]};return{sql:f(M.value++,F),params:[F],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"){let 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 h.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 RS{constructor(o){this.value=o}static[J]="Name";brand;getSQL(){return new h([this])}}function FM(o){return typeof o==="object"&&o!==null&&"mapToDriverValue"in o&&typeof o.mapToDriverValue==="function"}var kM={mapFromDriverValue:(o)=>o},$M={mapToDriverValue:(o)=>o},tY={...kM,...$M};class kn{constructor(o,n=$M){this.value=o,this.encoder=n}static[J]="Param";brand;getSQL(){return new h([this])}}function R(o,...n){let t=[];if(n.length>0||o.length>0&&o[0]!=="")t.push(new ho(o[0]));for(let[T,S]of n.entries())t.push(S,new ho(o[T+1]));return new h(t)}((o)=>{function n(){return new h([])}o.empty=n;function t(M){return new h(M)}o.fromList=t;function T(M){return new h([new ho(M)])}o.raw=T;function S(M,F){let k=[];for(let[W,O]of M.entries()){if(W>0&&F!==void 0)k.push(F);k.push(O)}return new h(k)}o.join=S;function f(M){return new RS(M)}o.identifier=f;function y(M){return new sn(M)}o.placeholder=y;function A(M,F){return new kn(M,F)}o.param=A})(R||(R={}));((o)=>{class n{constructor(t,T){this.sql=t,this.fieldAlias=T}static[J]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new n(this.sql,this.fieldAlias)}}o.Aliased=n})(h||(h={}));class sn{constructor(o){this.name=o}static[J]="Placeholder";getSQL(){return new h([this])}}function Zf(o,n){return o.map((t)=>{if(X(t,sn)){if(!(t.name in n))throw new Error(`No value for placeholder "${t.name}" was provided`);return n[t.name]}if(X(t,kn)&&X(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 fn{static[J]="View";[Do];constructor({name:o,schema:n,selectedFields:t,query:T}){this[Do]={name:o,originalName:o,schema:n,selectedFields:t,query:T,isExisting:!T,isAlias:!1}}getSQL(){return new h([this])}}Xo.prototype.getSQL=function(){return new h([this])};L.prototype.getSQL=function(){return new h([this])};xo.prototype.getSQL=function(){return new h([this])};class Bt{constructor(o){this.table=o}static[J]="ColumnAliasProxyHandler";get(o,n){if(n==="table")return this.table;return o[n]}}class wT{constructor(o,n){this.alias=o,this.replaceOriginalName=n}static[J]="TableAliasProxyHandler";get(o,n){if(n===L.Symbol.IsAlias)return!0;if(n===L.Symbol.Name)return this.alias;if(this.replaceOriginalName&&n===L.Symbol.OriginalName)return this.alias;if(n===Do)return{...o[Do],name:this.alias,isAlias:!0};if(n===L.Symbol.Columns){let T=o[L.Symbol.Columns];if(!T)return T;let S={};return Object.keys(T).map((f)=>{S[f]=new Proxy(T[f],new Bt(new Proxy(o,this)))}),S}let t=o[n];if(X(t,Xo))return new Proxy(t,new Bt(new Proxy(o,this)));return t}}function WS(o,n){return new Proxy(o,new wT(n,!1))}function bn(o,n){return new Proxy(o,new Bt(new Proxy(o.table,new wT(n,!1))))}function Pf(o,n){return new h.Aliased(KT(o.sql,n),o.fieldAlias)}function KT(o,n){return R.join(o.queryChunks.map((t)=>{if(X(t,Xo))return bn(t,n);if(X(t,h))return KT(t,n);if(X(t,h.Aliased))return Pf(t,n);return t}))}class OS extends Error{static[J]="DrizzleError";constructor({message:o,cause:n}){super(o);this.name="DrizzleError",this.cause=n}}class ef extends OS{static[J]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}function yn(o,n){if(FM(n)&&!qf(o)&&!X(o,kn)&&!X(o,sn)&&!X(o,Xo)&&!X(o,L)&&!X(o,fn))return new kn(o,n);return o}var Ct=(o,n)=>{return R`${o} = ${yn(n,o)}`},JM=(o,n)=>{return R`${o} <> ${yn(n,o)}`};function XT(...o){let n=o.filter((t)=>t!==void 0);if(n.length===0)return;if(n.length===1)return new h(n);return new h([new ho("("),R.join(n,new ho(" and ")),new ho(")")])}function RM(...o){let n=o.filter((t)=>t!==void 0);if(n.length===0)return;if(n.length===1)return new h(n);return new h([new ho("("),R.join(n,new ho(" or ")),new ho(")")])}function WM(o){return R`not ${o}`}var OM=(o,n)=>{return R`${o} > ${yn(n,o)}`},_M=(o,n)=>{return R`${o} >= ${yn(n,o)}`},wM=(o,n)=>{return R`${o} < ${yn(n,o)}`},KM=(o,n)=>{return R`${o} <= ${yn(n,o)}`};function XM(o,n){if(Array.isArray(n)){if(n.length===0)return R`false`;return R`${o} in ${n.map((t)=>yn(t,o))}`}return R`${o} in ${yn(n,o)}`}function EM(o,n){if(Array.isArray(n)){if(n.length===0)return R`true`;return R`${o} not in ${n.map((t)=>yn(t,o))}`}return R`${o} not in ${yn(n,o)}`}function YM(o){return R`${o} is null`}function GM(o){return R`${o} is not null`}function zM(o){return R`exists ${o}`}function HM(o){return R`not exists ${o}`}function mM(o,n,t){return R`${o} between ${yn(n,o)} and ${yn(t,o)}`}function QM(o,n,t){return R`${o} not between ${yn(n,o)} and ${yn(t,o)}`}function DM(o,n){return R`${o} like ${n}`}function UM(o,n){return R`${o} not like ${n}`}function VM(o,n){return R`${o} ilike ${n}`}function rM(o,n){return R`${o} not ilike ${n}`}function BM(o){return R`${o} asc`}function CM(o){return R`${o} desc`}class LM{static[J]="ConsoleLogWriter";write(o){console.log(o)}}class lf{static[J]="DefaultLogger";writer;constructor(o){this.writer=o?.writer??new LM}logQuery(o,n){let t=n.map((S)=>{try{return JSON.stringify(S)}catch{return String(S)}}),T=t.length?` -- params: [${t.join(", ")}]`:"";this.writer.write(`Query: ${o}${T}`)}}class gf{static[J]="NoopLogger";logQuery(){}}class so{static[J]="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 IM(o,n,t){let T={},S=o.reduce((f,{path:y,field:A},M)=>{let F;if(X(A,Xo))F=A;else if(X(A,h))F=A.decoder;else F=A.sql.decoder;let k=f;for(let[W,O]of y.entries())if(W<y.length-1){if(!(O in k))k[O]={};k=k[O]}else{let E=n[M],Q=k[O]=E===null?null:F.mapFromDriverValue(E);if(t&&X(A,Xo)&&y.length===2){let z=y[0];if(!(z in T))T[z]=Q===null?_n(A.table):!1;else if(typeof T[z]==="string"&&T[z]!==_n(A.table))T[z]=!1}}return f},{});if(t&&Object.keys(T).length>0){for(let[f,y]of Object.entries(T))if(typeof y==="string"&&!t[y])S[f]=null}return S}function wn(o,n){return Object.entries(o).reduce((t,[T,S])=>{if(typeof T!=="string")return t;let f=n?[...n,T]:[T];if(X(S,Xo)||X(S,h)||X(S,h.Aliased))t.push({path:f,field:S});else if(X(S,L))t.push(...wn(S[L.Symbol.Columns],f));else t.push(...wn(S,f));return t},[])}function df(o,n){let t=Object.keys(o),T=Object.keys(n);if(t.length!==T.length)return!1;for(let[S,f]of t.entries())if(f!==T[S])return!1;return!0}function _S(o,n){let t=Object.entries(n).filter(([,T])=>T!==void 0).map(([T,S])=>{if(X(S,h))return[T,S];else return[T,new kn(S,o[L.Symbol.Columns][T])]});if(t.length===0)throw new Error("No values to set");return Object.fromEntries(t)}function jM(o,n){for(let t of n)for(let T of Object.getOwnPropertyNames(t.prototype)){if(T==="constructor")continue;Object.defineProperty(o.prototype,T,Object.getOwnPropertyDescriptor(t.prototype,T)||Object.create(null))}}function bM(o){return o[L.Symbol.Columns]}function uf(o){return X(o,xo)?o._.alias:X(o,fn)?o[Do].name:X(o,h)?void 0:o[L.Symbol.IsAlias]?o[L.Symbol.Name]:o[L.Symbol.BaseName]}function Ao(o,n){return{name:typeof o==="string"&&o.length>0?o:"",config:typeof o==="object"?o:n}}function NM(o){if(typeof o!=="object"||o===null)return!1;if(o.constructor.name!=="Object")return!1;if("logger"in o){let n=typeof o.logger;if(n!=="boolean"&&(n!=="object"||typeof o.logger.logQuery!=="function")&&n!=="undefined")return!1;return!0}if("schema"in o){let n=typeof o.logger;if(n!=="object"&&n!=="undefined")return!1;return!0}if("casing"in o){let n=typeof o.logger;if(n!=="string"&&n!=="undefined")return!1;return!0}if("mode"in o){if(o.mode!=="default"||o.mode!=="planetscale"||o.mode!==void 0)return!1;return!0}if("connection"in o){let n=typeof o.connection;if(n!=="string"&&n!=="object"&&n!=="undefined")return!1;return!0}if("client"in o){let n=typeof o.client;if(n!=="object"&&n!=="function"&&n!=="undefined")return!1;return!0}if(Object.keys(o).length===0)return!0;return!1}class ot extends N{static[J]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(o){if(o){let{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){let{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}}class hM extends ot{static[J]="PgBigInt53Builder";constructor(o){super(o,"number","PgBigInt53")}build(o){return new cM(o,this.config)}}class cM extends r{static[J]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}}class xM extends ot{static[J]="PgBigInt64Builder";constructor(o){super(o,"bigint","PgBigInt64")}build(o){return new iM(o,this.config)}}class iM extends r{static[J]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(o){return BigInt(o)}}function vM(o,n){let{name:t,config:T}=Ao(o,n);if(T.mode==="number")return new hM(t);return new xM(t)}class pM extends N{static[J]="PgBigSerial53Builder";constructor(o){super(o,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new qM(o,this.config)}}class qM extends r{static[J]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}}class ZM extends N{static[J]="PgBigSerial64Builder";constructor(o){super(o,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(o){return new PM(o,this.config)}}class PM extends r{static[J]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(o){return BigInt(o)}}function eM(o,n){let{name:t,config:T}=Ao(o,n);if(T.mode==="number")return new pM(t);return new ZM(t)}class lM extends N{static[J]="PgBooleanBuilder";constructor(o){super(o,"boolean","PgBoolean")}build(o){return new gM(o,this.config)}}class gM extends r{static[J]="PgBoolean";getSQLType(){return"boolean"}}function ET(o){return new lM(o??"")}class dM extends N{static[J]="PgCharBuilder";constructor(o,n){super(o,"string","PgChar");this.config.length=n.length,this.config.enumValues=n.enum}build(o){return new uM(o,this.config)}}class uM extends r{static[J]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function aM(o,n={}){let{name:t,config:T}=Ao(o,n);return new dM(t,T)}class sM extends N{static[J]="PgCidrBuilder";constructor(o){super(o,"string","PgCidr")}build(o){return new oF(o,this.config)}}class oF extends r{static[J]="PgCidr";getSQLType(){return"cidr"}}function nF(o){return new sM(o??"")}class tF extends N{static[J]="PgCustomColumnBuilder";constructor(o,n,t){super(o,"custom","PgCustomColumn");this.config.fieldConfig=n,this.config.customTypeParams=t}build(o){return new TF(o,this.config)}}class TF extends r{static[J]="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}}function SF(o){return(n,t)=>{let{name:T,config:S}=Ao(n,t);return new tF(T,S,o)}}class Zn extends N{static[J]="PgDateColumnBaseBuilder";defaultNow(){return this.default(R`now()`)}}class fF extends Zn{static[J]="PgDateBuilder";constructor(o){super(o,"date","PgDate")}build(o){return new wS(o,this.config)}}class wS extends r{static[J]="PgDate";getSQLType(){return"date"}mapFromDriverValue(o){return new Date(o)}mapToDriverValue(o){return o.toISOString()}}class yF extends Zn{static[J]="PgDateStringBuilder";constructor(o){super(o,"string","PgDateString")}build(o){return new KS(o,this.config)}}class KS extends r{static[J]="PgDateString";getSQLType(){return"date"}}function AF(o,n){let{name:t,config:T}=Ao(o,n);if(T?.mode==="date")return new fF(t);return new yF(t)}class MF extends N{static[J]="PgDoublePrecisionBuilder";constructor(o){super(o,"number","PgDoublePrecision")}build(o){return new FF(o,this.config)}}class FF extends r{static[J]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseFloat(o);return o}}function kF(o){return new MF(o??"")}class $F extends N{static[J]="PgInetBuilder";constructor(o){super(o,"string","PgInet")}build(o){return new JF(o,this.config)}}class JF extends r{static[J]="PgInet";getSQLType(){return"inet"}}function RF(o){return new $F(o??"")}class WF extends ot{static[J]="PgIntegerBuilder";constructor(o){super(o,"number","PgInteger")}build(o){return new OF(o,this.config)}}class OF extends r{static[J]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseInt(o);return o}}function XS(o){return new WF(o??"")}class _F extends N{static[J]="PgIntervalBuilder";constructor(o,n){super(o,"string","PgInterval");this.config.intervalConfig=n}build(o){return new wF(o,this.config)}}class wF extends r{static[J]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let o=this.fields?` ${this.fields}`:"",n=this.precision?`(${this.precision})`:"";return`interval${o}${n}`}}function KF(o,n={}){let{name:t,config:T}=Ao(o,n);return new _F(t,T)}class XF extends N{static[J]="PgJsonBuilder";constructor(o){super(o,"json","PgJson")}build(o){return new ES(o,this.config)}}class ES extends r{static[J]="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 EF(o){return new XF(o??"")}class YF extends N{static[J]="PgJsonbBuilder";constructor(o){super(o,"json","PgJsonb")}build(o){return new YS(o,this.config)}}class YS extends r{static[J]="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 GF(o){return new YF(o??"")}class zF extends N{static[J]="PgLineBuilder";constructor(o){super(o,"array","PgLine")}build(o){return new HF(o,this.config)}}class HF extends r{static[J]="PgLine";getSQLType(){return"line"}mapFromDriverValue(o){let[n,t,T]=o.slice(1,-1).split(",");return[Number.parseFloat(n),Number.parseFloat(t),Number.parseFloat(T)]}mapToDriverValue(o){return`{${o[0]},${o[1]},${o[2]}}`}}class mF extends N{static[J]="PgLineABCBuilder";constructor(o){super(o,"json","PgLineABC")}build(o){return new QF(o,this.config)}}class QF extends r{static[J]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(o){let[n,t,T]=o.slice(1,-1).split(",");return{a:Number.parseFloat(n),b:Number.parseFloat(t),c:Number.parseFloat(T)}}mapToDriverValue(o){return`{${o.a},${o.b},${o.c}}`}}function DF(o,n){let{name:t,config:T}=Ao(o,n);if(!T?.mode||T.mode==="tuple")return new zF(t);return new mF(t)}class UF extends N{static[J]="PgMacaddrBuilder";constructor(o){super(o,"string","PgMacaddr")}build(o){return new VF(o,this.config)}}class VF extends r{static[J]="PgMacaddr";getSQLType(){return"macaddr"}}function rF(o){return new UF(o??"")}class BF extends N{static[J]="PgMacaddr8Builder";constructor(o){super(o,"string","PgMacaddr8")}build(o){return new CF(o,this.config)}}class CF extends r{static[J]="PgMacaddr8";getSQLType(){return"macaddr8"}}function LF(o){return new BF(o??"")}class IF extends N{static[J]="PgNumericBuilder";constructor(o,n,t){super(o,"string","PgNumeric");this.config.precision=n,this.config.scale=t}build(o){return new GS(o,this.config)}}class GS extends r{static[J]="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 jF(o,n){let{name:t,config:T}=Ao(o,n);return new IF(t,T?.precision,T?.scale)}class bF extends N{static[J]="PgPointTupleBuilder";constructor(o){super(o,"array","PgPointTuple")}build(o){return new NF(o,this.config)}}class NF extends r{static[J]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(o){if(typeof o==="string"){let[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 hF extends N{static[J]="PgPointObjectBuilder";constructor(o){super(o,"json","PgPointObject")}build(o){return new cF(o,this.config)}}class cF extends r{static[J]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(o){if(typeof o==="string"){let[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 xF(o,n){let{name:t,config:T}=Ao(o,n);if(!T?.mode||T.mode==="tuple")return new bF(t);return new hF(t)}function gJ(o){let 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 iF(o,n){let t=new ArrayBuffer(8),T=new DataView(t);for(let S=0;S<8;S++)T.setUint8(S,o[n+S]);return T.getFloat64(0,!0)}function af(o){let n=gJ(o),t=0,T=n[t];t+=1;let S=new DataView(n.buffer),f=S.getUint32(t,T===1);t+=4;let y;if(f&536870912)y=S.getUint32(t,T===1),t+=4;if((f&65535)===1){let A=iF(n,t);t+=8;let M=iF(n,t);return t+=8,[A,M]}throw new Error("Unsupported geometry type")}class vF extends N{static[J]="PgGeometryBuilder";constructor(o){super(o,"array","PgGeometry")}build(o){return new pF(o,this.config)}}class pF extends r{static[J]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(o){return af(o)}mapToDriverValue(o){return`point(${o[0]} ${o[1]})`}}class qF extends N{static[J]="PgGeometryObjectBuilder";constructor(o){super(o,"json","PgGeometryObject")}build(o){return new ZF(o,this.config)}}class ZF extends r{static[J]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(o){let n=af(o);return{x:n[0],y:n[1]}}mapToDriverValue(o){return`point(${o.x} ${o.y})`}}function PF(o,n){let{name:t,config:T}=Ao(o,n);if(!T?.mode||T.mode==="tuple")return new vF(t);return new qF(t)}class eF extends N{static[J]="PgRealBuilder";constructor(o,n){super(o,"number","PgReal");this.config.length=n}build(o){return new lF(o,this.config)}}class lF extends r{static[J]="PgReal";constructor(o,n){super(o,n)}getSQLType(){return"real"}mapFromDriverValue=(o)=>{if(typeof o==="string")return Number.parseFloat(o);return o}}function gF(o){return new eF(o??"")}class dF extends N{static[J]="PgSerialBuilder";constructor(o){super(o,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new uF(o,this.config)}}class uF extends r{static[J]="PgSerial";getSQLType(){return"serial"}}function aF(o){return new dF(o??"")}class sF extends ot{static[J]="PgSmallIntBuilder";constructor(o){super(o,"number","PgSmallInt")}build(o){return new ok(o,this.config)}}class ok extends r{static[J]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(o)=>{if(typeof o==="string")return Number(o);return o}}function nk(o){return new sF(o??"")}class tk extends N{static[J]="PgSmallSerialBuilder";constructor(o){super(o,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new Tk(o,this.config)}}class Tk extends r{static[J]="PgSmallSerial";getSQLType(){return"smallserial"}}function Sk(o){return new tk(o??"")}class fk extends N{static[J]="PgTextBuilder";constructor(o,n){super(o,"string","PgText");this.config.enumValues=n.enum}build(o){return new yk(o,this.config)}}class yk extends r{static[J]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function Ak(o,n={}){let{name:t,config:T}=Ao(o,n);return new fk(t,T)}class Mk extends Zn{constructor(o,n,t){super(o,"string","PgTime");this.withTimezone=n,this.precision=t,this.config.withTimezone=n,this.config.precision=t}static[J]="PgTimeBuilder";build(o){return new zS(o,this.config)}}class zS extends r{static[J]="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 Fk(o,n={}){let{name:t,config:T}=Ao(o,n);return new Mk(t,T.withTimezone??!1,T.precision)}class kk extends Zn{static[J]="PgTimestampBuilder";constructor(o,n,t){super(o,"date","PgTimestamp");this.config.withTimezone=n,this.config.precision=t}build(o){return new HS(o,this.config)}}class HS extends r{static[J]="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 $k extends Zn{static[J]="PgTimestampStringBuilder";constructor(o,n,t){super(o,"string","PgTimestampString");this.config.withTimezone=n,this.config.precision=t}build(o){return new mS(o,this.config)}}class mS extends r{static[J]="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 Dn(o,n={}){let{name:t,config:T}=Ao(o,n);if(T?.mode==="string")return new $k(t,T.withTimezone??!1,T.precision);return new kk(t,T?.withTimezone??!1,T?.precision)}class Jk extends N{static[J]="PgUUIDBuilder";constructor(o){super(o,"string","PgUUID")}defaultRandom(){return this.default(R`gen_random_uuid()`)}build(o){return new QS(o,this.config)}}class QS extends r{static[J]="PgUUID";getSQLType(){return"uuid"}}function $n(o){return new Jk(o??"")}class Rk extends N{static[J]="PgVarcharBuilder";constructor(o,n){super(o,"string","PgVarchar");this.config.length=n.length,this.config.enumValues=n.enum}build(o){return new Wk(o,this.config)}}class Wk extends r{static[J]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function io(o,n={}){let{name:t,config:T}=Ao(o,n);return new Rk(t,T)}class Ok extends N{static[J]="PgBinaryVectorBuilder";constructor(o,n){super(o,"string","PgBinaryVector");this.config.dimensions=n.dimensions}build(o){return new _k(o,this.config)}}class _k extends r{static[J]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function wk(o,n){let{name:t,config:T}=Ao(o,n);return new Ok(t,T)}class Kk extends N{static[J]="PgHalfVectorBuilder";constructor(o,n){super(o,"array","PgHalfVector");this.config.dimensions=n.dimensions}build(o){return new Xk(o,this.config)}}class Xk extends r{static[J]="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 Ek(o,n){let{name:t,config:T}=Ao(o,n);return new Kk(t,T)}class Yk extends N{static[J]="PgSparseVectorBuilder";constructor(o,n){super(o,"string","PgSparseVector");this.config.dimensions=n.dimensions}build(o){return new Gk(o,this.config)}}class Gk extends r{static[J]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function zk(o,n){let{name:t,config:T}=Ao(o,n);return new Yk(t,T)}class Hk extends N{static[J]="PgVectorBuilder";constructor(o,n){super(o,"array","PgVector");this.config.dimensions=n.dimensions}build(o){return new mk(o,this.config)}}class mk extends r{static[J]="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 Qk(o,n){let{name:t,config:T}=Ao(o,n);return new Hk(t,T)}function Dk(){return{bigint:vM,bigserial:eM,boolean:ET,char:aM,cidr:nF,customType:SF,date:AF,doublePrecision:kF,inet:RF,integer:XS,interval:KF,json:EF,jsonb:GF,line:DF,macaddr:rF,macaddr8:LF,numeric:jF,point:xF,geometry:PF,real:gF,serial:aF,smallint:nk,smallserial:Sk,text:Ak,time:Fk,timestamp:Dn,uuid:$n,varchar:io,bit:wk,halfvec:Ek,sparsevec:zk,vector:Qk}}var sf=Symbol.for("drizzle:PgInlineForeignKeys"),Uk=Symbol.for("drizzle:EnableRLS");class Kn extends L{static[J]="PgTable";static Symbol=Object.assign({},L.Symbol,{InlineForeignKeys:sf,EnableRLS:Uk});[sf]=[];[Uk]=!1;[L.Symbol.ExtraConfigBuilder]=void 0}function dJ(o,n,t,T,S=o){let f=new Kn(o,T,S),y=typeof n==="function"?n(Dk()):n,A=Object.fromEntries(Object.entries(y).map(([k,W])=>{let O=W;O.setName(k);let E=O.build(f);return f[sf].push(...O.buildForeignKeys(E,f)),[k,E]})),M=Object.fromEntries(Object.entries(y).map(([k,W])=>{let O=W;O.setName(k);let E=O.buildExtraConfigColumn(f);return[k,E]})),F=Object.assign(f,A);if(F[L.Symbol.Columns]=A,F[L.Symbol.ExtraConfigColumns]=M,t)F[Kn.Symbol.ExtraConfigBuilder]=t;return Object.assign(F,{enableRLS:()=>{return F[Kn.Symbol.EnableRLS]=!0,F}})}var nt=(o,n,t)=>{return dJ(o,n,t,void 0)};function Vk(...o){if(o[0].columns)return new YT(o[0].columns,o[0].name);return new YT(o)}class YT{static[J]="PgPrimaryKeyBuilder";columns;name;constructor(o,n){this.columns=o,this.name=n}build(o){return new rk(o,this.columns,this.name)}}class rk{constructor(o,n,t){this.table=o,this.columns=n,this.name=t}static[J]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[Kn.Symbol.Name]}_${this.columns.map((o)=>o.name).join("_")}_pk`}}class oy{constructor(o,n,t){this.sourceTable=o,this.referencedTable=n,this.relationName=t,this.referencedTableName=n[L.Symbol.Name]}static[J]="Relation";referencedTableName;fieldName}class Bk{constructor(o,n){this.table=o,this.config=n}static[J]="Relations"}class tt extends oy{constructor(o,n,t,T){super(o,n,t?.relationName);this.config=t,this.isNullable=T}static[J]="One";withFieldName(o){let n=new tt(this.sourceTable,this.referencedTable,this.config,this.isNullable);return n.fieldName=o,n}}class GT extends oy{constructor(o,n,t){super(o,n,t?.relationName);this.config=t}static[J]="Many";withFieldName(o){let n=new GT(this.sourceTable,this.referencedTable,this.config);return n.fieldName=o,n}}function Ck(){return{and:XT,between:mM,eq:Ct,exists:zM,gt:OM,gte:_M,ilike:VM,inArray:XM,isNull:YM,isNotNull:GM,like:DM,lt:wM,lte:KM,ne:JM,not:WM,notBetween:QM,notExists:HM,notLike:UM,notIlike:rM,notInArray:EM,or:RM,sql:R}}function Lk(){return{sql:R,asc:BM,desc:CM}}function Ik(o,n){if(Object.keys(o).length===1&&"default"in o&&!X(o.default,L))o=o.default;let t={},T={},S={};for(let[f,y]of Object.entries(o))if(X(y,L)){let A=kt(y),M=T[A];t[A]=f,S[f]={tsName:f,dbName:y[L.Symbol.Name],schema:y[L.Symbol.Schema],columns:y[L.Symbol.Columns],relations:M?.relations??{},primaryKey:M?.primaryKey??[]};for(let k of Object.values(y[L.Symbol.Columns]))if(k.primary)S[f].primaryKey.push(k);let F=y[L.Symbol.ExtraConfigBuilder]?.(y[L.Symbol.ExtraConfigColumns]);if(F){for(let k of Object.values(F))if(X(k,YT))S[f].primaryKey.push(...k.columns)}}else if(X(y,Bk)){let A=kt(y.table),M=t[A],F=y.config(n(y.table)),k;for(let[W,O]of Object.entries(F))if(M){let E=S[M];if(E.relations[W]=O,k)E.primaryKey.push(...k)}else{if(!(A in T))T[A]={relations:{},primaryKey:k};T[A].relations[W]=O}}return{tables:S,tableNamesMap:t}}function uJ(o){return function n(t,T){return new tt(o,t,T,T?.fields.reduce((S,f)=>S&&f.notNull,!0)??!1)}}function aJ(o){return function n(t,T){return new GT(o,t,T)}}function jk(o,n,t){if(X(t,tt)&&t.config)return{fields:t.config.fields,references:t.config.references};let T=n[kt(t.referencedTable)];if(!T)throw new Error(`Table "${t.referencedTable[L.Symbol.Name]}" not found in schema`);let S=o[T];if(!S)throw new Error(`Table "${T}" not found in schema`);let f=t.sourceTable,y=n[kt(f)];if(!y)throw new Error(`Table "${f[L.Symbol.Name]}" not found in schema`);let A=[];for(let M of Object.values(S.relations))if(t.relationName&&t!==M&&M.relationName===t.relationName||!t.relationName&&M.referencedTable===t.sourceTable)A.push(M);if(A.length>1)throw t.relationName?new Error(`There are multiple relations with name "${t.relationName}" in table "${T}"`):new Error(`There are multiple relations between "${T}" and "${t.sourceTable[L.Symbol.Name]}". Please specify relation name`);if(A[0]&&X(A[0],tt)&&A[0].config)return{fields:A[0].config.references,references:A[0].config.fields};throw new Error(`There is not enough information to infer relation "${y}.${t.fieldName}"`)}function bk(o){return{one:uJ(o),many:aJ(o)}}function DS(o,n,t,T,S=(f)=>f){let f={};for(let[y,A]of T.entries())if(A.isJson){let M=n.relations[A.tsKey],F=t[y],k=typeof F==="string"?JSON.parse(F):F;f[A.tsKey]=X(M,tt)?k&&DS(o,o[A.relationTableTsKey],k,A.selection,S):k.map((W)=>DS(o,o[A.relationTableTsKey],W,A.selection,S))}else{let M=S(t[y]),F=A.field,k;if(X(F,Xo))k=F;else if(X(F,h))k=F.decoder;else k=F.sql.decoder;f[A.tsKey]=M===null?null:k.mapFromDriverValue(M)}return f}import{readFileSync as dk}from"fs";import{resolve as yy}from"path";var $o;(function(o){o.assertEqual=(S)=>S;function n(S){}o.assertIs=n;function t(S){throw new Error}o.assertNever=t,o.arrayToEnum=(S)=>{let f={};for(let y of S)f[y]=y;return f},o.getValidEnumValues=(S)=>{let f=o.objectKeys(S).filter((A)=>typeof S[S[A]]!=="number"),y={};for(let A of f)y[A]=S[A];return o.objectValues(y)},o.objectValues=(S)=>{return o.objectKeys(S).map(function(f){return S[f]})},o.objectKeys=typeof Object.keys==="function"?(S)=>Object.keys(S):(S)=>{let f=[];for(let y in S)if(Object.prototype.hasOwnProperty.call(S,y))f.push(y);return f},o.find=(S,f)=>{for(let y of S)if(f(y))return y;return},o.isInteger=typeof Number.isInteger==="function"?(S)=>Number.isInteger(S):(S)=>typeof S==="number"&&isFinite(S)&&Math.floor(S)===S;function T(S,f=" | "){return S.map((y)=>typeof y==="string"?`'${y}'`:y).join(f)}o.joinValues=T,o.jsonStringifyReplacer=(S,f)=>{if(typeof f==="bigint")return f.toString();return f}})($o||($o={}));var ty;(function(o){o.mergeShapes=(n,t)=>{return{...n,...t}}})(ty||(ty={}));var I=$o.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Tt=(o)=>{switch(typeof o){case"undefined":return I.undefined;case"string":return I.string;case"number":return isNaN(o)?I.nan:I.number;case"boolean":return I.boolean;case"function":return I.function;case"bigint":return I.bigint;case"symbol":return I.symbol;case"object":if(Array.isArray(o))return I.array;if(o===null)return I.null;if(o.then&&typeof o.then==="function"&&o.catch&&typeof o.catch==="function")return I.promise;if(typeof Map!=="undefined"&&o instanceof Map)return I.map;if(typeof Set!=="undefined"&&o instanceof Set)return I.set;if(typeof Date!=="undefined"&&o instanceof Date)return I.date;return I.object;default:return I.unknown}},m=$o.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"]),sJ=(o)=>{return JSON.stringify(o,null,2).replace(/"([^"]+)":/g,"$1:")};class Jn extends Error{constructor(o){super();this.issues=[],this.addIssue=(t)=>{this.issues=[...this.issues,t]},this.addIssues=(t=[])=>{this.issues=[...this.issues,...t]};let 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){let n=o||function(S){return S.message},t={_errors:[]},T=(S)=>{for(let f of S.issues)if(f.code==="invalid_union")f.unionErrors.map(T);else if(f.code==="invalid_return_type")T(f.returnTypeError);else if(f.code==="invalid_arguments")T(f.argumentsError);else if(f.path.length===0)t._errors.push(n(f));else{let y=t,A=0;while(A<f.path.length){let M=f.path[A];if(A!==f.path.length-1)y[M]=y[M]||{_errors:[]};else y[M]=y[M]||{_errors:[]},y[M]._errors.push(n(f));y=y[M],A++}}};return T(this),t}static assert(o){if(!(o instanceof Jn))throw new Error(`Not a ZodError: ${o}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,$o.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(o=(n)=>n.message){let n={},t=[];for(let T of this.issues)if(T.path.length>0)n[T.path[0]]=n[T.path[0]]||[],n[T.path[0]].push(o(T));else t.push(o(T));return{formErrors:t,fieldErrors:n}}get formErrors(){return this.flatten()}}Jn.create=(o)=>{return new Jn(o)};var bt=(o,n)=>{let t;switch(o.code){case m.invalid_type:if(o.received===I.undefined)t="Required";else t=`Expected ${o.expected}, received ${o.received}`;break;case m.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(o.expected,$o.jsonStringifyReplacer)}`;break;case m.unrecognized_keys:t=`Unrecognized key(s) in object: ${$o.joinValues(o.keys,", ")}`;break;case m.invalid_union:t="Invalid input";break;case m.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${$o.joinValues(o.options)}`;break;case m.invalid_enum_value:t=`Invalid enum value. Expected ${$o.joinValues(o.options)}, received '${o.received}'`;break;case m.invalid_arguments:t="Invalid function arguments";break;case m.invalid_return_type:t="Invalid function return type";break;case m.invalid_date:t="Invalid date";break;case m.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 $o.assertNever(o.validation);else if(o.validation!=="regex")t=`Invalid ${o.validation}`;else t="Invalid";break;case m.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 m.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 m.custom:t="Invalid input";break;case m.invalid_intersection_types:t="Intersection results could not be merged";break;case m.not_multiple_of:t=`Number must be a multiple of ${o.multipleOf}`;break;case m.not_finite:t="Number must be finite";break;default:t=n.defaultError,$o.assertNever(o)}return{message:t}},ck=bt;function oR(o){ck=o}function US(){return ck}var VS=(o)=>{let{data:n,path:t,errorMaps:T,issueData:S}=o,f=[...t,...S.path||[]],y={...S,path:f};if(S.message!==void 0)return{...S,path:f,message:S.message};let A="",M=T.filter((F)=>!!F).slice().reverse();for(let F of M)A=F(y,{data:n,defaultError:A}).message;return{...S,path:f,message:A}},nR=[];function C(o,n){let t=US(),T=VS({issueData:n,data:o.data,path:o.path,errorMaps:[o.common.contextualErrorMap,o.schemaErrorMap,t,t===bt?void 0:bt].filter((S)=>!!S)});o.common.issues.push(T)}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){let t=[];for(let T of n){if(T.status==="aborted")return u;if(T.status==="dirty")o.dirty();t.push(T.value)}return{status:o.value,value:t}}static async mergeObjectAsync(o,n){let t=[];for(let T of n){let S=await T.key,f=await T.value;t.push({key:S,value:f})}return lo.mergeObjectSync(o,t)}static mergeObjectSync(o,n){let t={};for(let T of n){let{key:S,value:f}=T;if(S.status==="aborted")return u;if(f.status==="aborted")return u;if(S.status==="dirty")o.dirty();if(f.status==="dirty")o.dirty();if(S.value!=="__proto__"&&(typeof f.value!=="undefined"||T.alwaysSet))t[S.value]=f.value}return{status:o.value,value:t}}}var u=Object.freeze({status:"aborted"}),It=(o)=>({status:"dirty",value:o}),on=(o)=>({status:"valid",value:o}),Ty=(o)=>o.status==="aborted",Sy=(o)=>o.status==="dirty",mT=(o)=>o.status==="valid",QT=(o)=>typeof Promise!=="undefined"&&o instanceof Promise;function rS(o,n,t,T){if(t==="a"&&!T)throw new TypeError("Private accessor was defined without a getter");if(typeof n==="function"?o!==n||!T:!n.has(o))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?T:t==="a"?T.call(o):T?T.value:n.get(o)}function xk(o,n,t,T,S){if(T==="m")throw new TypeError("Private method is not writable");if(T==="a"&&!S)throw new TypeError("Private accessor was defined without a setter");if(typeof n==="function"?o!==n||!S:!n.has(o))throw new TypeError("Cannot write private member to an object whose class did not declare it");return T==="a"?S.call(o,t):S?S.value=t:n.set(o,t),t}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 zT,HT;class Bn{constructor(o,n,t,T){this._cachedPath=[],this.parent=o,this.data=n,this._path=t,this._key=T}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 Nk=(o,n)=>{if(mT(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;let t=new Jn(o.common.issues);return this._error=t,this._error}}}};function to(o){if(!o)return{};let{errorMap:n,invalid_type_error:t,required_error:T,description:S}=o;if(n&&(t||T))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(n)return{errorMap:n,description:S};return{errorMap:(y,A)=>{var M,F;let{message:k}=o;if(y.code==="invalid_enum_value")return{message:k!==null&&k!==void 0?k:A.defaultError};if(typeof A.data==="undefined")return{message:(M=k!==null&&k!==void 0?k:T)!==null&&M!==void 0?M:A.defaultError};if(y.code!=="invalid_type")return{message:A.defaultError};return{message:(F=k!==null&&k!==void 0?k:t)!==null&&F!==void 0?F:A.defaultError}},description:S}}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 Tt(o.data)}_getOrReturnCtx(o,n){return n||{common:o.parent.common,data:o.data,parsedType:Tt(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:Tt(o.data),schemaErrorMap:this._def.errorMap,path:o.path,parent:o.parent}}}_parseSync(o){let n=this._parse(o);if(QT(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(o){let n=this._parse(o);return Promise.resolve(n)}parse(o,n){let t=this.safeParse(o,n);if(t.success)return t.data;throw t.error}safeParse(o,n){var t;let T={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:Tt(o)},S=this._parseSync({data:o,path:T.path,parent:T});return Nk(T,S)}async parseAsync(o,n){let t=await this.safeParseAsync(o,n);if(t.success)return t.data;throw t.error}async safeParseAsync(o,n){let 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:Tt(o)},T=this._parse({data:o,path:t.path,parent:t}),S=await(QT(T)?T:Promise.resolve(T));return Nk(t,S)}refine(o,n){let t=(T)=>{if(typeof n==="string"||typeof n==="undefined")return{message:n};else if(typeof n==="function")return n(T);else return n};return this._refinement((T,S)=>{let f=o(T),y=()=>S.addIssue({code:m.custom,...t(T)});if(typeof Promise!=="undefined"&&f instanceof Promise)return f.then((A)=>{if(!A)return y(),!1;else return!0});if(!f)return y(),!1;else return!0})}refinement(o,n){return this._refinement((t,T)=>{if(!o(t))return T.addIssue(typeof n==="function"?n(t,T):n),!1;else return!0})}_refinement(o){return new Xn({schema:this,typeName:g.ZodEffects,effect:{type:"refinement",refinement:o}})}superRefine(o){return this._refinement(o)}optional(){return rn.create(this,this._def)}nullable(){return en.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Vn.create(this,this._def)}promise(){return Wt.create(this,this._def)}or(o){return xt.create([this,o],this._def)}and(o){return it.create(this,o,this._def)}transform(o){return new Xn({...to(this._def),schema:this,typeName:g.ZodEffects,effect:{type:"transform",transform:o}})}default(o){let n=typeof o==="function"?o:()=>o;return new Zt({...to(this._def),innerType:this,defaultValue:n,typeName:g.ZodDefault})}brand(){return new CS({typeName:g.ZodBranded,type:this,...to(this._def)})}catch(o){let n=typeof o==="function"?o:()=>o;return new Pt({...to(this._def),innerType:this,catchValue:n,typeName:g.ZodCatch})}describe(o){return new this.constructor({...this._def,description:o})}pipe(o){return CT.create(this,o)}readonly(){return et.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var tR=/^c[^\s-]{8,}$/i,TR=/^[0-9a-z]+$/,SR=/^[0-9A-HJKMNP-TV-Z]{26}$/,fR=/^[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,yR=/^[a-z0-9_-]{21}$/i,AR=/^[-+]?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)?)??$/,MR=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,FR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ny,kR=/^(?:(?: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])$/,$R=/^(([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}=))?$/,ik="((\\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])))",RR=new RegExp(`^${ik}\$`);function vk(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 WR(o){return new RegExp(`^${vk(o)}\$`)}function pk(o){let n=`${ik}T${vk(o)}`,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 OR(o,n){if((n==="v4"||!n)&&kR.test(o))return!0;if((n==="v6"||!n)&&$R.test(o))return!0;return!1}class Un extends To{_parse(o){if(this._def.coerce)o.data=String(o.data);if(this._getType(o)!==I.string){let S=this._getOrReturnCtx(o);return C(S,{code:m.invalid_type,expected:I.string,received:S.parsedType}),u}let t=new lo,T=void 0;for(let S of this._def.checks)if(S.kind==="min"){if(o.data.length<S.value)T=this._getOrReturnCtx(o,T),C(T,{code:m.too_small,minimum:S.value,type:"string",inclusive:!0,exact:!1,message:S.message}),t.dirty()}else if(S.kind==="max"){if(o.data.length>S.value)T=this._getOrReturnCtx(o,T),C(T,{code:m.too_big,maximum:S.value,type:"string",inclusive:!0,exact:!1,message:S.message}),t.dirty()}else if(S.kind==="length"){let f=o.data.length>S.value,y=o.data.length<S.value;if(f||y){if(T=this._getOrReturnCtx(o,T),f)C(T,{code:m.too_big,maximum:S.value,type:"string",inclusive:!0,exact:!0,message:S.message});else if(y)C(T,{code:m.too_small,minimum:S.value,type:"string",inclusive:!0,exact:!0,message:S.message});t.dirty()}}else if(S.kind==="email"){if(!MR.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{validation:"email",code:m.invalid_string,message:S.message}),t.dirty()}else if(S.kind==="emoji"){if(!ny)ny=new RegExp(FR,"u");if(!ny.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{validation:"emoji",code:m.invalid_string,message:S.message}),t.dirty()}else if(S.kind==="uuid"){if(!fR.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{validation:"uuid",code:m.invalid_string,message:S.message}),t.dirty()}else if(S.kind==="nanoid"){if(!yR.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{validation:"nanoid",code:m.invalid_string,message:S.message}),t.dirty()}else if(S.kind==="cuid"){if(!tR.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{validation:"cuid",code:m.invalid_string,message:S.message}),t.dirty()}else if(S.kind==="cuid2"){if(!TR.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{validation:"cuid2",code:m.invalid_string,message:S.message}),t.dirty()}else if(S.kind==="ulid"){if(!SR.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{validation:"ulid",code:m.invalid_string,message:S.message}),t.dirty()}else if(S.kind==="url")try{new URL(o.data)}catch(f){T=this._getOrReturnCtx(o,T),C(T,{validation:"url",code:m.invalid_string,message:S.message}),t.dirty()}else if(S.kind==="regex"){if(S.regex.lastIndex=0,!S.regex.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{validation:"regex",code:m.invalid_string,message:S.message}),t.dirty()}else if(S.kind==="trim")o.data=o.data.trim();else if(S.kind==="includes"){if(!o.data.includes(S.value,S.position))T=this._getOrReturnCtx(o,T),C(T,{code:m.invalid_string,validation:{includes:S.value,position:S.position},message:S.message}),t.dirty()}else if(S.kind==="toLowerCase")o.data=o.data.toLowerCase();else if(S.kind==="toUpperCase")o.data=o.data.toUpperCase();else if(S.kind==="startsWith"){if(!o.data.startsWith(S.value))T=this._getOrReturnCtx(o,T),C(T,{code:m.invalid_string,validation:{startsWith:S.value},message:S.message}),t.dirty()}else if(S.kind==="endsWith"){if(!o.data.endsWith(S.value))T=this._getOrReturnCtx(o,T),C(T,{code:m.invalid_string,validation:{endsWith:S.value},message:S.message}),t.dirty()}else if(S.kind==="datetime"){if(!pk(S).test(o.data))T=this._getOrReturnCtx(o,T),C(T,{code:m.invalid_string,validation:"datetime",message:S.message}),t.dirty()}else if(S.kind==="date"){if(!RR.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{code:m.invalid_string,validation:"date",message:S.message}),t.dirty()}else if(S.kind==="time"){if(!WR(S).test(o.data))T=this._getOrReturnCtx(o,T),C(T,{code:m.invalid_string,validation:"time",message:S.message}),t.dirty()}else if(S.kind==="duration"){if(!AR.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{validation:"duration",code:m.invalid_string,message:S.message}),t.dirty()}else if(S.kind==="ip"){if(!OR(o.data,S.version))T=this._getOrReturnCtx(o,T),C(T,{validation:"ip",code:m.invalid_string,message:S.message}),t.dirty()}else if(S.kind==="base64"){if(!JR.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{validation:"base64",code:m.invalid_string,message:S.message}),t.dirty()}else $o.assertNever(S);return{status:t.value,value:o.data}}_regex(o,n,t){return this.refinement((T)=>o.test(T),{validation:n,code:m.invalid_string,...q.errToObj(t)})}_addCheck(o){return new Un({...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 Un({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Un({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Un({...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}}Un.create=(o)=>{var n;return new Un({checks:[],typeName:g.ZodString,coerce:(n=o===null||o===void 0?void 0:o.coerce)!==null&&n!==void 0?n:!1,...to(o)})};function _R(o,n){let t=(o.toString().split(".")[1]||"").length,T=(n.toString().split(".")[1]||"").length,S=t>T?t:T,f=parseInt(o.toFixed(S).replace(".","")),y=parseInt(n.toFixed(S).replace(".",""));return f%y/Math.pow(10,S)}class ft 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)!==I.number){let S=this._getOrReturnCtx(o);return C(S,{code:m.invalid_type,expected:I.number,received:S.parsedType}),u}let t=void 0,T=new lo;for(let S of this._def.checks)if(S.kind==="int"){if(!$o.isInteger(o.data))t=this._getOrReturnCtx(o,t),C(t,{code:m.invalid_type,expected:"integer",received:"float",message:S.message}),T.dirty()}else if(S.kind==="min"){if(S.inclusive?o.data<S.value:o.data<=S.value)t=this._getOrReturnCtx(o,t),C(t,{code:m.too_small,minimum:S.value,type:"number",inclusive:S.inclusive,exact:!1,message:S.message}),T.dirty()}else if(S.kind==="max"){if(S.inclusive?o.data>S.value:o.data>=S.value)t=this._getOrReturnCtx(o,t),C(t,{code:m.too_big,maximum:S.value,type:"number",inclusive:S.inclusive,exact:!1,message:S.message}),T.dirty()}else if(S.kind==="multipleOf"){if(_R(o.data,S.value)!==0)t=this._getOrReturnCtx(o,t),C(t,{code:m.not_multiple_of,multipleOf:S.value,message:S.message}),T.dirty()}else if(S.kind==="finite"){if(!Number.isFinite(o.data))t=this._getOrReturnCtx(o,t),C(t,{code:m.not_finite,message:S.message}),T.dirty()}else $o.assertNever(S);return{status:T.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,T){return new ft({...this._def,checks:[...this._def.checks,{kind:o,value:n,inclusive:t,message:q.toString(T)}]})}_addCheck(o){return new ft({...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"&&$o.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)}}ft.create=(o)=>{return new ft({checks:[],typeName:g.ZodNumber,coerce:(o===null||o===void 0?void 0:o.coerce)||!1,...to(o)})};class yt 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)!==I.bigint){let S=this._getOrReturnCtx(o);return C(S,{code:m.invalid_type,expected:I.bigint,received:S.parsedType}),u}let t=void 0,T=new lo;for(let S of this._def.checks)if(S.kind==="min"){if(S.inclusive?o.data<S.value:o.data<=S.value)t=this._getOrReturnCtx(o,t),C(t,{code:m.too_small,type:"bigint",minimum:S.value,inclusive:S.inclusive,message:S.message}),T.dirty()}else if(S.kind==="max"){if(S.inclusive?o.data>S.value:o.data>=S.value)t=this._getOrReturnCtx(o,t),C(t,{code:m.too_big,type:"bigint",maximum:S.value,inclusive:S.inclusive,message:S.message}),T.dirty()}else if(S.kind==="multipleOf"){if(o.data%S.value!==BigInt(0))t=this._getOrReturnCtx(o,t),C(t,{code:m.not_multiple_of,multipleOf:S.value,message:S.message}),T.dirty()}else $o.assertNever(S);return{status:T.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,T){return new yt({...this._def,checks:[...this._def.checks,{kind:o,value:n,inclusive:t,message:q.toString(T)}]})}_addCheck(o){return new yt({...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}}yt.create=(o)=>{var n;return new yt({checks:[],typeName:g.ZodBigInt,coerce:(n=o===null||o===void 0?void 0:o.coerce)!==null&&n!==void 0?n:!1,...to(o)})};class Nt extends To{_parse(o){if(this._def.coerce)o.data=Boolean(o.data);if(this._getType(o)!==I.boolean){let t=this._getOrReturnCtx(o);return C(t,{code:m.invalid_type,expected:I.boolean,received:t.parsedType}),u}return on(o.data)}}Nt.create=(o)=>{return new Nt({typeName:g.ZodBoolean,coerce:(o===null||o===void 0?void 0:o.coerce)||!1,...to(o)})};class $t extends To{_parse(o){if(this._def.coerce)o.data=new Date(o.data);if(this._getType(o)!==I.date){let S=this._getOrReturnCtx(o);return C(S,{code:m.invalid_type,expected:I.date,received:S.parsedType}),u}if(isNaN(o.data.getTime())){let S=this._getOrReturnCtx(o);return C(S,{code:m.invalid_date}),u}let t=new lo,T=void 0;for(let S of this._def.checks)if(S.kind==="min"){if(o.data.getTime()<S.value)T=this._getOrReturnCtx(o,T),C(T,{code:m.too_small,message:S.message,inclusive:!0,exact:!1,minimum:S.value,type:"date"}),t.dirty()}else if(S.kind==="max"){if(o.data.getTime()>S.value)T=this._getOrReturnCtx(o,T),C(T,{code:m.too_big,message:S.message,inclusive:!0,exact:!1,maximum:S.value,type:"date"}),t.dirty()}else $o.assertNever(S);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:g.ZodDate,...to(o)})};class DT extends To{_parse(o){if(this._getType(o)!==I.symbol){let t=this._getOrReturnCtx(o);return C(t,{code:m.invalid_type,expected:I.symbol,received:t.parsedType}),u}return on(o.data)}}DT.create=(o)=>{return new DT({typeName:g.ZodSymbol,...to(o)})};class ht extends To{_parse(o){if(this._getType(o)!==I.undefined){let t=this._getOrReturnCtx(o);return C(t,{code:m.invalid_type,expected:I.undefined,received:t.parsedType}),u}return on(o.data)}}ht.create=(o)=>{return new ht({typeName:g.ZodUndefined,...to(o)})};class ct extends To{_parse(o){if(this._getType(o)!==I.null){let t=this._getOrReturnCtx(o);return C(t,{code:m.invalid_type,expected:I.null,received:t.parsedType}),u}return on(o.data)}}ct.create=(o)=>{return new ct({typeName:g.ZodNull,...to(o)})};class Jt extends To{constructor(){super(...arguments);this._any=!0}_parse(o){return on(o.data)}}Jt.create=(o)=>{return new Jt({typeName:g.ZodAny,...to(o)})};class St extends To{constructor(){super(...arguments);this._unknown=!0}_parse(o){return on(o.data)}}St.create=(o)=>{return new St({typeName:g.ZodUnknown,...to(o)})};class Nn extends To{_parse(o){let n=this._getOrReturnCtx(o);return C(n,{code:m.invalid_type,expected:I.never,received:n.parsedType}),u}}Nn.create=(o)=>{return new Nn({typeName:g.ZodNever,...to(o)})};class UT extends To{_parse(o){if(this._getType(o)!==I.undefined){let t=this._getOrReturnCtx(o);return C(t,{code:m.invalid_type,expected:I.void,received:t.parsedType}),u}return on(o.data)}}UT.create=(o)=>{return new UT({typeName:g.ZodVoid,...to(o)})};class Vn extends To{_parse(o){let{ctx:n,status:t}=this._processInputParams(o),T=this._def;if(n.parsedType!==I.array)return C(n,{code:m.invalid_type,expected:I.array,received:n.parsedType}),u;if(T.exactLength!==null){let f=n.data.length>T.exactLength.value,y=n.data.length<T.exactLength.value;if(f||y)C(n,{code:f?m.too_big:m.too_small,minimum:y?T.exactLength.value:void 0,maximum:f?T.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:T.exactLength.message}),t.dirty()}if(T.minLength!==null){if(n.data.length<T.minLength.value)C(n,{code:m.too_small,minimum:T.minLength.value,type:"array",inclusive:!0,exact:!1,message:T.minLength.message}),t.dirty()}if(T.maxLength!==null){if(n.data.length>T.maxLength.value)C(n,{code:m.too_big,maximum:T.maxLength.value,type:"array",inclusive:!0,exact:!1,message:T.maxLength.message}),t.dirty()}if(n.common.async)return Promise.all([...n.data].map((f,y)=>{return T.type._parseAsync(new Bn(n,f,n.path,y))})).then((f)=>{return lo.mergeArray(t,f)});let S=[...n.data].map((f,y)=>{return T.type._parseSync(new Bn(n,f,n.path,y))});return lo.mergeArray(t,S)}get element(){return this._def.type}min(o,n){return new Vn({...this._def,minLength:{value:o,message:q.toString(n)}})}max(o,n){return new Vn({...this._def,maxLength:{value:o,message:q.toString(n)}})}length(o,n){return new Vn({...this._def,exactLength:{value:o,message:q.toString(n)}})}nonempty(o){return this.min(1,o)}}Vn.create=(o,n)=>{return new Vn({type:o,minLength:null,maxLength:null,exactLength:null,typeName:g.ZodArray,...to(n)})};function Lt(o){if(o instanceof Uo){let n={};for(let t in o.shape){let T=o.shape[t];n[t]=rn.create(Lt(T))}return new Uo({...o._def,shape:()=>n})}else if(o instanceof Vn)return new Vn({...o._def,type:Lt(o.element)});else if(o instanceof rn)return rn.create(Lt(o.unwrap()));else if(o instanceof en)return en.create(Lt(o.unwrap()));else if(o instanceof hn)return hn.create(o.items.map((n)=>Lt(n)));else return o}class Uo extends To{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let o=this._def.shape(),n=$o.objectKeys(o);return this._cached={shape:o,keys:n}}_parse(o){if(this._getType(o)!==I.object){let M=this._getOrReturnCtx(o);return C(M,{code:m.invalid_type,expected:I.object,received:M.parsedType}),u}let{status:t,ctx:T}=this._processInputParams(o),{shape:S,keys:f}=this._getCached(),y=[];if(!(this._def.catchall instanceof Nn&&this._def.unknownKeys==="strip")){for(let M in T.data)if(!f.includes(M))y.push(M)}let A=[];for(let M of f){let F=S[M],k=T.data[M];A.push({key:{status:"valid",value:M},value:F._parse(new Bn(T,k,T.path,M)),alwaysSet:M in T.data})}if(this._def.catchall instanceof Nn){let M=this._def.unknownKeys;if(M==="passthrough")for(let F of y)A.push({key:{status:"valid",value:F},value:{status:"valid",value:T.data[F]}});else if(M==="strict"){if(y.length>0)C(T,{code:m.unrecognized_keys,keys:y}),t.dirty()}else if(M==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let M=this._def.catchall;for(let F of y){let k=T.data[F];A.push({key:{status:"valid",value:F},value:M._parse(new Bn(T,k,T.path,F)),alwaysSet:F in T.data})}}if(T.common.async)return Promise.resolve().then(async()=>{let M=[];for(let F of A){let k=await F.key,W=await F.value;M.push({key:k,value:W,alwaysSet:F.alwaysSet})}return M}).then((M)=>{return lo.mergeObjectSync(t,M)});else return lo.mergeObjectSync(t,A)}get shape(){return this._def.shape()}strict(o){return q.errToObj,new Uo({...this._def,unknownKeys:"strict",...o!==void 0?{errorMap:(n,t)=>{var T,S,f,y;let A=(f=(S=(T=this._def).errorMap)===null||S===void 0?void 0:S.call(T,n,t).message)!==null&&f!==void 0?f:t.defaultError;if(n.code==="unrecognized_keys")return{message:(y=q.errToObj(o).message)!==null&&y!==void 0?y:A};return{message:A}}}:{}})}strip(){return new Uo({...this._def,unknownKeys:"strip"})}passthrough(){return new Uo({...this._def,unknownKeys:"passthrough"})}extend(o){return new Uo({...this._def,shape:()=>({...this._def.shape(),...o})})}merge(o){return new Uo({unknownKeys:o._def.unknownKeys,catchall:o._def.catchall,shape:()=>({...this._def.shape(),...o._def.shape()}),typeName:g.ZodObject})}setKey(o,n){return this.augment({[o]:n})}catchall(o){return new Uo({...this._def,catchall:o})}pick(o){let n={};return $o.objectKeys(o).forEach((t)=>{if(o[t]&&this.shape[t])n[t]=this.shape[t]}),new Uo({...this._def,shape:()=>n})}omit(o){let n={};return $o.objectKeys(this.shape).forEach((t)=>{if(!o[t])n[t]=this.shape[t]}),new Uo({...this._def,shape:()=>n})}deepPartial(){return Lt(this)}partial(o){let n={};return $o.objectKeys(this.shape).forEach((t)=>{let T=this.shape[t];if(o&&!o[t])n[t]=T;else n[t]=T.optional()}),new Uo({...this._def,shape:()=>n})}required(o){let n={};return $o.objectKeys(this.shape).forEach((t)=>{if(o&&!o[t])n[t]=this.shape[t];else{let S=this.shape[t];while(S instanceof rn)S=S._def.innerType;n[t]=S}}),new Uo({...this._def,shape:()=>n})}keyof(){return qk($o.objectKeys(this.shape))}}Uo.create=(o,n)=>{return new Uo({shape:()=>o,unknownKeys:"strip",catchall:Nn.create(),typeName:g.ZodObject,...to(n)})};Uo.strictCreate=(o,n)=>{return new Uo({shape:()=>o,unknownKeys:"strict",catchall:Nn.create(),typeName:g.ZodObject,...to(n)})};Uo.lazycreate=(o,n)=>{return new Uo({shape:o,unknownKeys:"strip",catchall:Nn.create(),typeName:g.ZodObject,...to(n)})};class xt extends To{_parse(o){let{ctx:n}=this._processInputParams(o),t=this._def.options;function T(S){for(let y of S)if(y.result.status==="valid")return y.result;for(let y of S)if(y.result.status==="dirty")return n.common.issues.push(...y.ctx.common.issues),y.result;let f=S.map((y)=>new Jn(y.ctx.common.issues));return C(n,{code:m.invalid_union,unionErrors:f}),u}if(n.common.async)return Promise.all(t.map(async(S)=>{let f={...n,common:{...n.common,issues:[]},parent:null};return{result:await S._parseAsync({data:n.data,path:n.path,parent:f}),ctx:f}})).then(T);else{let S=void 0,f=[];for(let A of t){let M={...n,common:{...n.common,issues:[]},parent:null},F=A._parseSync({data:n.data,path:n.path,parent:M});if(F.status==="valid")return F;else if(F.status==="dirty"&&!S)S={result:F,ctx:M};if(M.common.issues.length)f.push(M.common.issues)}if(S)return n.common.issues.push(...S.ctx.common.issues),S.result;let y=f.map((A)=>new Jn(A));return C(n,{code:m.invalid_union,unionErrors:y}),u}}get options(){return this._def.options}}xt.create=(o,n)=>{return new xt({options:o,typeName:g.ZodUnion,...to(n)})};var Pn=(o)=>{if(o instanceof vt)return Pn(o.schema);else if(o instanceof Xn)return Pn(o.innerType());else if(o instanceof pt)return[o.value];else if(o instanceof At)return o.options;else if(o instanceof qt)return $o.objectValues(o.enum);else if(o instanceof Zt)return Pn(o._def.innerType);else if(o instanceof ht)return[void 0];else if(o instanceof ct)return[null];else if(o instanceof rn)return[void 0,...Pn(o.unwrap())];else if(o instanceof en)return[null,...Pn(o.unwrap())];else if(o instanceof CS)return Pn(o.unwrap());else if(o instanceof et)return Pn(o.unwrap());else if(o instanceof Pt)return Pn(o._def.innerType);else return[]};class BS extends To{_parse(o){let{ctx:n}=this._processInputParams(o);if(n.parsedType!==I.object)return C(n,{code:m.invalid_type,expected:I.object,received:n.parsedType}),u;let t=this.discriminator,T=n.data[t],S=this.optionsMap.get(T);if(!S)return C(n,{code:m.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[t]}),u;if(n.common.async)return S._parseAsync({data:n.data,path:n.path,parent:n});else return S._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){let T=new Map;for(let S of n){let f=Pn(S.shape[o]);if(!f.length)throw new Error(`A discriminator value for key \`${o}\` could not be extracted from all schema options`);for(let y of f){if(T.has(y))throw new Error(`Discriminator property ${String(o)} has duplicate value ${String(y)}`);T.set(y,S)}}return new BS({typeName:g.ZodDiscriminatedUnion,discriminator:o,options:n,optionsMap:T,...to(t)})}}function fy(o,n){let t=Tt(o),T=Tt(n);if(o===n)return{valid:!0,data:o};else if(t===I.object&&T===I.object){let S=$o.objectKeys(n),f=$o.objectKeys(o).filter((A)=>S.indexOf(A)!==-1),y={...o,...n};for(let A of f){let M=fy(o[A],n[A]);if(!M.valid)return{valid:!1};y[A]=M.data}return{valid:!0,data:y}}else if(t===I.array&&T===I.array){if(o.length!==n.length)return{valid:!1};let S=[];for(let f=0;f<o.length;f++){let y=o[f],A=n[f],M=fy(y,A);if(!M.valid)return{valid:!1};S.push(M.data)}return{valid:!0,data:S}}else if(t===I.date&&T===I.date&&+o===+n)return{valid:!0,data:o};else return{valid:!1}}class it extends To{_parse(o){let{status:n,ctx:t}=this._processInputParams(o),T=(S,f)=>{if(Ty(S)||Ty(f))return u;let y=fy(S.value,f.value);if(!y.valid)return C(t,{code:m.invalid_intersection_types}),u;if(Sy(S)||Sy(f))n.dirty();return{status:n.value,value:y.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(([S,f])=>T(S,f));else return T(this._def.left._parseSync({data:t.data,path:t.path,parent:t}),this._def.right._parseSync({data:t.data,path:t.path,parent:t}))}}it.create=(o,n,t)=>{return new it({left:o,right:n,typeName:g.ZodIntersection,...to(t)})};class hn extends To{_parse(o){let{status:n,ctx:t}=this._processInputParams(o);if(t.parsedType!==I.array)return C(t,{code:m.invalid_type,expected:I.array,received:t.parsedType}),u;if(t.data.length<this._def.items.length)return C(t,{code:m.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),u;if(!this._def.rest&&t.data.length>this._def.items.length)C(t,{code:m.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty();let S=[...t.data].map((f,y)=>{let A=this._def.items[y]||this._def.rest;if(!A)return null;return A._parse(new Bn(t,f,t.path,y))}).filter((f)=>!!f);if(t.common.async)return Promise.all(S).then((f)=>{return lo.mergeArray(n,f)});else return lo.mergeArray(n,S)}get items(){return this._def.items}rest(o){return new hn({...this._def,rest:o})}}hn.create=(o,n)=>{if(!Array.isArray(o))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new hn({items:o,typeName:g.ZodTuple,rest:null,...to(n)})};class VT extends To{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(o){let{status:n,ctx:t}=this._processInputParams(o);if(t.parsedType!==I.object)return C(t,{code:m.invalid_type,expected:I.object,received:t.parsedType}),u;let T=[],S=this._def.keyType,f=this._def.valueType;for(let y in t.data)T.push({key:S._parse(new Bn(t,y,t.path,y)),value:f._parse(new Bn(t,t.data[y],t.path,y)),alwaysSet:y in t.data});if(t.common.async)return lo.mergeObjectAsync(n,T);else return lo.mergeObjectSync(n,T)}get element(){return this._def.valueType}static create(o,n,t){if(n instanceof To)return new VT({keyType:o,valueType:n,typeName:g.ZodRecord,...to(t)});return new VT({keyType:Un.create(),valueType:o,typeName:g.ZodRecord,...to(n)})}}class rT extends To{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(o){let{status:n,ctx:t}=this._processInputParams(o);if(t.parsedType!==I.map)return C(t,{code:m.invalid_type,expected:I.map,received:t.parsedType}),u;let T=this._def.keyType,S=this._def.valueType,f=[...t.data.entries()].map(([y,A],M)=>{return{key:T._parse(new Bn(t,y,t.path,[M,"key"])),value:S._parse(new Bn(t,A,t.path,[M,"value"]))}});if(t.common.async){let y=new Map;return Promise.resolve().then(async()=>{for(let A of f){let M=await A.key,F=await A.value;if(M.status==="aborted"||F.status==="aborted")return u;if(M.status==="dirty"||F.status==="dirty")n.dirty();y.set(M.value,F.value)}return{status:n.value,value:y}})}else{let y=new Map;for(let A of f){let{key:M,value:F}=A;if(M.status==="aborted"||F.status==="aborted")return u;if(M.status==="dirty"||F.status==="dirty")n.dirty();y.set(M.value,F.value)}return{status:n.value,value:y}}}}rT.create=(o,n,t)=>{return new rT({valueType:n,keyType:o,typeName:g.ZodMap,...to(t)})};class Rt extends To{_parse(o){let{status:n,ctx:t}=this._processInputParams(o);if(t.parsedType!==I.set)return C(t,{code:m.invalid_type,expected:I.set,received:t.parsedType}),u;let T=this._def;if(T.minSize!==null){if(t.data.size<T.minSize.value)C(t,{code:m.too_small,minimum:T.minSize.value,type:"set",inclusive:!0,exact:!1,message:T.minSize.message}),n.dirty()}if(T.maxSize!==null){if(t.data.size>T.maxSize.value)C(t,{code:m.too_big,maximum:T.maxSize.value,type:"set",inclusive:!0,exact:!1,message:T.maxSize.message}),n.dirty()}let S=this._def.valueType;function f(A){let M=new Set;for(let F of A){if(F.status==="aborted")return u;if(F.status==="dirty")n.dirty();M.add(F.value)}return{status:n.value,value:M}}let y=[...t.data.values()].map((A,M)=>S._parse(new Bn(t,A,t.path,M)));if(t.common.async)return Promise.all(y).then((A)=>f(A));else return f(y)}min(o,n){return new Rt({...this._def,minSize:{value:o,message:q.toString(n)}})}max(o,n){return new Rt({...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)}}Rt.create=(o,n)=>{return new Rt({valueType:o,minSize:null,maxSize:null,typeName:g.ZodSet,...to(n)})};class jt extends To{constructor(){super(...arguments);this.validate=this.implement}_parse(o){let{ctx:n}=this._processInputParams(o);if(n.parsedType!==I.function)return C(n,{code:m.invalid_type,expected:I.function,received:n.parsedType}),u;function t(y,A){return VS({data:y,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,US(),bt].filter((M)=>!!M),issueData:{code:m.invalid_arguments,argumentsError:A}})}function T(y,A){return VS({data:y,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,US(),bt].filter((M)=>!!M),issueData:{code:m.invalid_return_type,returnTypeError:A}})}let S={errorMap:n.common.contextualErrorMap},f=n.data;if(this._def.returns instanceof Wt){let y=this;return on(async function(...A){let M=new Jn([]),F=await y._def.args.parseAsync(A,S).catch((O)=>{throw M.addIssue(t(A,O)),M}),k=await Reflect.apply(f,this,F);return await y._def.returns._def.type.parseAsync(k,S).catch((O)=>{throw M.addIssue(T(k,O)),M})})}else{let y=this;return on(function(...A){let M=y._def.args.safeParse(A,S);if(!M.success)throw new Jn([t(A,M.error)]);let F=Reflect.apply(f,this,M.data),k=y._def.returns.safeParse(F,S);if(!k.success)throw new Jn([T(F,k.error)]);return k.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...o){return new jt({...this._def,args:hn.create(o).rest(St.create())})}returns(o){return new jt({...this._def,returns:o})}implement(o){return this.parse(o)}strictImplement(o){return this.parse(o)}static create(o,n,t){return new jt({args:o?o:hn.create([]).rest(St.create()),returns:n||St.create(),typeName:g.ZodFunction,...to(t)})}}class vt extends To{get schema(){return this._def.getter()}_parse(o){let{ctx:n}=this._processInputParams(o);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}vt.create=(o,n)=>{return new vt({getter:o,typeName:g.ZodLazy,...to(n)})};class pt extends To{_parse(o){if(o.data!==this._def.value){let n=this._getOrReturnCtx(o);return C(n,{received:n.data,code:m.invalid_literal,expected:this._def.value}),u}return{status:"valid",value:o.data}}get value(){return this._def.value}}pt.create=(o,n)=>{return new pt({value:o,typeName:g.ZodLiteral,...to(n)})};function qk(o,n){return new At({values:o,typeName:g.ZodEnum,...to(n)})}class At extends To{constructor(){super(...arguments);zT.set(this,void 0)}_parse(o){if(typeof o.data!=="string"){let n=this._getOrReturnCtx(o),t=this._def.values;return C(n,{expected:$o.joinValues(t),received:n.parsedType,code:m.invalid_type}),u}if(!rS(this,zT,"f"))xk(this,zT,new Set(this._def.values),"f");if(!rS(this,zT,"f").has(o.data)){let n=this._getOrReturnCtx(o),t=this._def.values;return C(n,{received:n.data,code:m.invalid_enum_value,options:t}),u}return on(o.data)}get options(){return this._def.values}get enum(){let o={};for(let n of this._def.values)o[n]=n;return o}get Values(){let o={};for(let n of this._def.values)o[n]=n;return o}get Enum(){let o={};for(let n of this._def.values)o[n]=n;return o}extract(o,n=this._def){return At.create(o,{...this._def,...n})}exclude(o,n=this._def){return At.create(this.options.filter((t)=>!o.includes(t)),{...this._def,...n})}}zT=new WeakMap;At.create=qk;class qt extends To{constructor(){super(...arguments);HT.set(this,void 0)}_parse(o){let n=$o.getValidEnumValues(this._def.values),t=this._getOrReturnCtx(o);if(t.parsedType!==I.string&&t.parsedType!==I.number){let T=$o.objectValues(n);return C(t,{expected:$o.joinValues(T),received:t.parsedType,code:m.invalid_type}),u}if(!rS(this,HT,"f"))xk(this,HT,new Set($o.getValidEnumValues(this._def.values)),"f");if(!rS(this,HT,"f").has(o.data)){let T=$o.objectValues(n);return C(t,{received:t.data,code:m.invalid_enum_value,options:T}),u}return on(o.data)}get enum(){return this._def.values}}HT=new WeakMap;qt.create=(o,n)=>{return new qt({values:o,typeName:g.ZodNativeEnum,...to(n)})};class Wt extends To{unwrap(){return this._def.type}_parse(o){let{ctx:n}=this._processInputParams(o);if(n.parsedType!==I.promise&&n.common.async===!1)return C(n,{code:m.invalid_type,expected:I.promise,received:n.parsedType}),u;let t=n.parsedType===I.promise?n.data:Promise.resolve(n.data);return on(t.then((T)=>{return this._def.type.parseAsync(T,{path:n.path,errorMap:n.common.contextualErrorMap})}))}}Wt.create=(o,n)=>{return new Wt({type:o,typeName:g.ZodPromise,...to(n)})};class Xn extends To{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===g.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(o){let{status:n,ctx:t}=this._processInputParams(o),T=this._def.effect||null,S={addIssue:(f)=>{if(C(t,f),f.fatal)n.abort();else n.dirty()},get path(){return t.path}};if(S.addIssue=S.addIssue.bind(S),T.type==="preprocess"){let f=T.transform(t.data,S);if(t.common.async)return Promise.resolve(f).then(async(y)=>{if(n.value==="aborted")return u;let A=await this._def.schema._parseAsync({data:y,path:t.path,parent:t});if(A.status==="aborted")return u;if(A.status==="dirty")return It(A.value);if(n.value==="dirty")return It(A.value);return A});else{if(n.value==="aborted")return u;let y=this._def.schema._parseSync({data:f,path:t.path,parent:t});if(y.status==="aborted")return u;if(y.status==="dirty")return It(y.value);if(n.value==="dirty")return It(y.value);return y}}if(T.type==="refinement"){let f=(y)=>{let A=T.refinement(y,S);if(t.common.async)return Promise.resolve(A);if(A instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return y};if(t.common.async===!1){let y=this._def.schema._parseSync({data:t.data,path:t.path,parent:t});if(y.status==="aborted")return u;if(y.status==="dirty")n.dirty();return f(y.value),{status:n.value,value:y.value}}else return this._def.schema._parseAsync({data:t.data,path:t.path,parent:t}).then((y)=>{if(y.status==="aborted")return u;if(y.status==="dirty")n.dirty();return f(y.value).then(()=>{return{status:n.value,value:y.value}})})}if(T.type==="transform")if(t.common.async===!1){let f=this._def.schema._parseSync({data:t.data,path:t.path,parent:t});if(!mT(f))return f;let y=T.transform(f.value,S);if(y instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:y}}else return this._def.schema._parseAsync({data:t.data,path:t.path,parent:t}).then((f)=>{if(!mT(f))return f;return Promise.resolve(T.transform(f.value,S)).then((y)=>({status:n.value,value:y}))});$o.assertNever(T)}}Xn.create=(o,n,t)=>{return new Xn({schema:o,typeName:g.ZodEffects,effect:n,...to(t)})};Xn.createWithPreprocess=(o,n,t)=>{return new Xn({schema:n,effect:{type:"preprocess",transform:o},typeName:g.ZodEffects,...to(t)})};class rn extends To{_parse(o){if(this._getType(o)===I.undefined)return on(void 0);return this._def.innerType._parse(o)}unwrap(){return this._def.innerType}}rn.create=(o,n)=>{return new rn({innerType:o,typeName:g.ZodOptional,...to(n)})};class en extends To{_parse(o){if(this._getType(o)===I.null)return on(null);return this._def.innerType._parse(o)}unwrap(){return this._def.innerType}}en.create=(o,n)=>{return new en({innerType:o,typeName:g.ZodNullable,...to(n)})};class Zt extends To{_parse(o){let{ctx:n}=this._processInputParams(o),t=n.data;if(n.parsedType===I.undefined)t=this._def.defaultValue();return this._def.innerType._parse({data:t,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Zt.create=(o,n)=>{return new Zt({innerType:o,typeName:g.ZodDefault,defaultValue:typeof n.default==="function"?n.default:()=>n.default,...to(n)})};class Pt extends To{_parse(o){let{ctx:n}=this._processInputParams(o),t={...n,common:{...n.common,issues:[]}},T=this._def.innerType._parse({data:t.data,path:t.path,parent:{...t}});if(QT(T))return T.then((S)=>{return{status:"valid",value:S.status==="valid"?S.value:this._def.catchValue({get error(){return new Jn(t.common.issues)},input:t.data})}});else return{status:"valid",value:T.status==="valid"?T.value:this._def.catchValue({get error(){return new Jn(t.common.issues)},input:t.data})}}removeCatch(){return this._def.innerType}}Pt.create=(o,n)=>{return new Pt({innerType:o,typeName:g.ZodCatch,catchValue:typeof n.catch==="function"?n.catch:()=>n.catch,...to(n)})};class BT extends To{_parse(o){if(this._getType(o)!==I.nan){let t=this._getOrReturnCtx(o);return C(t,{code:m.invalid_type,expected:I.nan,received:t.parsedType}),u}return{status:"valid",value:o.data}}}BT.create=(o)=>{return new BT({typeName:g.ZodNaN,...to(o)})};var wR=Symbol("zod_brand");class CS extends To{_parse(o){let{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 CT extends To{_parse(o){let{status:n,ctx:t}=this._processInputParams(o);if(t.common.async)return(async()=>{let S=await this._def.in._parseAsync({data:t.data,path:t.path,parent:t});if(S.status==="aborted")return u;if(S.status==="dirty")return n.dirty(),It(S.value);else return this._def.out._parseAsync({data:S.value,path:t.path,parent:t})})();else{let T=this._def.in._parseSync({data:t.data,path:t.path,parent:t});if(T.status==="aborted")return u;if(T.status==="dirty")return n.dirty(),{status:"dirty",value:T.value};else return this._def.out._parseSync({data:T.value,path:t.path,parent:t})}}static create(o,n){return new CT({in:o,out:n,typeName:g.ZodPipeline})}}class et extends To{_parse(o){let n=this._def.innerType._parse(o),t=(T)=>{if(mT(T))T.value=Object.freeze(T.value);return T};return QT(n)?n.then((T)=>t(T)):t(n)}unwrap(){return this._def.innerType}}et.create=(o,n)=>{return new et({innerType:o,typeName:g.ZodReadonly,...to(n)})};function Zk(o,n={},t){if(o)return Jt.create().superRefine((T,S)=>{var f,y;if(!o(T)){let A=typeof n==="function"?n(T):typeof n==="string"?{message:n}:n,M=(y=(f=A.fatal)!==null&&f!==void 0?f:t)!==null&&y!==void 0?y:!0,F=typeof A==="string"?{message:A}:A;S.addIssue({code:"custom",...F,fatal:M})}});return Jt.create()}var KR={object:Uo.lazycreate},g;(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"})(g||(g={}));var XR=(o,n={message:`Input not instance of ${o.name}`})=>Zk((t)=>t instanceof o,n),Pk=Un.create,ek=ft.create,ER=BT.create,YR=yt.create,lk=Nt.create,GR=$t.create,zR=DT.create,HR=ht.create,mR=ct.create,QR=Jt.create,DR=St.create,UR=Nn.create,VR=UT.create,rR=Vn.create,LT=Uo.create,BR=Uo.strictCreate,CR=xt.create,LR=BS.create,IR=it.create,jR=hn.create,bR=VT.create,NR=rT.create,hR=Rt.create,cR=jt.create,xR=vt.create,iR=pt.create,vR=At.create,pR=qt.create,qR=Wt.create,hk=Xn.create,ZR=rn.create,PR=en.create,eR=Xn.createWithPreprocess,lR=CT.create,gR=()=>Pk().optional(),dR=()=>ek().optional(),uR=()=>lk().optional(),aR={string:(o)=>Un.create({...o,coerce:!0}),number:(o)=>ft.create({...o,coerce:!0}),boolean:(o)=>Nt.create({...o,coerce:!0}),bigint:(o)=>yt.create({...o,coerce:!0}),date:(o)=>$t.create({...o,coerce:!0})},sR=u,zo=Object.freeze({__proto__:null,defaultErrorMap:bt,setErrorMap:oR,getErrorMap:US,makeIssue:VS,EMPTY_PATH:nR,addIssueToContext:C,ParseStatus:lo,INVALID:u,DIRTY:It,OK:on,isAborted:Ty,isDirty:Sy,isValid:mT,isAsync:QT,get util(){return $o},get objectUtil(){return ty},ZodParsedType:I,getParsedType:Tt,ZodType:To,datetimeRegex:pk,ZodString:Un,ZodNumber:ft,ZodBigInt:yt,ZodBoolean:Nt,ZodDate:$t,ZodSymbol:DT,ZodUndefined:ht,ZodNull:ct,ZodAny:Jt,ZodUnknown:St,ZodNever:Nn,ZodVoid:UT,ZodArray:Vn,ZodObject:Uo,ZodUnion:xt,ZodDiscriminatedUnion:BS,ZodIntersection:it,ZodTuple:hn,ZodRecord:VT,ZodMap:rT,ZodSet:Rt,ZodFunction:jt,ZodLazy:vt,ZodLiteral:pt,ZodEnum:At,ZodNativeEnum:qt,ZodPromise:Wt,ZodEffects:Xn,ZodTransformer:Xn,ZodOptional:rn,ZodNullable:en,ZodDefault:Zt,ZodCatch:Pt,ZodNaN:BT,BRAND:wR,ZodBranded:CS,ZodPipeline:CT,ZodReadonly:et,custom:Zk,Schema:To,ZodSchema:To,late:KR,get ZodFirstPartyTypeKind(){return g},coerce:aR,any:QR,array:rR,bigint:YR,boolean:lk,date:GR,discriminatedUnion:LR,effect:hk,enum:vR,function:cR,instanceof:XR,intersection:IR,lazy:xR,literal:iR,map:NR,nan:ER,nativeEnum:pR,never:UR,null:mR,nullable:PR,number:ek,object:LT,oboolean:uR,onumber:dR,optional:ZR,ostring:gR,pipeline:lR,preprocess:eR,promise:qR,record:bR,set:hR,strictObject:BR,string:Pk,symbol:zR,transformer:hk,tuple:jR,undefined:HR,union:CR,unknown:DR,void:VR,NEVER:sR,ZodIssueCode:m,quotelessJson:sJ,ZodError:Jn});function gk(o){let n=o.runtimeEnvStrict??o.runtimeEnv??process.env;if(o.emptyStringAsUndefined??!1){for(let[K,U]of Object.entries(n))if(U==="")delete n[K]}if(!!o.skipValidation)return n;let S=typeof o.client==="object"?o.client:{},f=typeof o.server==="object"?o.server:{},y=typeof o.shared==="object"?o.shared:{},A=LT(S),M=LT(f),F=LT(y),k=o.isServer??(typeof window==="undefined"||("Deno"in window)),W=A.merge(F),O=M.merge(F).merge(A),E=k?O.safeParse(n):W.safeParse(n),Q=o.onValidationError??((K)=>{throw console.error("\u274C Invalid environment variables:",K.flatten().fieldErrors),new Error("Invalid environment variables")}),z=o.onInvalidAccess??((K)=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(E.success===!1)return Q(E.error);let G=(K)=>{if(!o.clientPrefix)return!0;return!K.startsWith(o.clientPrefix)&&!(K in F.shape)},V=(K)=>{return k||!G(K)},x=(K)=>{return K==="__esModule"||K==="$$typeof"},c=(o.extends??[]).reduce((K,U)=>{return Object.assign(K,U)},{}),P=Object.assign(E.data,c);return new Proxy(P,{get(K,U){if(typeof U!=="string")return;if(x(U))return;if(!V(U))return z(U);return Reflect.get(K,U)}})}var o0="__vite_start_time"in globalThis,n0=typeof window!=="undefined",d7="vitest"in globalThis,Cn=gk({isServer:!o0&&!n0,server:{CI:zo.string().transform((o)=>!0).optional(),POSTGRES_USER:zo.string(),POSTGRES_PASSWORD:zo.string(),POSTGRES_DATABASE:zo.string(),POSTGRES_HOST:zo.string(),POSTGRES_PORT:zo.string().transform((o)=>Number.parseInt(o,10)),BACKEND_PORT:zo.string().transform((o)=>Number.parseInt(o,10)),RUN_WORKERS_FROM_SOURCE:zo.union([zo.literal("true"),zo.literal("false")]).optional().transform((o)=>o==="true"),FRONTEND_PORT:zo.string().transform((o)=>Number.parseInt(o,10)),FRONTEND_ORIGINS:zo.string().transform((o)=>JSON.parse(o)).pipe(zo.array(zo.string())),OPENAI_API_KEY:zo.string().optional()},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:zo.string(),VITE_USE_SELF_SIGNED_CERTIFICATE:zo.union([zo.literal("true"),zo.literal("false")]).optional().transform((o)=>o==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var uk=yy(import.meta.dirname,"../dev"),ak=Cn.VITE_USE_SELF_SIGNED_CERTIFICATE?{cert:dk(yy(uk,"./cert.pem"),"utf-8"),key:dk(yy(uk,"./key.pem"),"utf-8")}:void 0;import l0 from"path";import m0 from"os";import Q0 from"fs";var LS=new Map,Ay=new Map,My=Symbol("OriginError"),lt={};class En extends Promise{constructor(o,n,t,T,S={}){let f,y;super((A,M)=>{f=A,y=M});this.tagged=Array.isArray(o.raw),this.strings=o,this.args=n,this.handler=t,this.canceller=T,this.options=S,this.state=null,this.statement=null,this.resolve=(A)=>(this.active=!1,f(A)),this.reject=(A)=>(this.active=!1,y(A)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[My]=this.handler.debug?new Error:this.tagged&&t0(this.strings)}get origin(){return(this.handler.debug?this[My].stack:this.tagged&&Ay.has(this.strings)?Ay.get(this.strings):Ay.set(this.strings,this[My].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();let T=new Promise((S,f)=>{this.cursorFn=(y)=>{return S({value:y,done:!1}),new Promise((A)=>t=A)},this.resolve=()=>(this.active=!1,S({done:!0})),this.reject=(y)=>(this.active=!1,f(y))});return this.execute(),T},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 t0(o){if(LS.has(o))return LS.get(o);let n=Error.stackTraceLimit;return Error.stackTraceLimit=4,LS.set(o,new Error),Error.stackTraceLimit=n,LS.get(o)}class gt extends Error{constructor(o){super(o.message);this.name=this.constructor.name,Object.assign(this,o)}}var Lo={connection:sk,postgres:o$,generic:n$,notSupported:t$};function sk(o,n,t){let{host:T,port:S}=t||n,f=Object.assign(new Error("write "+o+" "+(n.path||T+":"+S)),{code:o,errno:o,address:n.path||T},n.path?{}:{port:S});return Error.captureStackTrace(f,sk),f}function o$(o){let n=new gt(o);return Error.captureStackTrace(n,o$),n}function n$(o,n){let t=Object.assign(new Error(o+": "+n),{code:o});return Error.captureStackTrace(t,n$),t}function t$(o){let n=Object.assign(new Error(o+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:o});return Error.captureStackTrace(n,t$),n}var T0={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 bS{then(){Fy()}catch(){Fy()}finally(){Fy()}}class NT extends bS{constructor(o){super();this.value=cS(o)}}class cn extends bS{constructor(o,n,t){super();this.value=o,this.type=n,this.array=t}}class NS extends bS{constructor(o,n){super();this.first=o,this.rest=n}build(o,n,t,T){let S=S0.map(([f,y])=>({fn:y,i:o.search(f)})).sort((f,y)=>f.i-y.i).pop();return S.i===-1?Wy(this.first,T):S.fn(this.first,this.rest,n,t,T)}}function hS(o,n,t,T){let S=o instanceof cn?o.value:o;if(S===void 0){if(o instanceof cn?o.value=T.transform.undefined:S=o=T.transform.undefined,S===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||jS(o.value)]||o.type||y$(o.value):o.type):(n.push(o),jS(o)))}var S$=M$(T0);function Jy(o,n,t,T,S,f){for(let y=1;y<o.strings.length;y++)n+=Ry(n,t,T,S,f)+o.strings[y],t=o.args[y];return n}function Ry(o,n,t,T,S){return n instanceof NS?n.build(o,t,T,S):n instanceof En?$y(n,t,T,S):n instanceof NT?n.value:n&&n[0]instanceof En?n.reduce((f,y)=>f+" "+$y(y,t,T,S),""):hS(n,t,T,S)}function $y(o,n,t,T){return o.fragment=!0,Jy(o,o.strings[0],o.args[0],n,t,T)}function f$(o,n,t,T,S){return o.map((f)=>"("+T.map((y)=>Ry("values",f[y],n,t,S)).join(",")+")").join(",")}function T$(o,n,t,T,S){let f=Array.isArray(o[0]),y=n.length?n.flat():Object.keys(f?o[0]:o);return f$(f?o:[o],t,T,y,S)}function IS(o,n,t,T,S){if(typeof o==="string"&&(o=[o].concat(n)),Array.isArray(o))return Wy(o,S);let f;return(n.length?n.flat():Object.keys(o)).map((A)=>{return f=o[A],(f instanceof En?$y(f,t,T,S):f instanceof NT?f.value:hS(f,t,T,S))+" as "+cS(S.transform.column.to?S.transform.column.to(A):A)}).join(",")}var S0=Object.entries({values:T$,in:(...o)=>{let n=T$(...o);return n==="()"?"(null)":n},select:IS,as:IS,returning:IS,"\\(":IS,update(o,n,t,T,S){return(n.length?n.flat():Object.keys(o)).map((f)=>cS(S.transform.column.to?S.transform.column.to(f):f)+"="+Ry("values",o[f],t,T,S))},insert(o,n,t,T,S){let f=n.length?n.flat():Object.keys(Array.isArray(o)?o[0]:o);return"("+Wy(f,S)+")values"+f$(Array.isArray(o)?o:[o],t,T,f,S)}}).map(([o,n])=>[new RegExp("((?:^|[\\s(])"+o+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),n]);function Fy(){throw Lo.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:f0,parsers:y0}=S$;function y$(o){if(Array.isArray(o))return y$(o[0]);return typeof o==="string"?1009:0}var A$=function(o){let n=M$(o||{});return{serializers:Object.assign({},f0,n.serializers),parsers:Object.assign({},y0,n.parsers)}};function M$(o){return Object.keys(o).reduce((n,t)=>{if(o[t].from&&[].concat(o[t].from).forEach((T)=>n.parsers[T]=o[t].parse),o[t].serialize)n.serializers[o[t].to]=o[t].serialize,o[t].from&&[].concat(o[t].from).forEach((T)=>n.serializers[T]=o[t].serialize);return n},{parsers:{},serializers:{}})}function Wy(o,{transform:{column:n}}){return o.map((t)=>cS(n.to?n.to(t):t)).join(",")}var cS=function o(n){return'"'+n.replace(/"/g,'""').replace(/\./g,'"."')+'"'},jS=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},A0=/\\/g,M0=/"/g;function F0(o){return o.replace(A0,"\\\\").replace(M0,'\\"')}var F$=function o(n,t,T,S){if(Array.isArray(n)===!1)return n;if(!n.length)return"{}";let f=n[0],y=S===1020?";":",";if(Array.isArray(f)&&!f.type)return"{"+n.map((A)=>o(A,t,T,S)).join(y)+"}";return"{"+n.map((A)=>{if(A===void 0){if(A=T.transform.undefined,A===void 0)throw Lo.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return A===null?"null":'"'+F0(t?t(A.type?A.value:A):""+A)+'"'}).join(y)+"}"},ky={i:0,char:null,str:"",quoted:!1,last:0},k$=function o(n,t,T){return ky.i=ky.last=0,$$(ky,n,t,T)};function $$(o,n,t,T){let S=[],f=T===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==='"')S.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,S.push($$(o,n,t,T));else if(o.char==="}"){o.quoted=!1,o.last<o.i&&S.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===f&&o.p!=="}"&&o.p!=='"')S.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&&S.push(t?t(n.slice(o.last,o.i+1)):n.slice(o.last,o.i+1)),S}var Ot=(o)=>{let n=o[0];for(let t=1;t<o.length;t++)n+=o[t]==="_"?o[++t].toUpperCase():o[t];return n},_t=(o)=>{let n=o[0].toUpperCase();for(let t=1;t<o.length;t++)n+=o[t]==="_"?o[++t].toUpperCase():o[t];return n},wt=(o)=>o.replace(/_/g,"-"),IT=(o)=>o.replace(/([A-Z])/g,"_$1").toLowerCase(),jT=(o)=>(o.slice(0,1)+o.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),bT=(o)=>o.replace(/-/g,"_");function Oy(o){return function n(t,T){return typeof t==="object"&&t!==null&&(T.type===114||T.type===3802)?Array.isArray(t)?t.map((S)=>n(S,T)):Object.entries(t).reduce((S,[f,y])=>Object.assign(S,{[o(f)]:n(y,T)}),{}):t}}Ot.column={from:Ot};Ot.value={from:Oy(Ot)};IT.column={to:IT};var _y={...Ot};_y.column.to=IT;_t.column={from:_t};_t.value={from:Oy(_t)};jT.column={to:jT};var wy={..._t};wy.column.to=jT;wt.column={from:wt};wt.value={from:Oy(wt)};bT.column={to:bT};var Ky={...wt};Ky.column.to=bT;import J$ from"net";import R0 from"tls";import hT from"crypto";import Xy from"stream";import{performance as R$}from"perf_hooks";class Kt extends Array{constructor(){super();Object.defineProperties(this,{count:{value:null,writable:!0},state:{value:null,writable:!0},command:{value:null,writable:!0},columns:{value:null,writable:!0},statement:{value:null,writable:!0}})}static get[Symbol.species](){return Array}}var Rn=k0;function k0(o=[]){let n=o.slice(),t=0;return{get length(){return n.length-t},remove:(T)=>{let S=n.indexOf(T);return S===-1?null:(n.splice(S,1),T)},push:(T)=>(n.push(T),T),shift:()=>{let T=n[t++];if(t===n.length)t=0,n=[];else n[t-1]=void 0;return T}}}var go=Buffer.allocUnsafe(256),$0="BCcDdEFfHPpQSX".split("").reduce((o,n)=>{let t=n.charCodeAt(0);return o[n]=()=>{return go[0]=t,Wo.i=5,Wo},o},{}),Wo=Object.assign(J0,$0,{N:String.fromCharCode(0),i:0,inc(o){return Wo.i+=o,Wo},str(o){let n=Buffer.byteLength(o);return xS(n),Wo.i+=go.write(o,Wo.i,n,"utf8"),Wo},i16(o){return xS(2),go.writeUInt16BE(o,Wo.i),Wo.i+=2,Wo},i32(o,n){if(n||n===0)return go.writeUInt32BE(o,n),Wo;return xS(4),go.writeUInt32BE(o,Wo.i),Wo.i+=4,Wo},z(o){return xS(o),go.fill(0,Wo.i,Wo.i+o),Wo.i+=o,Wo},raw(o){return go=Buffer.concat([go.subarray(0,Wo.i),o]),Wo.i=go.length,Wo},end(o=1){go.writeUInt32BE(Wo.i-o,o);let n=go.subarray(0,Wo.i);return Wo.i=0,go=Buffer.allocUnsafe(256),n}}),Z=Wo;function xS(o){if(go.length-Wo.i<o){let n=go,t=n.length;go=Buffer.allocUnsafe(t+(t>>1)+o),n.copy(go)}}function J0(){return Wo.i=0,Wo}var Gy=_$,W0=1,Mt=Z().S().end(),W$=Z().H().end(),O0=Z().i32(8).i32(80877103).end(8),_0=Buffer.concat([Z().E().str(Z.N).i32(0).end(),Mt]),w0=Z().D().str("S").str(Z.N).end(),dt=()=>{},K0=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),X0={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 _$(o,n={},{onopen:t=dt,onend:T=dt,onclose:S=dt}={}){let{ssl:f,max:y,user:A,host:M,port:F,database:k,parsers:W,transform:O,onnotice:E,onnotify:Q,onparameter:z,max_pipeline:G,keep_alive:V,backoff:x,target_session_attrs:c}=o,P=Rn(),Y=W0++,K={pid:null,secret:null},U=Yy(sS,o.idle_timeout),p=Yy(sS,o.max_lifetime),b=Yy(c$,o.connect_timeout),w=null,v,j=new Kt,a=Buffer.alloc(0),oo=o.fetch_types,no={},_o={},Mn=Math.random().toString(36).slice(2),H=1,i=0,fo=0,Ro=0,Io=0,So=0,wo=0,Co=0,mo=null,Eo=null,vo=!1,Ko=null,Yn=null,po=null,ln=null,jo=null,Yo=null,Gn=null,Ln=null,B=null,oT=null,qo={queue:n.closed,idleTimer:U,connect($){po=$||!0,gy()},terminate:tT,execute:nT,cancel:j$,end:sS,count:0,id:Y};return n.closed&&n.closed.push(qo),qo;async function I$(){let $;try{$=o.socket?await Promise.resolve(o.socket(o)):new J$.Socket}catch(_){Gt(_);return}return $.on("error",Gt),$.on("close",dy),$.on("drain",ey),$}async function j$({pid:$,secret:_},e,Jo){try{v=Z().i32(16).i32(80877102).i32($).i32(_).end(16),await ly(),w.once("error",Jo),w.once("close",e)}catch(Vo){Jo(Vo)}}function nT($){if(vo)return ZT($,Lo.connection("CONNECTION_DESTROYED",o));if($.cancelled)return;try{return $.state=K,B?P.push($):(B=$,B.active=!0),h$($),co(b$($))&&!$.describeFirst&&!$.cursorFn&&P.length<G&&(!$.options.onexecute||$.options.onexecute(qo))}catch(_){return P.length===0&&co(Mt),In(_),!0}}function b$($){if($.parameters.length>=65534)throw Lo.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return $.options.simple?Z().Q().str($.statement.string+Z.N).end():$.describeFirst?Buffer.concat([qy($),W$]):$.prepare?$.prepared?qT($):Buffer.concat([qy($),qT($)]):N$($)}function qy($){return Buffer.concat([ay($.statement.string,$.parameters,$.statement.types,$.statement.name),zJ("S",$.statement.name)])}function qT($){return Buffer.concat([GJ($.parameters,$.statement.types,$.statement.name,$.cursorName),$.cursorFn?sy("",$.cursorRows):_0])}function N$($){return Buffer.concat([ay($.statement.string,$.parameters,$.statement.types),w0,qT($)])}function h$($){let _=[],e=[],Jo=Jy($,$.strings[0],$.args[0],_,e,o);!$.tagged&&$.args.forEach((Vo)=>hS(Vo,_,e,o)),$.prepare=o.prepare&&("prepare"in $.options?$.options.prepare:!0),$.string=Jo,$.signature=$.prepare&&e+Jo,$.onlyDescribe&&delete _o[$.signature],$.parameters=$.parameters||_,$.prepared=$.prepare&&$.signature in _o,$.describeFirst=$.onlyDescribe||_.length&&!$.prepared,$.statement=$.prepared?_o[$.signature]:{string:Jo,types:e,name:$.prepare?Mn+H++:""},typeof o.debug==="function"&&o.debug(Y,Jo,_,e)}function co($,_){if(Yo=Yo?Buffer.concat([Yo,$]):Buffer.from($),_||Yo.length>=1024)return Zy(_);return Eo===null&&(Eo=setImmediate(Zy)),!0}function Zy($){let _=w.write(Yo,$);return Eo!==null&&clearImmediate(Eo),Yo=Eo=null,_}function c$(){In(Lo.connection("CONNECT_TIMEOUT",o,w)),w.destroy()}async function Py(){if(co(O0),!await new Promise((_)=>w.once("data",(e)=>_(e[0]===83)))&&f==="prefer")return Yt();w.removeAllListeners(),w=R0.connect({socket:w,servername:J$.isIP(w.host)?void 0:w.host,...f==="require"||f==="allow"||f==="prefer"?{rejectUnauthorized:!1}:f==="verify-full"?{}:typeof f==="object"?f:{}}),w.on("secureConnect",Yt),w.on("error",Gt),w.on("close",dy),w.on("drain",ey)}function ey(){!B&&t(qo)}function aS($){if(Ko){if(Ko.push($),fo-=$.length,fo>=0)return}a=Ko?Buffer.concat(Ko,So-fo):a.length===0?$:Buffer.concat([a,$],a.length+$.length);while(a.length>4){if(So=a.readUInt32BE(1),So>=a.length){fo=So-a.length,Ko=[a];break}try{x$(a.subarray(0,So+1))}catch(_){B&&(B.cursorFn||B.describeFirst)&&co(Mt),In(_)}a=a.subarray(So+1),fo=0,Ko=null}}async function ly(){if(vo=!1,no={},w||(w=await I$()),!w)return;if(b.start(),o.socket)return f?Py():Yt();if(w.on("connect",f?Py:Yt),o.path)return w.connect(o.path);w.ssl=f,w.connect(F[Ro],M[Ro]),w.host=M[Ro],w.port=F[Ro],Ro=(Ro+1)%F.length}function gy(){setTimeout(ly,i?i+wo-R$.now():0)}function Yt(){try{_o={},oo=o.fetch_types,Mn=Math.random().toString(36).slice(2),H=1,p.start(),w.on("data",aS),V&&w.setKeepAlive&&w.setKeepAlive(!0,1000*V);let $=mJ();co($)}catch($){Gt($)}}function Gt($){if(qo.queue===n.connecting&&o.host[Io+1])return;In($);while(P.length)ZT(P.shift(),$)}function In($){jo&&(jo.destroy($),jo=null),B&&ZT(B,$),po&&(ZT(po,$),po=null)}function ZT($,_){"query"in _||"parameters"in _||Object.defineProperties(_,{stack:{value:_.stack+$.origin.replace(/.*\n/,"\n"),enumerable:o.debug},query:{value:$.string,enumerable:o.debug},parameters:{value:$.parameters,enumerable:o.debug},args:{value:$.args,enumerable:o.debug},types:{value:$.statement&&$.statement.types,enumerable:o.debug}}),$.reject(_)}function sS(){return ln||(!qo.reserved&&T(qo),!qo.reserved&&!po&&!B&&P.length===0?(tT(),new Promise(($)=>w&&w.readyState!=="closed"?w.once("close",$):$())):ln=new Promise(($)=>Gn=$))}function tT(){if(vo=!0,jo||B||po||P.length)Gt(Lo.connection("CONNECTION_DESTROYED",o));if(clearImmediate(Eo),w)w.removeListener("data",aS),w.removeListener("connect",Yt),w.readyState==="open"&&w.end(Z().X().end());Gn&&(Gn(),ln=Gn=null)}async function dy($){if(a=Buffer.alloc(0),fo=0,Ko=null,clearImmediate(Eo),w.removeListener("data",aS),w.removeListener("connect",Yt),U.cancel(),p.cancel(),b.cancel(),w.removeAllListeners(),w=null,po)return gy();!$&&(B||P.length)&&Gt(Lo.connection("CONNECTION_CLOSED",o,w)),i=R$.now(),$&&o.shared.retries++,wo=(typeof x==="function"?x(o.shared.retries):x)*1000,S(qo,Lo.connection("CONNECTION_CLOSED",o,w))}function x$($,_=$[0]){(_===68?i$:_===100?WJ:_===65?MJ:_===83?v$:_===90?p$:_===67?q$:_===50?uy:_===49?Z$:_===116?P$:_===84?e$:_===82?l$:_===110?oJ:_===75?nJ:_===69?yJ:_===115?FJ:_===51?kJ:_===71?$J:_===78?_J:_===72?JJ:_===99?OJ:_===73?wJ:_===86?KJ:_===118?XJ:_===87?RJ:EJ)($)}function i$($){let _=7,e,Jo,Vo,Zo=B.isRaw?new Array(B.statement.columns.length):{};for(let uo=0;uo<B.statement.columns.length;uo++)Jo=B.statement.columns[uo],e=$.readInt32BE(_),_+=4,Vo=e===-1?null:B.isRaw===!0?$.subarray(_,_+=e):Jo.parser===void 0?$.toString("utf8",_,_+=e):Jo.parser.array===!0?Jo.parser($.toString("utf8",_+1,_+=e)):Jo.parser($.toString("utf8",_,_+=e)),B.isRaw?Zo[uo]=B.isRaw===!0?Vo:O.value.from?O.value.from(Vo,Jo):Vo:Zo[Jo.name]=O.value.from?O.value.from(Vo,Jo):Vo;B.forEachFn?B.forEachFn(O.row.from?O.row.from(Zo):Zo,j):j[Co++]=O.row.from?O.row.from(Zo):Zo}function v$($){let[_,e]=$.toString("utf8",5,$.length-1).split(Z.N);if(no[_]=e,o.parameters[_]!==e)o.parameters[_]=e,z&&z(_,e)}function p$($){if(B&&B.options.simple&&B.resolve(Yn||j),B=Yn=null,j=new Kt,b.cancel(),po){if(c){if(!no.in_hot_standby||!no.default_transaction_read_only)return fJ();else if(SJ(c,no))return tT()}if(oo)return po===!0&&(po=null),tJ();po!==!0&&nT(po),o.shared.retries=Io=0,po=null;return}while(P.length&&(B=P.shift())&&(B.active=!0,B.cancelled))_$(o).cancel(B.state,B.cancelled.resolve,B.cancelled.reject);if(B)return;qo.reserved?!qo.reserved.release&&$[5]===73?ln?tT():(qo.reserved=null,t(qo)):qo.reserved():ln?tT():t(qo)}function q$($){Co=0;for(let _=$.length-1;_>0;_--){if($[_]===32&&$[_+1]<58&&j.count===null)j.count=+$.toString("utf8",_+1,$.length-1);if($[_-1]>=65){j.command=$.toString("utf8",5,_),j.state=K;break}}if(oT&&(oT(),oT=null),j.command==="BEGIN"&&y!==1&&!qo.reserved)return In(Lo.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(B.options.simple)return uy();if(B.cursorFn)j.count&&B.cursorFn(j),co(Mt);B.resolve(j)}function Z$(){B.parsing=!1}function uy(){!j.statement&&(j.statement=B.statement),j.columns=B.statement.columns}function P$($){let _=$.readUInt16BE(5);for(let e=0;e<_;++e)!B.statement.types[e]&&(B.statement.types[e]=$.readUInt32BE(7+e*4));B.prepare&&(_o[B.signature]=B.statement),B.describeFirst&&!B.onlyDescribe&&(co(qT(B)),B.describeFirst=!1)}function e$($){if(j.command)Yn=Yn||[j],Yn.push(j=new Kt),j.count=null,B.statement.columns=null;let _=$.readUInt16BE(5),e=7,Jo;B.statement.columns=Array(_);for(let Vo=0;Vo<_;++Vo){Jo=e;while($[e++]!==0);let Zo=$.readUInt32BE(e),uo=$.readUInt16BE(e+4),gn=$.readUInt32BE(e+6);B.statement.columns[Vo]={name:O.column.from?O.column.from($.toString("utf8",Jo,e-1)):$.toString("utf8",Jo,e-1),parser:W[gn],table:Zo,number:uo,type:gn},e+=18}if(j.statement=B.statement,B.onlyDescribe)return B.resolve(B.statement),co(Mt)}async function l$($,_=$.readUInt32BE(5)){(_===3?g$:_===5?d$:_===10?u$:_===11?a$:_===12?s$:_!==0?YJ:dt)($,_)}async function g$(){let $=await of();co(Z().p().str($).z(1).end())}async function d$($){let _="md5"+await O$(Buffer.concat([Buffer.from(await O$(await of()+A)),$.subarray(9)]));co(Z().p().str(_).z(1).end())}async function u$(){Ln=(await hT.randomBytes(18)).toString("base64"),Z().p().str("SCRAM-SHA-256"+Z.N);let $=Z.i;co(Z.inc(4).str("n,,n=*,r="+Ln).i32(Z.i-$-4,$).end())}async function a$($){let _=$.toString("utf8",9).split(",").reduce((uo,gn)=>(uo[gn[0]]=gn.slice(2),uo),{}),e=await hT.pbkdf2Sync(await of(),Buffer.from(_.s,"base64"),parseInt(_.i),32,"sha256"),Jo=await iS(e,"Client Key"),Vo="n=*,r="+Ln+",r="+_.r+",s="+_.s+",i="+_.i+",c=biws,r="+_.r;mo=(await iS(await iS(e,"Server Key"),Vo)).toString("base64");let Zo="c=biws,r="+_.r+",p="+Y0(Jo,Buffer.from(await iS(await E0(Jo),Vo))).toString("base64");co(Z().p().str(Zo).end())}function s$($){if($.toString("utf8",9).split(Z.N,1)[0].slice(2)===mo)return;In(Lo.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),w.destroy()}function of(){return Promise.resolve(typeof o.pass==="function"?o.pass():o.pass)}function oJ(){if(j.statement=B.statement,j.statement.columns=[],B.onlyDescribe)return B.resolve(B.statement),co(Mt)}function nJ($){K.pid=$.readUInt32BE(5),K.secret=$.readUInt32BE(9)}async function tJ(){oo=!1,(await new En([`
|
|
3
|
+
var QJ=Object.create;var{getPrototypeOf:DJ,defineProperty:yf,getOwnPropertyNames:UJ}=Object;var VJ=Object.prototype.hasOwnProperty;var oW=(o,n,T)=>{T=o!=null?QJ(DJ(o)):{};let t=n||!o||!o.__esModule?yf(T,"default",{value:o,enumerable:!0}):T;for(let S of UJ(o))if(!VJ.call(t,S))yf(t,S,{get:()=>o[S],enumerable:!0});return t};var nW=(o,n)=>()=>(n||o((n={exports:{}}).exports,n),n.exports);var BJ=(o,n)=>{for(var T in n)yf(o,T,{get:n[T],enumerable:!0,configurable:!0,set:(t)=>n[T]=()=>t})};import{join as d0,normalize as u0,resolve as Ik}from"path";function HT(o=Math.random){return o().toString(36).slice(2)}class St extends Promise{fate;resolve;reject;done=!1;constructor(o){let n,T;super((t,S)=>{n=t,T=S});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){let 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 tA(o){return Object.entries(o)}var SA=(o,n,T=to.STORE)=>{return Gn(T,{key:`${o.key}:JSON`,get:({get:t})=>n.toJson(t(o)),set:({set:t},S)=>{t(o,n.fromJson(S))}})};function U(o){while(o.child!==null)o=o.child;return o}function fA(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){let 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 rn(o,n,T){let t={key:n.key,type:"atom_family"},S=o.families.get(n.key);if(S)o.logger.error("\u2757","atom_family",n.key,`Overwriting an existing ${zn(S)} "${S.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let f=new s,A=Object.assign((M)=>{let F=l(M),$={key:n.key,subKey:F},W=`${n.key}(${F})`,O=U(o),G=n.default,D={key:W,default:G instanceof Function?G(M):G};if(n.effects)D.effects=n.effects(M);let z=fn(O,D,$);return f.next({type:"state_creation",token:z}),z},t,{subject:f,install:(M)=>rn(M,n),internalRoles:T});return o.families.set(n.key,A),o.defaults.set(n.key,n.default),t}function yA(o,n){if("mutable"in n)return ft(o,n);return rn(o,n)}function xn(o,n,T){let t={key:n.key,type:"readonly_selector_family"},S=o.families.get(n.key);if(S)o.logger.error("\u2757","readonly_selector_family",n.key,`Overwriting an existing ${zn(S)} "${S.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let f=new s,A=Object.assign((M)=>{let F=l(M),$={key:n.key,subKey:F},W=`${n.key}(${F})`,O=U(o),G=yt(O,{key:W,get:n.get(M)},$);return f.next({type:"state_creation",token:G}),G},t,{internalRoles:T,subject:f,install:(M)=>xn(M,n),default:(M)=>{return n.get(M)({get:(...$)=>fo(o,...$),find:($,W)=>Ao(o,$,W),seek:($,W)=>Eo(o,$,W),json:($)=>Vo(o,$)})}});return o.families.set(n.key,A),t}function At(o,n){if("set"in n)return Mt(o,n);return xn(o,n)}var CJ={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function mT(o,n){let T=l(n),t=`${o.key}(${T})`,S=CJ[o.type],f={key:t,type:S};if(S==="molecule")Object.assign(f,{key:n,family:o});else Object.assign(f,{family:{key:o.key,subKey:T}});return Object.assign(f,{counterfeit:!0}),f}function go(o){let n={key:o.key,type:o.type};if("family"in o)n.family=o.family;return n}var IW=Symbol("provenance");function Mf(o,n,T){let t=l(T);try{let S=[],f;if(n==="root")S.push(o.molecules.get('"root"')),f="all";else if(typeof n==="string"&&n.startsWith(LJ)){f="any";let $=l(n),W=o.molecules.get($);if(!W)throw new Error(`Molecule ${$} not found in store "${o.config.name}"`);S.push(W)}else if(T.startsWith("T$--")){f="all";for(let W of n){let O=l(W),G=o.molecules.get(O);if(!G)throw new Error(`Molecule ${O} not found in store "${o.config.name}"`);S.push(G)}}else{f="any";let W=l(n),O=o.molecules.get(W);if(!O)throw new Error(`Molecule ${W} not found in store "${o.config.name}"`);S.push(O)}let y=new QT(S,T);y._dependsOn=f,o.molecules.set(t,y);for(let $ of S)$.below.set(y.stringKey,y);let A={type:"molecule_creation",subType:"modern",key:y.key,provenance:n},M=U(o);if(yo(M)&&M.transactionMeta.phase==="building")M.transactionMeta.update.updates.push(A);else M.on.moleculeCreationStart.next(A)}catch(S){if(S instanceof Error)o.logger.error("\u274C","molecule",t,"allocation failed:",S.message)}return T}function Ft(o,n){let T=l(n),t=o.molecules.get(T);if(!t)throw new Error(`Molecule ${T} not found in store "${o.config.name}"`);for(let F of t.joins.values())F.relations.delete(t.key),F.molecules.delete(t.stringKey);let S;if(t.above.size===1)S=t.above.values().next().value.key;else S=[...t.above.values()].map(({key:F})=>F);let f=[];for(let F of t.tokens.values()){let $=F.family;f.push([$.key,o.valueMap.get(F.key)])}for(let F of t.tokens.values())so(o,F);for(let F of t.below.values())if(F.dependsOn==="all")Ft(o,F.key);else if(F.above.delete(t.stringKey),F.above.size===0)Ft(o,F.key);t.below.clear();let y={type:"molecule_disposal",subType:"modern",key:t.key,values:f,provenance:S},A=U(o);if(yo(A)&&A.transactionMeta.phase==="building")A.transactionMeta.update.updates.push(y);else A.on.moleculeDisposal.next(y);A.molecules.delete(t.stringKey);for(let F of t.above.values())F.below.delete(t.stringKey)}var LJ="T$";function DT(o){return AA(to.STORE,o)}function $T(o){return yA(to.STORE,o)}function Ff(...o){if(o.length===2)return fo(to.STORE,...o);return fo(to.STORE,...o)}var $f=(o)=>(n,T,t,S,...f)=>{console[o](`${n} ${T} "${t}" ${S}`,...f)},IJ={error:$f("error"),info:$f("info"),warn:$f("warn")};class kf{logLevel;filter;logger;constructor(o,n,T=IJ){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 et(o){return At(to.STORE,o)}function $t(o){return Jf(o,to.STORE)}class Fn{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(o,n)=>`${o}:${n}`;warn;getRelatedKeys(o){return this.relations.get(o)}addRelation(o,n){let T=this.relations.get(o),t=this.relations.get(n);if(T)T.add(n);else T=new Set([n]),this.relations.set(o,T);if(t)t.add(o);else t=new Set([o]),this.relations.set(n,t)}deleteRelation(o,n){let T=this.relations.get(o);if(T){if(T.delete(n),T.size===0)this.relations.delete(o);let t=this.relations.get(n);if(t){if(t.delete(o),t.size===0)this.relations.delete(n)}}}replaceRelationsUnsafely(o,n){this.relations.set(o,new Set(n));for(let T of n){let t=new Set().add(o);this.relations.set(T,t)}}replaceRelationsSafely(o,n){let T=this.relations.get(o),t=this.isAType?.(o)?o:void 0,S=t===void 0?o:void 0;if(T)for(let f of T){t??=f,S??=f;let y=this.relations.get(f);if(y){if(y.size===1)this.relations.delete(f);else y.delete(o);this.contents.delete(this.makeContentKey(t,S))}}this.relations.set(o,new Set(n));for(let f of n){let y=this.relations.get(f);if(y)y.add(o);else y=new Set().add(o),this.relations.set(f,y)}}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,t])=>[T,new Set(t)])),this.contents=new Map(o.contents);if(this.isAType=n?.isAType??null,this.isBType=n?.isBType??null,this.isContent=n?.isContent??null,n?.makeContentKey)this.makeContentKey=n.makeContentKey;if(n?.externalStore){let T=n.externalStore;if(this.has=(t,S)=>T.has(t,S),this.addRelation=(t,S)=>{T.addRelation(t,S)},this.deleteRelation=(t,S)=>{T.deleteRelation(t,S)},this.replaceRelationsSafely=(t,S)=>{T.replaceRelationsSafely(t,S)},this.replaceRelationsUnsafely=(t,S)=>{T.replaceRelationsUnsafely(t,S)},this.getRelatedKeys=(t)=>T.getRelatedKeys(t),T.getContent)this.getContentInternal=(t)=>{return T.getContent(t)},this.setContent=(t,S)=>{T.setContent(t,S)},this.deleteContent=(t)=>{T.deleteContent(t)};for(let[t,S]of o.relations??[]){let f=this.isAType?.(t)?t:void 0,y=f===void 0?t:void 0;for(let A of S)f??=A,y??=A,this.addRelation(f,y)}for(let[t,S]of o.contents??[])this.setContent(t,S)}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){let T=typeof n[0]==="string"?n[0]:o[this.b],t=n[1]??typeof n[0]==="string"?void 0:n[0];switch(o=typeof o==="string"?o:o[this.a],this.cardinality){case"1:1":{let S=this.getRelatedKey(o);if(S&&S!==T)this.delete(o,S)}case"1:n":{let S=this.getRelatedKey(T);if(S&&S!==o)this.delete(S,T)}}if(t){let S=this.makeContentKey(o,T);this.setContent(S,t)}return this.addRelation(o,T),this}delete(o,n){n=typeof n==="string"?n:o[this.b];let T=typeof o==="string"?o:o[this.a];if(T===void 0&&typeof n==="string"){let t=this.getRelatedKeys(n);if(t)for(let S of t)this.delete(S,n)}if(typeof T==="string"&&n===void 0){let t=this.getRelatedKeys(T);if(t)for(let S of t)this.delete(T,S)}if(typeof T==="string"&&typeof n==="string"){this.deleteRelation(T,n);let t=this.makeContentKey(T,n);this.deleteContent(t)}return this}getRelatedKey(o){let 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.`);let T;for(let t of n){T=t;break}return T}}replaceRelations(o,n,T){let t=!Array.isArray(n),S=t?Object.keys(n):n;if(T?.reckless)this.replaceRelationsUnsafely(o,S);else this.replaceRelationsSafely(o,S);if(t)for(let f of S){let y=this.makeContentKey(o,f),A=n[f];this.setContent(y,A)}return this}getContent(o,n){let T=this.makeContentKey(o,n);return this.getContentInternal(T)}getRelationEntries(o){let n=o[this.a],T=o[this.b];if(n!==void 0&&T===void 0){let t=this.getRelatedKeys(n);if(t)return[...t].map((S)=>{return[S,this.getContent(n,S)]})}if(n===void 0&&T!==void 0){let t=this.getRelatedKeys(T);if(t)return[...t].map((S)=>{return[S,this.getContent(S,T)]})}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 yo(o){return"phase"in o.transactionMeta}var FA=(o)=>{let n=U(o);if(!yo(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};var rJ=(o)=>o[0].toUpperCase()+o.slice(1);function zn(o){return o.type.split("_").map(rJ).join(" ")}class yn extends Error{constructor(...o){let n=o[0],T=o.length===2?o[1]:o[2];if(o.length===2)super(`${zn(n)} ${l(n.key)} not found in store "${T.config.name}".`);else{let t=o[1];super(`${zn(n)} "${n.key}" member ${l(t)} not found in store "${T.config.name}".`)}}}function un(o,n,T){return(...t)=>{let S=d(o,T);if(S)return S.run(t,n);throw new yn(o,T)}}var dt=(o)=>(n)=>o instanceof Function?o(n):o;var an=(o,n)=>{if(n.valueMap.has(o.key))return n.logger.info("\uD83D\uDCD6",o.type,o.key,"reading cached value"),$A(o,n);if(o.type==="selector"||o.type==="readonly_selector")return n.logger.info("\uD83E\uDDEE",o.type,o.key,"computing value"),o.get();let 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 kA=(o,n)=>{if(o.operation.open){let 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}"${!yo(o)?"":` ${o.transactionMeta.phase} "${o.transactionMeta.update.key}"`}`)},JA=(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)},RA=(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)},UT=(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 WA=(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 Rf=(o,n)=>{let T=U(n),t=T.selectorAtoms.getRelatedKeys(o.key);if(T.logger.info("\uD83E\uDDF9",o.type,o.key,t?`evicting ${t.size} states downstream:`:"no downstream states",t??"to evict"),t){if(T.operation.open)T.logger.info("\uD83E\uDDF9",o.type,o.key,`[ ${[...T.operation.done].join(", ")} ] already done`);for(let S of t){if(RA(T,S))continue;OA(S,T),UT(T,S)}}};function jJ(o,n){if(wA(n.newValue))return!1;if(o.includes("\uD83D\uDD0D"))return!1;return!0}var _A=(o,n,T)=>{let{key:t}=o,S=U(T);if(!yo(S)||S.transactionMeta.phase!=="building"){T.logger.error("\uD83D\uDC1E","atom",t,"stowUpdate called outside of a transaction. This is probably a bug.");return}if(!jJ(t,n))return;let y={type:"atom_update",key:t,...n};if(o.family)y.family=o.family;S.transactionMeta.update.updates.push(y),T.logger.info("\uD83D\uDCC1","atom",t,"stowed (",n.oldValue,"->",n.newValue,")")};var KA=(o,n,T)=>{let t=an(o,T),S=t;if(o.type==="mutable_atom"&&yo(T)){let{parent:y}=T;S=kt(o,y,T)}if(S=dt(n)(S),T.logger.info("\uD83D\uDCDD","atom",o.key,"set to",S),S=Wn(o.key,S,o.subject,T),XA(o.key,T))EA(o.key,T);UT(T,o.key),Rf(o,T);let f={oldValue:t,newValue:S};if(Bo(T))WA(o,f,T);else if(T.parent){if(T.on.transactionApplying.state===null)_A(o,f,T);else if(o.key.startsWith("*")){let y=o.key.slice(1),A=T.atoms.get(y),M=T.valueMap.get(y);if(A.type==="mutable_atom"&&yo(T)){let{parent:$}=T;M=kt(A,$,T)}if(M.do(f.newValue)===null)Rf(A,T)}}};var ut=(o,n,T)=>{switch(o.type){case"atom":case"mutable_atom":KA(o,n,T);break;case"selector":o.set(n);break}};function at(o,n){if(n.family){let T=o.families.get(n.family.key);if(T)return T}}function Qo(o,...n){let T,t,S,f;if(n.length===2){if(T=n[0],f=n[1],t=at(o,T)??null,t)S=T.family?jo(T.family.subKey):null,T=Ao(o,t,S)}else t=n[0],S=n[1],f=n[2],T=Ao(o,t,S);if("counterfeit"in T){let M=o.disposalTraces.buffer.find((F)=>F?.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}".`,M?`This state was previously disposed:
|
|
4
|
+
${M.trace}`:"No previous disposal trace was found.");return}let y=kA(o,T);if(y){let M=o.on.operationClose.subscribe(`waiting to set "${T.key}" at T-${y}`,()=>{M(),o.logger.info("\uD83D\uDFE2",T.type,T.key,`resuming deferred setState from T-${y}`),Qo(o,T,f)});return}let A=d(T,o);ut(A,f,o),JA(o)}function st(o,n,T){let{key:t,newValue:S,oldValue:f}=n,y=o==="newValue"?S:f,A={key:t,type:"atom"};if(n.family)Object.assign(A,{family:n.family});Qo(T,A,y)}function YA(o,n){let T=new s,t={type:"molecule_family",key:n.key,dependsOn:n.dependsOn??"all"},S={...t,subject:T,new:n.new};return o.moleculeFamilies.set(n.key,S),t}function Hn(o,n,T){let t=vn(T,n,o.key);o.tokens.set(t.key,t);let S=yo(T)&&T.transactionMeta.phase==="building",f=T.moleculeInProgress===o.key;if(!S&&!f)o.subject.next({type:"state_creation",token:t});return t}class No extends Set{mode="record";subject=new s;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(o,n=0){super(o);if(o instanceof No)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){let n=new No(o.members,o.cacheLimit);return n.cache=o.cache,n.cacheIdx=o.cacheIdx,n.cacheUpdateNumber=o.cacheUpdateNumber,n}add(o){let n=super.add(o);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${l(o)}`);return n}clear(){let o=this.mode==="record"?[...this]:null;if(super.clear(),o)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(o)}`)}delete(o){let 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 No(this);let n=this.child._subscribe("transaction",(T)=>{this.transactionUpdates?.push(T)});try{if(o(this.child)){for(let t of this.transactionUpdates)this.doStep(t);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){let n=o.indexOf(":"),T=o.substring(0,n),t=o.substring(n+1);switch(T){case"add":this.add(JSON.parse(t));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(t));break;case"tx":for(let S of t.split(";"))this.doStep(S)}}getUpdateNumber(o){let n=o.indexOf("=");return Number(o.substring(0,n))}do(o){let n=o.indexOf("="),T=Number(o.substring(0,n)),t=T-this.cacheUpdateNumber;if(t>0){if(t===1){this.mode="playback";let f=o.substring(n+1);return this.doStep(f),this.mode="record",this.cacheUpdateNumber=T,null}return this.cacheUpdateNumber+1}if(Math.abs(t)<this.cacheLimit){let f=this.cacheIdx+t;if(this.cache[f]===o)return null;this.mode="playback";let A=!1;while(!A){this.cacheIdx%=this.cacheLimit;let F=this.cache[this.cacheIdx];if(this.cacheIdx--,!F)return"OUT_OF_RANGE";this.undo(F),A=this.cacheIdx===f-1}let M=o.substring(n+1);return this.doStep(M),this.mode="record",this.cacheUpdateNumber=T,null}return"OUT_OF_RANGE"}undoStep(o){let n=o.indexOf(":"),T=o.substring(0,n),t=o.substring(n+1);switch(T){case"add":this.delete(JSON.parse(t));break;case"del":this.add(JSON.parse(t));break;case"clear":{let S=JSON.parse(t);for(let f of S)this.add(f);break}case"tx":{let S=t.split(";");for(let f=S.length-1;f>=0;f--)this.undoStep(S[f])}}}undo(o){let n=o.indexOf("=");if(Number(o.substring(0,n))===this.cacheUpdateNumber){this.mode="playback";let t=o.substring(n+1);return this.undoStep(t),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function Ho(o){return o[0].toUpperCase()+o.slice(1)}class _f{options;defaultContent;toolkit;retrieve;molecules=new Map;relations;states;core;transact(o,n){let T=this.toolkit;this.toolkit=o,n(this),this.toolkit=T}store;alternates;[Symbol.dispose](){this.alternates.delete(this.store.config.name)}in(o){let n=o.config.name,T=this.alternates.get(n);if(T)return T;let t=new _f(this.options,this.defaultContent,o);return this.alternates.set(n,t),t.alternates=this.alternates,t}constructor(o,n,T=to.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=(E,K)=>{let m=this.toolkit.seek(E,K);if(m)return m;let c=this.store.molecules.get(l(K));if(c){let b=d(E,T);return Hn(c,b,T)}if(T.config.lifespan==="immortal")throw new yn(E,K,T);return vn(T,E,K)},this.toolkit={get:(...E)=>fo(T,...E),set:(...E)=>{Qo(T,...E)},find:this.retrieve,seek:(...E)=>Eo(T,...E),json:(E)=>Vo(T,E),dispose:(...E)=>{so(T,...E)}};let t=o.between[0],S=o.between[1],f=ft(T,{key:`${o.key}/relatedKeys`,default:()=>new No,mutable:!0,fromJson:(E)=>No.fromJSON(E),toJson:(E)=>E.toJSON()},["join","relations"]);this.core={findRelatedKeysState:f};let y=({get:E},K)=>E(this.retrieve(f,K)),A=(E,K,m)=>{let{set:c}=E,b=this.retrieve(f,K),w=this.retrieve(f,m);c(b,(i)=>i.add(m)),c(w,(i)=>i.add(K))},M=(E,K,m)=>{let{set:c}=E,b=this.retrieve(f,K),w=this.retrieve(f,m),i,N;c(b,(q)=>{if(q.delete(m),q.size===0)i=`"${K}"`;return q}),c(w,(q)=>{if(q.delete(K),q.size===0)N=`"${m}"`;return q})},F=(E,K,m)=>{let{get:c,set:b}=E,w=this.retrieve(f,K),i=c(w);for(let N of i){if(m.includes(N))continue;let ko=this.retrieve(f,N);b(ko,(Oo)=>{return Oo.delete(K),Oo})}b(w,(N)=>{return N.transaction((q)=>{q.clear();for(let ko of m){let Oo=y(E,ko),Sn=Oo.has(K);if(this.relations.cardinality==="1:n"){let cn=[];for(let H of Oo){if(H===K)continue;let Z=y(E,H);if(Z.delete(ko),Z.size===0)cn.push(H)}if(!Sn&&Oo.size>0)Oo.clear();for(let H of cn){let Z=[ko,H].sort(),Fo=`"${Z[0]}:${Z[1]}"`;this.molecules.delete(Fo)}}if(!Sn)Oo.add(K);q.add(ko)}return!0}),N})},$=(E,K,m)=>{let{set:c}=E,b=this.retrieve(f,K);c(b,(w)=>{return w.transaction((i)=>{for(let N of m)i.add(N);return!0}),w});for(let w of m){let i=this.retrieve(f,w);c(i,(N)=>{return N.add(K),N})}return!0},W=(E,K,m)=>{let c=y(E,K);return m?c.has(m):c.size>0},O={getRelatedKeys:(E)=>y(this.toolkit,E),addRelation:(E,K)=>{A(this.toolkit,E,K)},deleteRelation:(E,K)=>{M(this.toolkit,E,K)},replaceRelationsSafely:(E,K)=>{F(this.toolkit,E,K)},replaceRelationsUnsafely:(E,K)=>{$(this.toolkit,E,K)},has:(E,K)=>W(this.toolkit,E,K)},G,D,z;if(n){D=rn(T,{key:`${o.key}/content`,default:n},["join","content"]),z=YA(T,{key:`${o.key}/content-molecules`,new:class b{key;constructor(w,i){this.key=i}}});let E=({get:b},w)=>b(this.retrieve(D,w)),K=({set:b},w,i)=>{b(this.retrieve(D,w),i)},m=(b,w)=>{let i=T.molecules.get(`"${w}"`);if(i)this.toolkit.dispose(i),this.molecules.delete(`"${w}"`)};G=Object.assign(O,{getContent:(b)=>{return E(this.toolkit,b)},setContent:(b,w)=>{K(this.toolkit,b,w)},deleteContent:(b)=>{m(this.toolkit,b)}})}else G=O;let Y=new Fn(o,{externalStore:G,isAType:o.isAType,isBType:o.isBType,makeContentKey:(...E)=>{let K=E.sort(),m=`${K[0]}:${K[1]}`,[c,b]=K.map((w)=>this.molecules.get(l(w)));if(T.config.lifespan==="immortal"&&c&&b){let w=U(T),i=pn(w,[c,b],z,m);this.molecules.set(`"${m}"`,d(i,w))}return m}}),B=()=>xn(T,{key:`${o.key}/singleRelatedKey`,get:(E)=>({get:K})=>{let m=this.retrieve(f,E),c=K(m);for(let b of c)return b;return null}},["join","keys"]),v=()=>{return xn(T,{key:`${o.key}/multipleRelatedKeys`,get:(E)=>({get:K})=>{let m=Of(f,T),c=this.retrieve(m,E);return K(c).members}},["join","keys"])},x=()=>xn(T,{key:`${o.key}/singleRelatedEntry`,get:(E)=>({get:K})=>{let m=this.retrieve(f,E),c=K(m);for(let b of c){let w=Y.isAType?.(E)?E:void 0,i=w===void 0?E:void 0;w??=b,i??=b;let N=Y.makeContentKey(w,i),q=this.retrieve(D,N),ko=K(q);return[b,ko]}return null}},["join","entries"]),a=()=>xn(T,{key:`${o.key}/multipleRelatedEntries`,get:(E)=>({get:K})=>{let m=Of(f,T),c=this.retrieve(m,E);return K(c).members.map((w)=>{let i=Y.isAType?.(E)?E:void 0,N=i===void 0?E:void 0;i??=w,N??=w;let q=Y.makeContentKey(i,N),ko=this.retrieve(D,q),Oo=K(ko);return[w,Oo]})}},["join","entries"]);switch(o.cardinality){case"1:1":{let E=B(),K=`${t}KeyOf${Ho(S)}`,m=`${S}KeyOf${Ho(t)}`,c={[K]:E,[m]:E},b;if(n){let w=x(),i=`${t}EntryOf${Ho(S)}`,N=`${S}EntryOf${Ho(t)}`,q={[i]:w,[N]:w};b=Object.assign(c,q)}else b=c;this.relations=Y,this.states=b;break}case"1:n":{let E=B(),K=v(),m=`${t}KeyOf${Ho(S)}`,c=`${S}KeysOf${Ho(t)}`,b={[m]:E,[c]:K},w;if(n){let i=x(),N=a(),q=`${t}EntryOf${Ho(S)}`,ko=`${S}EntriesOf${Ho(t)}`,Oo={[q]:i,[ko]:N};w=Object.assign(b,Oo)}else w=b;this.relations=Y,this.states=w;break}default:{let E=v(),K=`${t}KeysOf${Ho(S)}`,m=`${S}KeysOf${Ho(t)}`,c={[K]:E,[m]:E},b;if(n){let w=a(),i=`${t}EntriesOf${Ho(S)}`,N=`${S}EntriesOf${Ho(t)}`,q={[i]:w,[N]:w};b=Object.assign(c,q)}else b=c;this.relations=Y,this.states=b}}}}function oS(o,n,T=to.STORE){return Wf(T).set(o.key,new _f(o,n,T)),{key:o.key,type:"join",a:o.between[0],b:o.between[1],cardinality:o.cardinality}}function Wf(o){if("joins"in o&&o.joins instanceof Map)return o.joins;let n=new Map;return o.joins=n,n}function Jt(o,n){let T=Wf(n),t=T.get(o.key);if(t===void 0){if(t=Wf(to.STORE).get(o.key)?.in(n),t===void 0)throw new Error(`Join "${o.key}" not found in store "${n.config.name}"`);T.set(o.key,t)}return t}function nS(o,n,T){let t=Jt(o,T),S;switch(o.cardinality){case"1:1":{let f=`${o.a}KeyOf${Ho(o.b)}`,y=`${o.b}KeyOf${Ho(o.a)}`;S={get[f](){let M=t.states[f];return t.retrieve(M,n)},get[y](){let M=t.states[y];return t.retrieve(M,n)}};let A=`${o.a}EntryOf${Ho(o.b)}`;if(A in t.states){let M=`${o.b}EntryOf${Ho(o.a)}`;Object.assign(S,{get[A](){let F=t.states[A];return t.retrieve(F,n)},get[M](){let F=t.states[M];return t.retrieve(F,n)}})}break}case"1:n":{let f=`${o.a}KeyOf${Ho(o.b)}`,y=`${o.b}KeysOf${Ho(o.a)}`;S={get[f](){let M=t.states[f];return t.retrieve(M,n)},get[y](){let M=t.states[y];return t.retrieve(M,n)}};let A=`${o.a}EntryOf${Ho(o.b)}`;if(A in t.states){let M=`${o.b}EntriesOf${Ho(o.a)}`;Object.assign(S,{get[A](){let F=t.states[A];return t.retrieve(F,n)},get[M](){let F=t.states[M];return t.retrieve(F,n)}})}break}case"n:n":{let f=`${o.a}KeysOf${Ho(o.b)}`,y=`${o.b}KeysOf${Ho(o.a)}`;S={get[f](){let M=t.states[f];return t.retrieve(M,n)},get[y](){let M=t.states[y];return t.retrieve(M,n)}};let A=`${o.a}EntriesOf${Ho(o.b)}`;if(A in t.states){let M=`${o.b}EntriesOf${Ho(o.a)}`;Object.assign(S,{get[A](){let F=t.states[A];return t.retrieve(F,n)},get[M](){let F=t.states[M];return t.retrieve(F,n)}})}}}return S}function GA(o,n){return nS(o,n,to.STORE)}function TS(o,n,T){let t=Jt(o,T),S=U(T);if(yo(S)){let{toolkit:f}=S.transactionMeta;t.transact(f,({relations:y})=>{n(y)})}else n(t.relations)}function NJ(o,n){return Jt(o,n).core.findRelatedKeysState}function zA(o){return NJ(o,to.STORE)}function tS(o){return{store:o}}function fo(o,...n){let T,t,S;if(n.length===1){if(T=n[0],T.type!=="molecule"){if(t=at(o,T)??null,t)S=T.family?jo(T.family.subKey):null,T=Ao(o,t,S)}}else{t=n[0],S=n[1];let f;if(t.type==="molecule_family")f=Eo(o,t,S)??mT(t,S);else f=Ao(o,t,S);T=f}if("counterfeit"in T&&"family"in T){t=T.type==="molecule"?d(T.family,o):o.families.get(T.family.key);let f=T.type==="molecule"?T.key:T.family.subKey,y=o.disposalTraces.buffer.find((A)=>A?.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}".`,y?`This state was previously disposed:
|
|
5
|
+
${y.trace}`:"No previous disposal trace was found."),t.type){case"atom_family":case"mutable_atom_family":return o.defaults.get(t.key);case"selector_family":case"readonly_selector_family":{if(o.defaults.has(t.key))return o.defaults.get(T.family.key);let A=d(t,o).default(f);return o.defaults.set(t.key,A),A}case"molecule_family":throw new yn(t,f,o)}}switch(T.type){case"atom":case"mutable_atom":case"selector":case"readonly_selector":return an(d(T,o),o);case"molecule":return d(T,o).instance}}class QT{key;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 t of o)this.above.set(t.stringKey,t)}}function HA(o){return o[0].toUpperCase()+o.slice(1)}function pn(o,n,T,t,...S){let f=fA(o),y=U(o),A=l(t);y.moleculeInProgress=A;let M=Array.isArray(n)?n:[n],F=M.map((Y)=>{if(Y instanceof QT)return Y;let B=l(Y.key),v=o.molecules.get(B);if(!v)throw new Error(`Molecule ${B} not found in store "${o.config.name}"`);return v}),$=new QT(F,t,T);y.molecules.set(A,$);for(let Y of F)Y.below.set($.stringKey,$);let W={get:(...Y)=>fo(U(f),...Y),set:(...Y)=>{Qo(U(f),...Y)},seek:(Y,B)=>Eo(U(f),Y,B),json:(Y)=>Vo(U(f),Y),run:(Y,B=HT())=>un(Y,B,U(o)),make:(Y,B,v,...x)=>pn(U(f),Y,B,v,...x),dispose:(Y)=>{so(U(f),Y)},env:()=>tS(U(f)),bond:(Y,B)=>{if(Y.type==="join"){let{as:v}=B,x=Jt(Y,f);x.molecules.set(A,$),$.joins.set(Y.key,x);let a=O.subject.subscribe(`join:${Y.key}-${A}`,(w)=>{if(w.type==="molecule_disposal"){if(l(w.token.key)===A)a(),x.molecules.delete(A)}});if(v===null)return;let E=Y.a===v?Y.b:Y.a,K=GA(Y,t),m=K[`${E}KeysOf${HA(v)}`],c=K[`${E}EntriesOf${HA(v)}`],b={relatedKeys:m};if(c)b=Object.assign(b,{relatedEntries:c});return b}return Hn($,d(Y,f),U(f))},claim:(Y,B)=>{let{exclusive:v}=B,x=U(o).molecules.get(l(Y.key));if(x)if(v){for(let a of x.above.values())a.below.delete(x.stringKey);x.above.clear(),x.above.set($.stringKey,$),$.below.set(x.stringKey,x)}else x.above.set($.stringKey,$),$.below.set(x.stringKey,x)},spawn:(Y,B,...v)=>pn(U(o),[$],d(Y,o),B,...v)},O=d(T,o),G=O.new;$.instance=new G(W,t,...S);let D={type:"molecule",key:t,family:T},z={type:"molecule_creation",subType:"classic",token:D,family:T,context:M,params:S};if(Bo(y))O.subject.next(z);else if(yo(y)&&y.on.transactionApplying.state===null)y.transactionMeta.update.updates.push(z);return y.moleculeInProgress=null,D}function wf(o,n,T){switch(n){case"newValue":{mA(o,T);break}case"oldValue":{so(T,o.token);break}}}function Kf(o,n,T){switch(n){case"newValue":{so(T,o.token);break}case"oldValue":{mA(o,T),T.valueMap.set(o.token.key,o.value);break}}}function mA(o,n){let{family:T}=o.token;if(T){let t=n.families.get(T.key);if(t)Ao(n,t,jo(T.subKey))}}function Xf(o,n,T){switch(n){case"newValue":switch(o.subType){case"classic":pn(T,o.context,o.family,o.token.key,...o.params);break;case"modern":Mf(T,o.provenance,o.key);break}break;case"oldValue":switch(o.subType){case"classic":so(T,o.token);break;case"modern":Ft(T,o.key);break}break}}function Ef(o,n,T){switch(n){case"newValue":switch(o.subType){case"classic":so(T,o.token);break;case"modern":Ft(T,o.key);break}break;case"oldValue":switch(o.subType){case"classic":{let t=pn(T,o.context,o.family,o.token.key);for(let[S,f]of o.values){let y=`${S}(${l(t.key)})`,A=d(t,T),M=A.tokens.has(y),F=T.families.get(S);if(F&&!M)Hn(A,F,T);T.valueMap.set(y,f)}}break;case"modern":{Mf(T,o.provenance,o.key);for(let[t,S]of o.values){let f=T.families.get(t);if(f){Ao(T,f,o.key);let y=`${t}(${l(o.key)})`;T.valueMap.set(y,S)}}}}break}}function SS(o,n,T){let t=o==="newValue"?n.updates:[...n.updates].reverse();for(let S of t)switch(S.type){case"atom_update":case"selector_update":st(o,S,T);break;case"state_creation":wf(S,o,T);break;case"state_disposal":Kf(S,o,T);break;case"molecule_creation":Xf(S,o,T);break;case"molecule_disposal":Ef(S,o,T);break;case"transaction_update":SS(o,S,T);break}}function QA(o,n,T){if(Bo(T)&&o)T.transactionMeta.epoch.set(o,n)}function DA(o,n,T){if(!Bo(T))return;let S=T.transactionMeta.actionContinuities.getRelatedKey(o);if(S!==void 0)T.transactionMeta.epoch.set(S,n)}var UA=(o,n)=>{let T=U(n),{parent:t}=T;if(t===null||!yo(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,t.child=null,t.on.transactionApplying.next(T.transactionMeta);let{updates:S}=T.transactionMeta.update;if(n.logger.info("\uD83D\uDEC4","transaction",T.transactionMeta.update.key,`Applying transaction with ${S.length} updates:`,S),SS("newValue",T.transactionMeta.update,t),Bo(t))DA(T.transactionMeta.update.key,T.transactionMeta.update.epoch,t),d({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(yo(t))t.transactionMeta.update.updates.push(T.transactionMeta.update);t.on.transactionApplying.next(null)};function VA(o,n,T){if(!Bo(T))return;let{epoch:S,actionContinuities:f}=T.transactionMeta;if(f.set(o,n),!S.has(o))S.set(o,-1)}class On extends Map{source;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 BA=(o,n,T,t)=>{let S=U(T),f={parent:S,child:null,on:S.on,loggers:S.loggers,logger:S.logger,config:S.config,atoms:new On(S.atoms),atomsThatAreDefault:new Set(S.atomsThatAreDefault),families:new On(S.families),operation:{open:!1},readonlySelectors:new On(S.readonlySelectors),timelines:new On(S.timelines),timelineTopics:new Fn(S.timelineTopics.toJSON()),trackers:new Map,transactions:new On(S.transactions),selectorAtoms:new Fn(S.selectorAtoms.toJSON()),selectorGraph:new Fn(S.selectorGraph.toJSON(),{makeContentKey:(...F)=>F.sort().join(":")}),selectors:new On(S.selectors),valueMap:new On(S.valueMap),defaults:S.defaults,disposalTraces:T.disposalTraces.copy(),molecules:new On(S.molecules),moleculeFamilies:new On(S.moleculeFamilies),moleculeInProgress:S.moleculeInProgress,miscResources:new On(S.miscResources)},y=CA(o,T),A={phase:"building",update:{type:"transaction_update",key:o,id:t,epoch:y===void 0?Number.NaN:y+1,updates:[],params:n,output:void 0},toolkit:{get:(...F)=>fo(M,...F),set:(...F)=>{Qo(M,...F)},run:(F,$=HT())=>un(F,$,M),find:(F,$)=>Ao(M,F,$),seek:(F,$)=>Eo(M,F,$),json:(F)=>Vo(M,F),make:(F,$,W,...O)=>pn(M,F,$,W,...O),dispose:(...F)=>{so(M,...F)},env:()=>tS(M)}},M=Object.assign(f,{transactionMeta:A});return S.child=M,T.logger.info("\uD83D\uDEEB","transaction",o,"Building transaction with params:",n),M};function Jf(o,n){let T={key:o.key,type:"transaction",run:(f,y)=>{let A=BA(o.key,f,n,y);try{let M=U(n),{toolkit:F}=A.transactionMeta,$=o.do(F,...f);return UA($,M),$}catch(M){throw FA(t),n.logger.warn("\uD83D\uDCA5","transaction",o.key,"caught:",M),M}},install:(f)=>Jf(o,f),subject:new s},t=U(n);t.transactions.set(T.key,T);let S=go(T);return n.on.transactionCreation.next(S),S}function CA(o,n){let T=Bo(n),t=T?n.transactionMeta.actionContinuities.getRelatedKey(o):void 0;return T&&t!==void 0?n.transactionMeta.epoch.get(t):void 0}class fS{_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(){let o=new fS([...this._buffer]);return o._index=this._index,o}}class LA{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 fS(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 kf("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[,t]of n.families){if(t.internalRoles?.includes("mutable")||t.internalRoles?.includes("join"))continue;t.install(this)}let T=new Set;for(let[,t]of n.atoms){if(T.has(t.key))continue;if(t.install(this),t.type==="mutable_atom"){let S=Vo(n,t),f=qn(t);T.add(S.key),T.add(f.key)}}for(let[,t]of n.readonlySelectors)t.install(this);for(let[,t]of n.selectors){if(T.has(t.key))continue;t.install(this)}for(let[,t]of n.transactions)t.install(this);for(let[,t]of n.timelines)t.install(this)}}}var to={get STORE(){if(!globalThis.ATOM_IO_IMPLICIT_STORE)globalThis.ATOM_IO_IMPLICIT_STORE=new LA({name:"IMPLICIT_STORE",lifespan:"ephemeral"});return globalThis.ATOM_IO_IMPLICIT_STORE}};function d(o,n){let T,t=n;while(t!==null){switch(o.type){case"atom":case"mutable_atom":T=t.atoms.get(o.key);break;case"selector":T=t.selectors.get(o.key);break;case"readonly_selector":T=t.readonlySelectors.get(o.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":T=t.families.get(o.key);break;case"timeline":T=t.timelines.get(o.key);break;case"transaction":T=t.transactions.get(o.key);break;case"molecule":T=t.molecules.get(l(o.key));break;case"molecule_family":T=t.moleculeFamilies.get(o.key);break}if(T)return T;t=t.child}throw new yn(o,n)}function yS(o,n){let T;T=d(o,n);let{family:t}=o;for(let y of T.joins.values())y.relations.delete(T.key),y.molecules.delete(T.stringKey);let S=[];for(let y of T.above.values())S.push(go(y));let f=[];for(let y of T.tokens.values()){let A=y.family;f.push([A.key,n.valueMap.get(y.key)])}if(t){let y=d(t,n),A={type:"molecule_disposal",subType:"classic",token:o,family:t,context:S,values:f};if(o.family)A.family=o.family;for(let F of T.tokens.values())so(n,F);for(let F of T.below.values())if(F.dependsOn==="all")yS(F,n);else if(F.above.delete(T.stringKey),F.above.size===0)yS(F,n);if(T.below.clear(),yo(n)&&n.transactionMeta.phase==="building")n.transactionMeta.update.updates.push(A);else y.subject.next(A);n.molecules.delete(T.stringKey)}for(let y of T.above.values())y.below.delete(T.stringKey)}function vn(o,n,T){let t=o.families.get(n.key);if(t===void 0)throw new yn(n,o);let S=t(T),f=U(o);if(S.family&&f.moleculeInProgress===null){if(Bo(f))switch(S.type){case"atom":case"mutable_atom":o.on.atomCreation.next(S);break;case"selector":case"readonly_selector":o.on.selectorCreation.next(S);break}else if(yo(f)&&f.on.transactionApplying.state===null)f.transactionMeta.update.updates.push({type:"state_creation",token:S})}return S}function Eo(o,n,T){let t=l(T),S=`${n.key}(${t})`,f=U(o),y;switch(n.type){case"atom_family":case"mutable_atom_family":y=f.atoms.get(S);break;case"selector_family":y=f.selectors.get(S);break;case"readonly_selector_family":y=f.readonlySelectors.get(S);break;case"molecule_family":y=f.molecules.get(l(T))}if(y)return go(y);return y}function Ao(o,n,T){let t=Eo(o,n,T);if(t)return t;let S=o.molecules.get(l(T));if(S)return Hn(S,n,o);if(o.config.lifespan==="immortal"){let f=mT(n,T);return o.logger.error("\u274C",f.type,f.key,`was not found in store "${o.config.name}"; returned a counterfeit token.`),f}return t=vn(o,n,T),t}function so(o,...n){let T,t;if(n.length===1)T=n[0],t=T.key;else{let f=n[0],y=n[1];T=f.type==="molecule_family"?Eo(o,f,y)??mT(f,y):Ao(o,f,y)}try{d(T,o)}catch(f){let y=o.disposalTraces.buffer.find((A)=>A?.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}".`,y?`
|
|
6
|
+
This state was most recently disposed
|
|
7
|
+
${y.trace}`:"No previous disposal trace was found.");return}switch(T.type){case"atom":case"mutable_atom":Yf(T,o);break;case"selector":case"readonly_selector":IA(T,o);break;case"molecule":yS(T,o);break}let{stack:S}=new Error;if(S){let f=S?.split(`
|
|
8
|
+
`)?.slice(3)?.join(`
|
|
9
|
+
`);o.disposalTraces.add({key:T.key,trace:f})}}var AS=(o,n)=>U(n).atoms.has(o),hJ=(o,n)=>U(n).selectors.has(o),bJ=(o,n)=>U(n).readonlySelectors.has(o),rA=(o,n)=>AS(o,n)||hJ(o,n)||bJ(o,n);var MS=(o,n)=>{return U(n).selectorGraph.getRelationEntries({downstreamSelectorKey:o}).filter(([t,{source:S}])=>S!==o).map(([t,{source:S}])=>S).filter((t)=>rA(t,n))};var Gf=(o,n,T)=>{let t=[],S=MS(o,T);while(S.length>0){let f=S.shift();if(n.has(f))continue;if(n.add(f),!AS(f,T))S.push(...MS(f,T));else if(!t.includes(f))t.push(f)}return t},jA=(o,n)=>{let T=o.key,t=MS(T,n),S=new Set;return t.flatMap((f)=>AS(f,n)?f:Gf(f,S,n))};var NA=(o,n,T,t)=>{let S=U(t);if(n.type==="atom"||n.type==="mutable_atom")S.selectorAtoms.set({selectorKey:o,atomKey:n.key}),t.logger.info("\uD83D\uDD0D","selector",o,`discovers root atom "${n.key}"`);else{let f=Gf(n.key,T,t);t.logger.info("\uD83D\uDD0D","selector",o,`discovers root atoms: [ ${f.map((y)=>`"${y}"`).join(", ")} ]`);for(let y of f)S.selectorAtoms=S.selectorAtoms.set({selectorKey:o,atomKey:y})}T.add(n.key)};var FS=(o,n,T)=>({get:(...t)=>{let S=U(T),f;if(t.length===2){let[M,F]=t;switch(M.type){case"molecule_family":return fo(T,M,F);default:if(T.config.lifespan==="ephemeral")f=Ao(T,M,F);else{let $=Eo(T,M,F);if($)f=$;else throw new yn(M,F,T)}}}else[f]=t;if(f.type==="molecule")return fo(T,f);let y=d(f,T),A=an(y,T);return T.logger.info("\uD83D\uDD0C","selector",o,`registers dependency ( "${f.key}" =`,A,")"),S.selectorGraph.set({upstreamSelectorKey:f.key,downstreamSelectorKey:o},{source:f.key}),NA(o,f,n,T),A},set:(...t)=>{let S,f;if(t.length===2)S=t[0],f=t[1];else{let M=t[0],F=t[1];f=t[2];let $=T.config.lifespan==="ephemeral"?Ao(T,M,F):Eo(T,M,F);if(!$)throw new yn(M,F,T);S=$}let y=U(T),A=d(S,y);ut(A,f,y)},find:(t,S)=>Ao(T,t,S),seek:(t,S)=>Eo(T,t,S),json:(t)=>Vo(T,t)});var yt=(o,n,T)=>{let t=U(o),S=new s,f=new Set,{get:y,find:A,seek:M,json:F}=FS(n.key,f,t),$=()=>{let D=n.get({get:y,find:A,seek:M,json:F});return Wn(n.key,D,S,U(o)),f.clear(),D},W={...n,subject:S,install:(D)=>yt(D,n,T),get:$,type:"readonly_selector",...T&&{family:T}};t.readonlySelectors.set(n.key,W);let O=$();o.logger.info("\u2728",W.type,W.key,"=",O);let G={key:n.key,type:"readonly_selector"};if(T)G.family=T;return G};var Rt=(o,n,T)=>{let t=U(o),S=new s,f=new Set,y=FS(n.key,f,t),{find:A,get:M,seek:F,json:$}=y,W={find:A,get:M,seek:F,json:$},O=(B=n.get,v=U(o))=>{let x=B(W);return Wn(n.key,x,S,v),f.clear(),x},D={...n,subject:S,install:(B)=>Rt(B,n,T),get:O,set:(B)=>{let v=U(o),x=O(n.get,v),a=dt(B)(x);if(o.logger.info("\uD83D\uDCDD","selector",n.key,"set (",x,"->",a,")"),Wn(n.key,a,S,v),UT(v,n.key),Bo(v))S.next({newValue:a,oldValue:x});n.set(y,a)},type:"selector",...T&&{family:T}};t.selectors.set(n.key,D);let z=O();o.logger.info("\u2728",D.type,D.key,"=",z);let Y={key:n.key,type:"selector"};if(T)Y.family=T;return Y};function Gn(o,n){if("set"in n){let S=Rt(o,n,void 0);return o.on.selectorCreation.next(S),S}let t=yt(o,n,void 0);return o.on.selectorCreation.next(t),t}function IA(o,n){let T=U(n),{key:t}=o,S=d(o,T);if(!S.family)n.logger.error("\u274C","selector",t,"Standalone selectors cannot be disposed.");else{let f=T.molecules.get(S.family.subKey);if(f)f.tokens.delete(t);switch(o.type){case"selector":T.selectors.delete(t),d({key:S.family.key,type:"selector_family"},n).subject.next({type:"state_disposal",token:o});break;case"readonly_selector":T.readonlySelectors.delete(t),d({key:S.family.key,type:"readonly_selector_family"},n).subject.next({type:"state_disposal",token:o});break}if(T.valueMap.delete(t),T.selectorAtoms.delete(t),T.selectorGraph.delete(t),n.logger.info("\uD83D\uDD25",o.type,t,"deleted"),yo(T)&&T.transactionMeta.phase==="building")T.transactionMeta.update.updates.push({type:"state_disposal",token:o});else n.on.selectorDisposal.next(o)}}function Mt(o,n,T){let t={key:n.key,type:"selector_family"},S=o.families.get(n.key);if(S)o.logger.error("\u2757","selector_family",n.key,`Overwriting an existing ${zn(S)} "${S.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let f=new s,A=Object.assign((M)=>{let F=l(M),$={key:n.key,subKey:F},W=`${n.key}(${F})`,O=U(o),G=Rt(O,{key:W,get:n.get(M),set:n.set(M)},$);return f.next({type:"state_creation",token:G}),G},t,{internalRoles:T,subject:f,install:(M)=>Mt(M,n),default:(M)=>{return n.get(M)({get:(...$)=>fo(o,...$),find:($,W)=>Ao(o,$,W),seek:($,W)=>Eo(o,$,W),json:($)=>Vo(o,$)})}});return o.families.set(n.key,A),t}function hA(o,n,T=to.STORE){let t=Mt(T,{key:`${o.key}:JSON`,get:(f)=>({seek:y,get:A})=>{let M=y(o,f);if(M)return n.toJson(A(M));let F=l(f),$=T.molecules.get(F);if($){let O=Hn($,o,T);return n.toJson(A(O))}if(T.config.lifespan==="immortal")throw new Error(`No molecule found for key "${F}"`);let W=vn(T,o,f);return n.toJson(A(W))},set:(f)=>({seek:y,set:A},M)=>{let F=y(o,f);if(F)A(F,n.fromJson(M));else{let $=l(f),W=T.molecules.get($);if(W){let O=Hn(W,o,T);A(O,n.fromJson(M))}else{if(T.config.lifespan==="immortal")throw new Error(`No molecule found for key "${$}"`);A(vn(T,o,f),n.fromJson(M))}}}},["mutable","json"]);return d(o,T).subject.subscribe(`store=${T.config.name}::json-selector-family`,(f)=>{if(f.token.family)Eo(T,t,jo(f.token.family.subKey))}),t}var jo=(o)=>JSON.parse(o),l=(o)=>JSON.stringify(o),o4=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var bA=(o,n)=>{let T=U(n);if(T.operation.open)return T.operation.prev.get(o.key);return T.valueMap.get(o.key)};var mf=(o,n)=>{let T=U(n);return jA(o,n).map((S)=>{let f=T.atoms.get(S);if(f===void 0)throw new Error(`Atom "${S}", a dependency of selector "${o.key}", not found in store "${n.config.name}".`);return f.subject.subscribe(`${o.type}:${o.key}`,(y)=>{n.logger.info("\uD83D\uDCE2",o.type,o.key,"root",S,"went",y.oldValue,"->",y.newValue);let A=bA(o,T),M=an(o,T);n.logger.info("\u2728",o.type,o.key,"went",A,"->",M),o.subject.next({newValue:M,oldValue:A})})})};function lo(o,n,T,t){function S(W){if(t.operation.open){let O=t.on.operationClose.subscribe(`state subscription ${T}`,()=>{O(),n(W)})}else n(W)}let f=d(o,t);t.logger.info("\uD83D\uDC40",f.type,f.key,`Adding subscription "${T}"`);let y=f.type==="selector"||f.type==="readonly_selector",A=null,M=S;if(y)A=mf(f,t),M=(W)=>{if(A)A.length=0,A.push(...mf(f,t));S(W)};let F=f.subject.subscribe(T,M);return()=>{if(t.logger.info("\uD83D\uDE48",f.type,f.key,`Removing subscription "${T}"`),F(),A)for(let W of A)W()}}var zf=(o,n,T,t)=>{let S=d(o,t);t.logger.info("\uD83D\uDC40","timeline",o.key,`Adding subscription "${T}"`);let f=S.subject.subscribe(T,n);return()=>{t.logger.info("\uD83D\uDE48","timeline",o.key,`Removing subscription "${T}" from timeline`),f()}};var Hf=(o,n,T,t)=>{let S=d(o,t);t.logger.info("\uD83D\uDC40","transaction",o.key,`Adding subscription "${T}"`);let f=S.subject.subscribe(T,n);return()=>{t.logger.info("\uD83D\uDE48","transaction",o.key,`Removing subscription "${T}"`),f()}};class sn{Update;initializeState(o,n){let T=`*${o.key}`;n.atoms.delete(T),n.valueMap.delete(T);let t=o.family?{key:`*${o.family.key}`,subKey:o.family.subKey}:void 0,S=fn(n,{key:T,default:null},t);if(n.parent?.valueMap.has(T)){let f=n.parent.valueMap.get(T);n.valueMap.set(T,f)}return S}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(o,n,T){let t=`tracker:${T.config.name}:${yo(T)?T.transactionMeta.update.key:"main"}:${o.key}`,S=fo(T,o);this.unsubscribeFromInnerValue=S.subscribe(t,(f)=>{Qo(T,n,f)}),this.unsubscribeFromState=lo(o,(f)=>{if(f.newValue!==f.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=f.newValue.subscribe(t,(y)=>{Qo(T,n,y)})},t,T)}updateCore(o,n,T){let t=`tracker:${T.config.name}:${yo(T)?T.transactionMeta.update.key:"main"}:${o.key}`;lo(n,({newValue:S,oldValue:f})=>{let y=T.timelineTopics.getRelatedKey(n.key);if(y){if(T.timelines.get(y)?.timeTraveling){let F=zf({key:y,type:"timeline"},($)=>{F(),Qo(T,o,(W)=>{if($==="redo"&&S)W.do(S);else if($==="undo"&&f)W.undo(f);return W})},t,T);return}}let A=T.on.operationClose.subscribe(t,()=>{A();let M=fo(T,o),F=S===null?-1:M.getUpdateNumber(S),$=F-M.cacheUpdateNumber;if(S&&$===1)Qo(T,o,(W)=>(W.do(S),W));else T.logger.info("\u274C","mutable_atom",o.key,`could not be updated. Expected update number ${M.cacheUpdateNumber+1}, but got ${F}`)})},t,T)}mutableState;latestUpdateState;dispose;constructor(o,n){this.mutableState=o;let T=U(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 Wt(o,n,T){o.logger.info("\uD83D\uDD28","atom",n.key,`creating in store "${o.config.name}"`);let t=U(o),S=t.atoms.get(n.key);if(S&&S.type==="mutable_atom")return o.logger.error("\u274C","atom",n.key,"Tried to create atom, but it already exists in the store."),go(S);let f=new s,y={...n,type:"mutable_atom",install:(F)=>{return F.logger.info("\uD83D\uDEE0\uFE0F","atom",n.key,`installing in store "${F.config.name}"`),Wt(F,n,T)},subject:f};if(T)y.family=T;let A=n.default();t.atoms.set(y.key,y),$S(n.key,o),Wn(n.key,A,f,t);let M=go(y);if(n.effects){let F=0,$=[];for(let W of n.effects){let O=W({setSelf:(G)=>{Qo(o,M,G)},onSet:(G)=>lo(M,G,`effect[${F}]`,o)});if(O)$.push(O);++F}y.cleanup=()=>{for(let W of $)W()}}if(new sn(M,o),!T)SA(M,n,o);return M}class Qf{Update;latestUpdateAtoms;mutableAtoms;constructor(o,n){let T=rn(n,{key:`*${o.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=d(T,n),this.mutableAtoms=o,this.mutableAtoms.subject.subscribe(`store=${n.config.name}::tracker-atom-family`,(t)=>{if(t.token.family){let S=jo(t.token.family.subKey);Eo(n,this.latestUpdateAtoms,S),new sn(t.token,n)}}),this.latestUpdateAtoms.subject.subscribe(`store=${n.config.name}::tracker-atom-family`,(t)=>{if(t.token.family){let S=jo(t.token.family.subKey),f=Eo(n,this.mutableAtoms,S);if(f)new sn(f,n)}})}}function ft(o,n,T){let t={key:n.key,type:"mutable_atom_family"},S=o.families.get(n.key);if(S)o.logger.error("\u2757","mutable_atom_family",n.key,`Overwriting an existing ${zn(S)} "${S.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let f=new s,A=Object.assign((M)=>{let F=l(M),$={key:n.key,subKey:F},W=`${n.key}(${F})`,O=U(o),G={key:W,default:()=>n.default(M),toJson:n.toJson,fromJson:n.fromJson,mutable:!0};if(n.effects)G.effects=n.effects(M);let D=Wt(O,G,$);return f.next({type:"state_creation",token:D}),D},t,{subject:f,install:(M)=>ft(M,n),toJson:n.toJson,fromJson:n.fromJson,internalRoles:T});return o.families.set(n.key,A),hA(A,n,o),new Qf(A,o),t}var Of=(o,n)=>{let T=U(n),t=`${o.key}:JSON`;return T.families.get(t)};var Vo=(o,n)=>{if(n.family){let t=U(o),f={key:`${n.family.key}:JSON`,type:"selector_family"},y=d(f,t),A=JSON.parse(n.family.subKey);return Ao(o,y,A)}return{type:"selector",key:`${n.key}:JSON`}};var qn=(o)=>{let T={type:"atom",key:`*${o.key}`};if(o.family)T.family={key:`*${o.family.key}`,subKey:o.family.subKey};return T};function wA(o){return typeof o==="object"&&o!==null&&"do"in o&&"undo"in o&&"subscribe"in o}function kt(o,n,T){let t=n.valueMap.get(o.key),S=T.valueMap.get(o.key);if(t===S){if(t===void 0)return typeof o.default==="function"?o.default():o.default;n.logger.info("\uD83D\uDCC3","atom",o.key,"copying");let f=o.toJson(t),y=o.fromJson(f);return T.valueMap.set(o.key,y),new sn(o,n),y}return S}function Wn(o,n,T,t){let S=t.valueMap.get(o);if(S instanceof St)S.use(n);if(n instanceof Promise){let f=new St(n);return t.valueMap.set(o,f),f.then((y)=>{Wn(o,y,T,t),T.next({newValue:y,oldValue:f})}).catch((y)=>{t.logger.error("\uD83D\uDCA5","state",o,"rejected:",y)}),f}return t.valueMap.set(o,n),n}var $A=(o,n)=>{let T=n.valueMap.get(o.key);if(o.type==="mutable_atom"&&yo(n)){let{parent:t}=n;T=kt(o,t,n)}return T},OA=(o,n)=>{let T=n.valueMap.get(o);if(T instanceof St){let t=T,S=n.selectors.get(o)??n.readonlySelectors.get(o);if(S)t.use(S.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 XA=(o,n)=>{return U(n).atomsThatAreDefault.has(o)},$S=(o,n)=>{let T=U(n);T.atomsThatAreDefault=new Set(T.atomsThatAreDefault).add(o)},EA=(o,n)=>{let T=U(n);T.atomsThatAreDefault=new Set(U(n).atomsThatAreDefault),T.atomsThatAreDefault.delete(o)};function fn(o,n,T){o.logger.info("\uD83D\uDD28","atom",n.key,`creating in store "${o.config.name}"`);let t=U(o),S=t.atoms.get(n.key);if(S&&S.type==="atom")return o.logger.error("\u274C","atom",n.key,"Tried to create atom, but it already exists in the store."),go(S);let f=new s,y={...n,type:"atom",install:(F)=>{return F.logger.info("\uD83D\uDEE0\uFE0F","atom",n.key,`installing in store "${F.config.name}"`),fn(F,n,T)},subject:f};if(T)y.family=T;let A=n.default;if(n.default instanceof Function)A=n.default();t.atoms.set(y.key,y),$S(n.key,o),Wn(n.key,A,f,t);let M=go(y);if(n.effects){let F=0,$=[];for(let W of n.effects){let O=W({setSelf:(G)=>{Qo(o,M,G)},onSet:(G)=>lo(M,G,`effect[${F}]`,o)});if(O)$.push(O);++F}y.cleanup=()=>{for(let W of $)W()}}return M}function AA(o,n){if("mutable"in n){let S=Wt(o,n,void 0);return o.on.atomCreation.next(S),S}let t=fn(o,n,void 0);return o.on.atomCreation.next(t),t}function Yf(o,n){let T=U(n),{key:t}=o,S=d(o,T);if(!S.family)n.logger.error("\u274C","atom",t,"Standalone atoms cannot be disposed.");else{S.cleanup?.();let f=n.valueMap.get(S.key);d({key:S.family.key,type:"atom_family"},n).subject.next({type:"state_disposal",token:o,value:f});let A=T.molecules.get(S.family.subKey);if(A)A.tokens.delete(t);if(T.atoms.delete(t),T.valueMap.delete(t),T.selectorAtoms.delete(t),T.atomsThatAreDefault.delete(t),n.timelineTopics.delete(t),o.type==="mutable_atom"){let M=qn(o);Yf(M,n),n.trackers.delete(t)}if(n.logger.info("\uD83D\uDD25","atom",t,"deleted"),yo(T)&&T.transactionMeta.phase==="building")T.transactionMeta.update.updates.push({type:"state_disposal",token:o});else n.on.atomDisposal.next(o)}}var Df=(o)=>{let n=fn(o,{key:"\uD83D\uDD0D Atom Token Index (Internal)",default:()=>{let T=new Map;for(let[t,S]of o.atoms)if(!t.includes("\uD83D\uDD0D")){let f=go(S);if(S.family){let y=T.get(S.family.key);if(!y||!("familyMembers"in y))y={key:S.family.key,familyMembers:new Map},T.set(S.family.key,y);y.familyMembers.set(S.family.subKey,f)}else T.set(t,f)}return T},effects:[({setSelf:T})=>{o.on.atomCreation.subscribe("introspection",(t)=>{if(t.key.includes("\uD83D\uDD0D"))return;T((S)=>{if(t.family){let{key:f,subKey:y}=t.family,A=S.get(f);if(A===void 0||!("familyMembers"in A))A={key:f,familyMembers:new Map},S.set(f,A);A.familyMembers.set(y,t)}else S.set(t.key,t);return S})}),o.on.atomDisposal.subscribe("introspection",(t)=>{T((S)=>{if(t.family){let{key:f,subKey:y}=t.family,A=S.get(f);if(A&&"familyMembers"in A){if(A.familyMembers.delete(y),A.familyMembers.size===0)S.delete(f)}}else S.delete(t.key);return S})})}]},void 0);return Gn(o,{key:"\uD83D\uDD0D Atom Token Index",get:({get:T})=>T(n)})};var Uf=(o)=>{let n=fn(o,{key:"\uD83D\uDD0D Selector Token Index (Internal)",default:()=>{let T=new Map;for(let t of[o.readonlySelectors,o.selectors])for(let[S,f]of t)if(!S.includes("\uD83D\uDD0D")){let y=go(f);if(f.family){let A=T.get(f.family.key);if(!A||!("familyMembers"in A))A={key:f.family.key,familyMembers:new Map},T.set(f.family.key,A);A.familyMembers.set(f.family.subKey,y)}else T.set(S,y)}return T},effects:[({setSelf:T})=>{o.on.selectorCreation.subscribe("introspection",(t)=>{if(t.key.includes("\uD83D\uDD0D"))return;T((S)=>{if(t.family){let{key:f,subKey:y}=t.family,A=S.get(f);if(A===void 0||!("familyMembers"in A))A={key:f,familyMembers:new Map},S.set(f,A);A.familyMembers.set(y,t)}else S.set(t.key,t);return S})}),o.on.selectorDisposal.subscribe("introspection",(t)=>{T((S)=>{if(t.family){let{key:f,subKey:y}=t.family,A=S.get(f);if(A&&"familyMembers"in A){if(A.familyMembers.delete(y),A.familyMembers.size===0)S.delete(f)}}else S.delete(t.key);return S})})}]},void 0);return Gn(o,{key:"\uD83D\uDD0D Selector Token Index",get:({get:T})=>T(n)})};class kS{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(t){try{if(o instanceof T)return{type:n,data:o}}catch(S){}}return null}}var Vf=new kS({number:(o)=>typeof o==="number",string:(o)=>typeof o==="string",boolean:(o)=>typeof o==="boolean",null:(o)=>o===null});function Bf(o){if(!o)return!1;return Object.getPrototypeOf(o)===Object.prototype}var Cf=new kS({object:Bf,array:(o)=>Array.isArray(o)}),cJ=new kS({...Vf.supported,...Cf.supported}),VT=(o)=>{if(o===void 0)return"undefined";let n=cJ.refine(o);if(n)return n.type;return Object.getPrototypeOf(o).constructor.name};class cA{store;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(o=to.STORE){this.store=o;this.atomIndex=Df(this.store),this.selectorIndex=Uf(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=cA.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");let n=Ff(this.atomIndex),T=Ff(this.selectorIndex),t=[...n.values()].filter((A)=>("familyMembers"in A)),S=[...T.values()].filter((A)=>("familyMembers"in A)),f=performance.now(),y=[];if(o.atomFamilies)for(let A of t){let M=A.familyMembers.values();for(let F of M){let W=this.statesCreatedAt.get(F.key)??this.auditorCreatedAt,O=f-W;y.push([F,O])}}if(o.selectorFamilies)for(let A of S){let M=A.familyMembers.values();for(let F of M){let W=this.statesCreatedAt.get(F.key)??this.auditorCreatedAt,O=f-W;y.push([F,O])}}return y}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}}var Lf=(o,n)=>{let T=(t,S)=>{let y=((M,F)=>{let $=n(M,F);if($)return $;return null})(t,S);if(y?.jobComplete??y?.pathComplete)return y;let A=Array.isArray(S)?S.map((M,F)=>[F,M]):Bf(S)?Object.entries(S):[];for(let[M,F]of A){let $=T([...t,M],F);if($?.jobComplete)return $}return{}};T([],o)};function xJ(o,n){return{summary:`${o<n?"+":"-"}${Math.abs(o-n)} (${o} \u2192 ${n})`}}function iJ(o,n){return{summary:`${o.length<n.length?"+":"-"}${Math.abs(o.length-n.length)} ("${o}" \u2192 "${n}")`}}function vJ(o,n){return{summary:`${o} \u2192 ${n}`}}function xA(o,n,T){let t="",S=[],f=[],y=[];return Lf(o,(A,M)=>{let F;for(F of A){let $=n[F];if($===void 0)f.push([F,JSON.stringify(M)]);else{let W=T(M,$);if(W.summary!=="No Change")y.push([F,W])}}}),Lf(n,(A,M)=>{let F;for(F of A)if(o[F]===void 0)S.push([F,JSON.stringify(M)])}),t=`\uFF5E${y.length} \uFF0B${S.length} \uFF0D${f.length}`,{summary:t,added:S,removed:f,changed:y}}function pJ(o,n,T){return xA(o,n,T)}class iA{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(o,n,T){this.leafRefinery=o,this.treeRefinery=n,this.leafDiffers={},this.treeDiffers={};for(let t of Object.keys(o.supported)){let S=T[t];this.leafDiffers[t]=S}for(let t of Object.keys(n.supported)){let S=T[t];this.treeDiffers[t]=S}}diff(o,n){if(o===n)return{summary:"No Change"};let T=this.leafRefinery.refine(o)??this.treeRefinery.refine(o),t=this.leafRefinery.refine(n)??this.treeRefinery.refine(n);if(T!==null&&t!==null){if(T.type===t.type){if(T.type in this.leafDiffers)return this.leafDiffers[T.type](T.data,t.data);if(T.type in this.treeDiffers)return this.treeDiffers[T.type](T.data,t.data,(A,M)=>this.diff(A,M))}}let S=VT(o),f=VT(n);if(S===f)return{summary:`${S} \u2192 ${f}`};return{summary:`Type change: ${S} \u2192 ${f}`}}}var k8=new iA(Vf,Cf,{number:xJ,string:iJ,boolean:vJ,null:()=>({summary:"No Change"}),object:xA,array:pJ});class vA 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 JS{key;type="continuity";globals=[];actions=[];perspectives=[];constructor(o){this.key=o}static existing=new vA;static create(o,n){let T=new JS(o),{type:t,globals:S,actions:f,perspectives:y}=n(T),A={type:t,key:o,globals:S,actions:f,perspectives:y};return JS.existing.set(o,A),A}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":{let[T,t]=o;this.perspectives.push({type:"realtime_perspective",resourceAtoms:T,viewAtoms:t})}break}return this}}function E8(o){let{key:n,config:T}=o,t=JS.create(n,T),{actions:S}=t;for(let f of S)VA(n,f.key,to.STORE);return QA(n,-1,to.STORE),t}var m8=DT({key:"usersInRoomIndex",mutable:!0,default:()=>new No,toJson:(o)=>o.toJSON(),fromJson:(o)=>No.fromJSON(o)}),If=DT({key:"roomIndex",default:()=>new No,mutable:!0,toJson:(o)=>o.toJSON(),fromJson:(o)=>No.fromJSON(o)}),qJ={enteredAtEpoch:0},Ot=oS({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(o)=>typeof o==="string",isBType:(o)=>typeof o==="string"},qJ),Q8=et({key:"usersInMyRoomView",get:(o)=>({find:n})=>{let T=zA(Ot);return[n(T,o)]}});import{spawn as ZJ}from"child_process";class BT{emit;listeners;globalListeners;handleEvent(o,...n){for(let t of this.globalListeners)t(o,...n);let T=this.listeners.get(o);if(T)for(let t of T)t(...n)}id="no_id_retrieved";constructor(o){this.emit=o;this.listeners=new Map,this.globalListeners=new Set}on(o,n){let 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){let 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 rf extends BT{process;key;logger;incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";handleLog(o){if(Array.isArray(o)){let[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((t,...S)=>{let f=JSON.stringify([t,...S])+"\x03",y=(A)=>{if(A.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",y)};return this.process.stdin.once("error",y),this.process.stdin.write(f),this});this.process=o;this.key=n;this.logger=T;if(this.process=o,this.process.stdout.on("data",(t)=>{let S=t.toString();if(S==="ALIVE")return;this.unprocessedEvents.push(...S.split("\x03"));let f=this.unprocessedEvents.shift();this.incompleteData+=f??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let y=jo(this.incompleteData);this.handleEvent(...y);while(this.unprocessedEvents.length>0){let A=this.unprocessedEvents.shift();if(A){if(this.unprocessedEvents.length===0)this.incompleteData=A;y=jo(A),this.handleEvent(...y)}}this.incompleteData=""}catch(y){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error(y)}}),this.process.stderr.on("data",(t)=>{let S=t.toString();this.unprocessedLogs.push(...S.split("\x03"));let f=this.unprocessedLogs.shift();this.incompleteLog+=f??"";try{let y=jo(this.incompleteLog);this.handleLog(y);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)y=jo(this.incompleteLog),this.handleLog(y)}catch(y){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error(y),console.error("\u274C\u274C\u274C\uFE0F")}}),o.pid)this.id=o.pid.toString()}}class pA extends BT{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 jf extends BT{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...o){this.process.stderr.write(l(o.map((n)=>n instanceof No?`{ ${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)=>{let 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)=>{let n=o.toString();this.unprocessedEvents.push(...n.split("\x03"));let T=this.unprocessedEvents.shift();this.incompleteData+=T??"";try{let t=jo(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",t),this.handleEvent(...t);while(this.unprocessedEvents.length>0){let S=this.unprocessedEvents.shift();if(S){if(this.unprocessedEvents.length===0)this.incompleteData=S;let f=jo(S);this.handleEvent(...f)}}this.incompleteData=""}catch(t){if(t instanceof Error)this.logger.error("\u2757",t.message,t.cause,t.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");let n=new pA(`user:${o}`);this.relays.set(o,n),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let T of this.relayServices){let t=T(n);if(t)n.disposalFunctions.push(t)}this.on(`user:${o}`,(...T)=>{n.in.next(T)}),n.out.subscribe("socket",(T)=>{this.emit(...T)})}),this.on("user-leaves",(o)=>{let n=this.relays.get(o);if(this.off(`relay:${o}`),n)n.dispose(),this.relays.delete(o)}),process.stdout.write("ALIVE")}relay(o){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(o)}}var Nf=$T({key:"roomArguments",default:["echo",["Hello World!"]]}),qA=et({key:"room",get:(o)=>async({get:n,find:T})=>{let t=T(Nf,o),S=n(t),[f,y]=S,A=await new Promise((M)=>{let F=ZJ(f,y,{env:process.env}),$=(W)=>{if(W.toString()==="ALIVE")F.stdout.off("data",$),M(F)};F.stdout.on("data",$)});return new rf(A,o)}});var o5=$t({key:"createRoom",do:({get:o,set:n,find:T},t,S,f)=>{let y=f?[S,f]:[S],A=T(Nf,t);n(A,y),n(If,($)=>$.add(t));let M=T(qA,t);return o(M)}}),n5=$t({key:"joinRoom",do:(o,n,T,t)=>{let S={enteredAtEpoch:t};return TS(Ot,(f)=>{f.set({room:n,user:T},S)},o.env().store),S}}),T5=$t({key:"leaveRoom",do:(o,n,T)=>{TS(Ot,(t)=>{t.delete({room:n,user:T})},o.env().store)}}),t5=$t({key:"destroyRoom",do:(o,n)=>{TS(Ot,(T)=>{T.delete({room:n})},o.env().store),o.set(If,(T)=>(T.delete(n),T))}});function hf(o,n){return n.map((T)=>{switch(T.type){case"transaction_update":{let t=hf(o,T.updates);return{...T,updates:t}}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 y5=$T({key:"redactor",default:{occlude:(o)=>o}}),CT=$T({key:"unacknowledgedUpdates",default:()=>[]});var ZA=$T({key:"sockets",default:null}),k5=DT({key:"socketsIndex",mutable:!0,default:()=>new No,toJson:(o)=>o.toJSON(),fromJson:(o)=>No.fromJSON(o)}),J5=DT({key:"usersIndex",mutable:!0,default:()=>new No,toJson:(o)=>o.toJSON(),fromJson:(o)=>No.fromJSON(o)}),bf=oS({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(o)=>o.startsWith("user::"),isBType:(o)=>o.startsWith("socket::")});function PA(o,n,T,t){let S=n.key;return function f(){let y=[];for(let M of n.globals){let F=M.type==="mutable_atom"?Vo(o,M):M,$=fo(o,F);y.push(F,$)}for(let M of n.perspectives){let{viewAtoms:F,resourceAtoms:$}=M,W=Ao(o,F,T),O=fo(o,W);o.logger.info("\uD83D\uDC41","atom",$.key,`${T} can see`,{viewAtoms:F,resourceAtoms:$,userView:O});for(let G of O){let D=G.type==="mutable_atom"?Vo(o,G):G,z=fo(o,D);y.push(D,z)}}let A=Bo(o)?o.transactionMeta.epoch.get(S)??null:null;t?.emit(`continuity-init:${S}`,A,y)}}function gA(o,n,T){let t=n.key;return function S(f){o.logger.info("\uD83D\uDECE\uFE0F","continuity",t,"received",f);let{key:y,id:A}=f,M=`tx-run:${y}:${A}`,F=`${M}:start`,$=`${M}:end`;performance.mark(F);try{un({type:"transaction",key:y},A,o)(...f.params)}catch(O){if(O instanceof Error)o.logger.error("\u274C","continuity",t,`failed to run transaction ${y} from ${T} with update ${A}`,O.message)}performance.mark($);let W=performance.measure(M,F,$);o?.logger.info("\uD83D\uDE80","transaction",y,A,T,W.duration)}}function lA(o,n,T,t){let S=n.key;return function f(y){if(o.logger.info("\uD83D\uDC4D","continuity",S,`${T} acknowledged epoch ${y}`),t[0]?.epoch===y)Qo(o,CT,T,(M)=>{return M.shift(),o.logger.info("\uD83D\uDC4D","continuity",S,`${T} unacknowledged update queue now has`,M.length,"items"),M})}}function eA(o,n,T,t){let S=n.key,f=[];for(let y of n.actions){let A=Hf(y,(M)=>{try{let F=n.globals.map((O)=>{if(O.type==="atom")return O.key;return qn(O).key}).concat(n.perspectives.flatMap((O)=>{let{viewAtoms:G}=O,D=Ao(o,G,T);return fo(o,D).map((Y)=>{return Y.type==="mutable_atom"?"*"+Y.key:Y.key})})),$=hf(F,M.updates),W={...M,updates:$};Qo(o,CT,T,(O)=>{if(W)O.push(W),O.sort((G,D)=>G.epoch-D.epoch),o.logger.info("\uD83D\uDC4D","continuity",S,`${T} unacknowledged update queue now has`,O.length,"items");return O}),t?.emit(`tx-new:${S}`,W)}catch(F){if(F instanceof Error)o.logger.error("\u274C","continuity",S,`${T} failed to send update from transaction ${y.key} to ${T}`,F.message)}},`sync-continuity:${S}:${T}`,o);f.push(A)}return f}function dA(o,n,T,t){let S=n.key,f=[];for(let y of n.perspectives){let{viewAtoms:A}=y,M=Ao(o,A,T),F=lo(M,({oldValue:$,newValue:W})=>{let O=$.map((Y)=>Y.key),G=W.map((Y)=>Y.key),D=$.filter((Y)=>!G.includes(Y.key)),z=W.filter((Y)=>!O.includes(Y.key)).flatMap((Y)=>{let B=Y.type==="mutable_atom"?Vo(o,Y):Y,v=fo(o,B);return[B,v]});if(o.logger.info("\uD83D\uDC41","atom",y.resourceAtoms.key,`${T} has a new perspective`,{oldKeys:O,newKeys:G,revealed:z,concealed:D}),z.length>0)t?.emit(`reveal:${S}`,z);if(D.length>0)t?.emit(`conceal:${S}`,D)},`sync-continuity:${S}:${T}:perspective:${y.resourceAtoms.key}`,o);f.push(F)}return f}function v5({socket:o,store:n=to.STORE}){return function T(t){let S=o,f=t.key,y=nS(bf,`socket::${S.id}`,n).userKeyOfSocket,A=fo(n,y);if(!A)return n.logger.error("\u274C","continuity",f,`Tried to create a synchronizer for a socket (${S.id}) that is not connected to a user.`),()=>{};let M=nS(bf,A,n).socketKeyOfUser,F=lo(M,({newValue:B})=>{if(n.logger.info("\uD83D\uDC4B","continuity",f,`seeing ${A} on new socket ${B}`),B===null){n.logger.warn("\u274C","continuity",f,`User (${A}) is not connected to a socket, waiting for them to reappear.`);return}let v=Ao(n,ZA,B);S=fo(n,v);for(let a of $)S?.emit(`tx-new:${f}`,a)},`sync-continuity:${f}:${A}`,n),$=fo(n,CT,A),W=[],O=dA(n,t,A,S),G=eA(n,t,A,S);W.push(...O,...G);let D=PA(n,t,A,o);S.off(`get:${f}`,D),S.on(`get:${f}`,D);let z=gA(n,t,A);S.off(`tx-run:${f}`,z),S.on(`tx-run:${f}`,z);let Y=lA(n,t,A,$);return S?.on(`ack:${f}`,Y),()=>{for(let B of W)B();S?.off(`ack:${f}`,Y),S?.off(`get:${f}`,D),S?.off(`tx-run:${f}`,z)}}}var{file:Lk,serve:a0}=globalThis.Bun;var J=Symbol.for("drizzle:entityKind"),WE=Symbol.for("drizzle:hasOwnEntityKind");function X(o,n){if(!o||typeof o!=="object")return!1;if(o instanceof n)return!0;if(!Object.prototype.hasOwnProperty.call(n,J))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(J in T&&T[J]===n[J])return!0;T=Object.getPrototypeOf(T)}return!1}class Ro{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[J]="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 cf{static[J]="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 mn=Symbol.for("drizzle:Name");class xf{static[J]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(o,n){if(this.reference=()=>{let{name:T,columns:t,foreignColumns:S}=o();return{name:T,columns:t,foreignTable:S[0].table,foreignColumns:S}},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 uA(o,this)}}class uA{constructor(o,n){this.table=o,this.reference=n.reference,this.onUpdate=n._onUpdate,this.onDelete=n._onDelete}static[J]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:o,columns:n,foreignColumns:T}=this.reference(),t=n.map((y)=>y.name),S=T.map((y)=>y.name),f=[this.table[mn],...t,T[0].table[mn],...S];return o??`${f.join("_")}_fk`}}function RS(o,...n){return o(...n)}function aA(o,n){return`${o[mn]}_${n.join("_")}_unique`}function sA(o,n,T){for(let t=n;t<o.length;t++){let S=o[t];if(S==="\\"){t++;continue}if(S==='"')return[o.slice(n,t).replace(/\\/g,""),t+1];if(T)continue;if(S===","||S==="}")return[o.slice(n,t).replace(/\\/g,""),t]}return[o.slice(n).replace(/\\/g,""),o.length]}function oM(o,n=0){let T=[],t=n,S=!1;while(t<o.length){let f=o[t];if(f===","){if(S||t===n)T.push("");S=!0,t++;continue}if(S=!1,f==="\\"){t+=2;continue}if(f==='"'){let[M,F]=sA(o,t+1,!0);T.push(M),t=F;continue}if(f==="}")return[T,t+1];if(f==="{"){let[M,F]=oM(o,t+1);T.push(M),t=F;continue}let[y,A]=sA(o,t,!1);T.push(y),t=A}return[T,t]}function nM(o){let[n]=oM(o,1);return n}function vf(o){return`{${o.map((n)=>{if(Array.isArray(n))return vf(n);if(typeof n==="string")return`"${n.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${n}`}).join(",")}}`}class h extends cf{foreignKeyConfigs=[];static[J]="PgColumnBuilder";array(o){return new tM(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:t})=>{return RS((S,f)=>{let y=new xf(()=>{let A=S();return{columns:[o],foreignColumns:[A]}});if(f.onUpdate)y.onUpdate(f.onUpdate);if(f.onDelete)y.onDelete(f.onDelete);return y.build(n)},T,t)})}buildExtraConfigColumn(o){return new TM(o,this.config)}}class V extends Ro{constructor(o,n){if(!n.uniqueName)n.uniqueName=aA(o,[n.name]);super(o,n);this.table=o}static[J]="PgColumn"}class TM extends V{static[J]="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 _t{static[J]="IndexedColumn";constructor(o,n,T,t){this.name=o,this.keyAsName=n,this.type=T,this.indexConfig=t}name;keyAsName;type;indexConfig}class tM extends h{static[J]="PgArrayBuilder";constructor(o,n,T){super(o,"array","PgArray");this.config.baseBuilder=n,this.config.size=T}build(o){let n=this.config.baseBuilder.build(o);return new pf(o,this.config,n)}}class pf extends V{constructor(o,n,T,t){super(o,n);this.baseColumn=T,this.range=t,this.size=n.size}size;static[J]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(o){if(typeof o==="string")o=nM(o);return o.map((n)=>this.baseColumn.mapFromDriverValue(n))}mapToDriverValue(o,n=!1){let T=o.map((t)=>t===null?null:X(this.baseColumn,pf)?this.baseColumn.mapToDriverValue(t,!0):this.baseColumn.mapToDriverValue(t));if(n)return T;return vf(T)}}var qf=Symbol.for("drizzle:isPgEnum");function SM(o){return!!o&&typeof o==="function"&&qf in o&&o[qf]===!0}class fM extends h{static[J]="PgEnumColumnBuilder";constructor(o,n){super(o,"string","PgEnumColumn");this.config.enum=n}build(o){return new yM(o,this.config)}}class yM extends V{static[J]="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}}function WS(o,n){return PJ(o,n,void 0)}function PJ(o,n,T){let t=Object.assign((S)=>new fM(S??"",t),{enumName:o,enumValues:n,schema:T,[qf]:!0});return t}class ho{static[J]="Subquery";constructor(o,n,T,t=!1){this._={brand:"Subquery",sql:o,selectedFields:n,alias:T,isWith:t}}}class wt extends ho{static[J]="WithSubquery"}var AM="0.37.0";var Zf,Pf,Wo={startActiveSpan(o,n){if(!Zf)return n();if(!Pf)Pf=Zf.trace.getTracer("drizzle-orm",AM);return RS((T,t)=>t.startActiveSpan(o,(S)=>{try{return n(S)}catch(f){throw S.setStatus({code:T.SpanStatusCode.ERROR,message:f instanceof Error?f.message:"Unknown error"}),f}finally{S.end()}}),Zf,Pf)}};var Yo=Symbol.for("drizzle:ViewBaseConfig");var OS=Symbol.for("drizzle:Schema"),_S=Symbol.for("drizzle:Columns"),MM=Symbol.for("drizzle:ExtraConfigColumns"),gf=Symbol.for("drizzle:OriginalName"),lf=Symbol.for("drizzle:BaseName"),wS=Symbol.for("drizzle:IsAlias"),FM=Symbol.for("drizzle:ExtraConfigBuilder"),gJ=Symbol.for("drizzle:IsDrizzleTable");class L{static[J]="Table";static Symbol={Name:mn,Schema:OS,OriginalName:gf,Columns:_S,ExtraConfigColumns:MM,BaseName:lf,IsAlias:wS,ExtraConfigBuilder:FM};[mn];[gf];[OS];[_S];[MM];[lf];[wS]=!1;[gJ]=!0;[FM]=void 0;constructor(o,n,T){this[mn]=this[gf]=o,this[OS]=n,this[lf]=T}}function _n(o){return o[mn]}function kT(o){return`${o[OS]??"public"}.${o[mn]}`}function ef(o){return o!==null&&o!==void 0&&typeof o.getSQL==="function"}function lJ(o){let 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}class bo{static[J]="StringChunk";value;constructor(o){this.value=Array.isArray(o)?o:[o]}getSQL(){return new r([this])}}class r{constructor(o){this.queryChunks=o}static[J]="SQL";decoder=kM;shouldInlineParams=!1;append(o){return this.queryChunks.push(...o.queryChunks),this}toQuery(o){return Wo.startActiveSpan("drizzle.buildSQL",(n)=>{let 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){let T=Object.assign({},n,{inlineParams:n.inlineParams||this.shouldInlineParams,paramStartIndex:n.paramStartIndex||{value:0}}),{casing:t,escapeName:S,escapeParam:f,prepareTyping:y,inlineParams:A,paramStartIndex:M}=T;return lJ(o.map((F)=>{if(X(F,bo))return{sql:F.value.join(""),params:[]};if(X(F,KS))return{sql:S(F.value),params:[]};if(F===void 0)return{sql:"",params:[]};if(Array.isArray(F)){let $=[new bo("(")];for(let[W,O]of F.entries())if($.push(O),W<F.length-1)$.push(new bo(", "));return $.push(new bo(")")),this.buildQueryFromSourceParams($,T)}if(X(F,r))return this.buildQueryFromSourceParams(F.queryChunks,{...T,inlineParams:A||F.shouldInlineParams});if(X(F,L)){let $=F[L.Symbol.Schema],W=F[L.Symbol.Name];return{sql:$===void 0?S(W):S($)+"."+S(W),params:[]}}if(X(F,Ro)){let $=t.getColumnCasing(F);if(n.invokeSource==="indexes")return{sql:S($),params:[]};let W=F.table[L.Symbol.Schema];return{sql:F.table[wS]||W===void 0?S(F.table[L.Symbol.Name])+"."+S($):S(W)+"."+S(F.table[L.Symbol.Name])+"."+S($),params:[]}}if(X(F,An)){let $=F[Yo].schema,W=F[Yo].name;return{sql:$===void 0?S(W):S($)+"."+S(W),params:[]}}if(X(F,$n)){if(X(F.value,oT))return{sql:f(M.value++,F),params:[F],typings:["none"]};let $=F.value===null?null:F.encoder.mapToDriverValue(F.value);if(X($,r))return this.buildQueryFromSourceParams([$],T);if(A)return{sql:this.mapInlineParam($,T),params:[]};let W=["none"];if(y)W=[y(F.encoder)];return{sql:f(M.value++,$),params:[$],typings:W}}if(X(F,oT))return{sql:f(M.value++,F),params:[F],typings:["none"]};if(X(F,r.Aliased)&&F.fieldAlias!==void 0)return{sql:S(F.fieldAlias),params:[]};if(X(F,ho)){if(F._.isWith)return{sql:S(F._.alias),params:[]};return this.buildQueryFromSourceParams([new bo("("),F._.sql,new bo(") "),new KS(F._.alias)],T)}if(SM(F)){if(F.schema)return{sql:S(F.schema)+"."+S(F.enumName),params:[]};return{sql:S(F.enumName),params:[]}}if(ef(F)){if(F.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([F.getSQL()],T);return this.buildQueryFromSourceParams([new bo("("),F.getSQL(),new bo(")")],T)}if(A)return{sql:this.mapInlineParam(F,T),params:[]};return{sql:f(M.value++,F),params:[F],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"){let 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 r.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 KS{constructor(o){this.value=o}static[J]="Name";brand;getSQL(){return new r([this])}}function $M(o){return typeof o==="object"&&o!==null&&"mapToDriverValue"in o&&typeof o.mapToDriverValue==="function"}var kM={mapFromDriverValue:(o)=>o},JM={mapToDriverValue:(o)=>o},TY={...kM,...JM};class $n{constructor(o,n=JM){this.value=o,this.encoder=n}static[J]="Param";brand;getSQL(){return new r([this])}}function R(o,...n){let T=[];if(n.length>0||o.length>0&&o[0]!=="")T.push(new bo(o[0]));for(let[t,S]of n.entries())T.push(S,new bo(o[t+1]));return new r(T)}((o)=>{function n(){return new r([])}o.empty=n;function T(M){return new r(M)}o.fromList=T;function t(M){return new r([new bo(M)])}o.raw=t;function S(M,F){let $=[];for(let[W,O]of M.entries()){if(W>0&&F!==void 0)$.push(F);$.push(O)}return new r($)}o.join=S;function f(M){return new KS(M)}o.identifier=f;function y(M){return new oT(M)}o.placeholder=y;function A(M,F){return new $n(M,F)}o.param=A})(R||(R={}));((o)=>{class n{constructor(T,t){this.sql=T,this.fieldAlias=t}static[J]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new n(this.sql,this.fieldAlias)}}o.Aliased=n})(r||(r={}));class oT{constructor(o){this.name=o}static[J]="Placeholder";getSQL(){return new r([this])}}function df(o,n){return o.map((T)=>{if(X(T,oT)){if(!(T.name in n))throw new Error(`No value for placeholder "${T.name}" was provided`);return n[T.name]}if(X(T,$n)&&X(T.value,oT)){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 An{static[J]="View";[Yo];constructor({name:o,schema:n,selectedFields:T,query:t}){this[Yo]={name:o,originalName:o,schema:n,selectedFields:T,query:t,isExisting:!t,isAlias:!1}}getSQL(){return new r([this])}}Ro.prototype.getSQL=function(){return new r([this])};L.prototype.getSQL=function(){return new r([this])};ho.prototype.getSQL=function(){return new r([this])};class LT{constructor(o){this.table=o}static[J]="ColumnAliasProxyHandler";get(o,n){if(n==="table")return this.table;return o[n]}}class Kt{constructor(o,n){this.alias=o,this.replaceOriginalName=n}static[J]="TableAliasProxyHandler";get(o,n){if(n===L.Symbol.IsAlias)return!0;if(n===L.Symbol.Name)return this.alias;if(this.replaceOriginalName&&n===L.Symbol.OriginalName)return this.alias;if(n===Yo)return{...o[Yo],name:this.alias,isAlias:!0};if(n===L.Symbol.Columns){let t=o[L.Symbol.Columns];if(!t)return t;let S={};return Object.keys(t).map((f)=>{S[f]=new Proxy(t[f],new LT(new Proxy(o,this)))}),S}let T=o[n];if(X(T,Ro))return new Proxy(T,new LT(new Proxy(o,this)));return T}}function XS(o,n){return new Proxy(o,new Kt(n,!1))}function jn(o,n){return new Proxy(o,new LT(new Proxy(o.table,new Kt(n,!1))))}function uf(o,n){return new r.Aliased(Xt(o.sql,n),o.fieldAlias)}function Xt(o,n){return R.join(o.queryChunks.map((T)=>{if(X(T,Ro))return jn(T,n);if(X(T,r))return Xt(T,n);if(X(T,r.Aliased))return uf(T,n);return T}))}class ES extends Error{static[J]="DrizzleError";constructor({message:o,cause:n}){super(o);this.name="DrizzleError",this.cause=n}}class af extends ES{static[J]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}function Mn(o,n){if($M(n)&&!ef(o)&&!X(o,$n)&&!X(o,oT)&&!X(o,Ro)&&!X(o,L)&&!X(o,An))return new $n(o,n);return o}var IT=(o,n)=>{return R`${o} = ${Mn(n,o)}`},RM=(o,n)=>{return R`${o} <> ${Mn(n,o)}`};function Et(...o){let n=o.filter((T)=>T!==void 0);if(n.length===0)return;if(n.length===1)return new r(n);return new r([new bo("("),R.join(n,new bo(" and ")),new bo(")")])}function WM(...o){let n=o.filter((T)=>T!==void 0);if(n.length===0)return;if(n.length===1)return new r(n);return new r([new bo("("),R.join(n,new bo(" or ")),new bo(")")])}function OM(o){return R`not ${o}`}var _M=(o,n)=>{return R`${o} > ${Mn(n,o)}`},wM=(o,n)=>{return R`${o} >= ${Mn(n,o)}`},KM=(o,n)=>{return R`${o} < ${Mn(n,o)}`},XM=(o,n)=>{return R`${o} <= ${Mn(n,o)}`};function EM(o,n){if(Array.isArray(n)){if(n.length===0)return R`false`;return R`${o} in ${n.map((T)=>Mn(T,o))}`}return R`${o} in ${Mn(n,o)}`}function YM(o,n){if(Array.isArray(n)){if(n.length===0)return R`true`;return R`${o} not in ${n.map((T)=>Mn(T,o))}`}return R`${o} not in ${Mn(n,o)}`}function GM(o){return R`${o} is null`}function zM(o){return R`${o} is not null`}function HM(o){return R`exists ${o}`}function mM(o){return R`not exists ${o}`}function QM(o,n,T){return R`${o} between ${Mn(n,o)} and ${Mn(T,o)}`}function DM(o,n,T){return R`${o} not between ${Mn(n,o)} and ${Mn(T,o)}`}function UM(o,n){return R`${o} like ${n}`}function VM(o,n){return R`${o} not like ${n}`}function BM(o,n){return R`${o} ilike ${n}`}function CM(o,n){return R`${o} not ilike ${n}`}function LM(o){return R`${o} asc`}function IM(o){return R`${o} desc`}class rM{static[J]="ConsoleLogWriter";write(o){console.log(o)}}class sf{static[J]="DefaultLogger";writer;constructor(o){this.writer=o?.writer??new rM}logQuery(o,n){let T=n.map((S)=>{try{return JSON.stringify(S)}catch{return String(S)}}),t=T.length?` -- params: [${T.join(", ")}]`:"";this.writer.write(`Query: ${o}${t}`)}}class oy{static[J]="NoopLogger";logQuery(){}}class on{static[J]="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 jM(o,n,T){let t={},S=o.reduce((f,{path:y,field:A},M)=>{let F;if(X(A,Ro))F=A;else if(X(A,r))F=A.decoder;else F=A.sql.decoder;let $=f;for(let[W,O]of y.entries())if(W<y.length-1){if(!(O in $))$[O]={};$=$[O]}else{let G=n[M],D=$[O]=G===null?null:F.mapFromDriverValue(G);if(T&&X(A,Ro)&&y.length===2){let z=y[0];if(!(z in t))t[z]=D===null?_n(A.table):!1;else if(typeof t[z]==="string"&&t[z]!==_n(A.table))t[z]=!1}}return f},{});if(T&&Object.keys(t).length>0){for(let[f,y]of Object.entries(t))if(typeof y==="string"&&!T[y])S[f]=null}return S}function wn(o,n){return Object.entries(o).reduce((T,[t,S])=>{if(typeof t!=="string")return T;let f=n?[...n,t]:[t];if(X(S,Ro)||X(S,r)||X(S,r.Aliased))T.push({path:f,field:S});else if(X(S,L))T.push(...wn(S[L.Symbol.Columns],f));else T.push(...wn(S,f));return T},[])}function Yt(o,n){let T=Object.keys(o),t=Object.keys(n);if(T.length!==t.length)return!1;for(let[S,f]of T.entries())if(f!==t[S])return!1;return!0}function YS(o,n){let T=Object.entries(n).filter(([,t])=>t!==void 0).map(([t,S])=>{if(X(S,r)||X(S,Ro))return[t,S];else return[t,new $n(S,o[L.Symbol.Columns][t])]});if(T.length===0)throw new Error("No values to set");return Object.fromEntries(T)}function NM(o,n){for(let T of n)for(let t of Object.getOwnPropertyNames(T.prototype)){if(t==="constructor")continue;Object.defineProperty(o.prototype,t,Object.getOwnPropertyDescriptor(T.prototype,t)||Object.create(null))}}function hM(o){return o[L.Symbol.Columns]}function Zn(o){return X(o,ho)?o._.alias:X(o,An)?o[Yo].name:X(o,r)?void 0:o[L.Symbol.IsAlias]?o[L.Symbol.Name]:o[L.Symbol.BaseName]}function So(o,n){return{name:typeof o==="string"&&o.length>0?o:"",config:typeof o==="object"?o:n}}function bM(o){if(typeof o!=="object"||o===null)return!1;if(o.constructor.name!=="Object")return!1;if("logger"in o){let n=typeof o.logger;if(n!=="boolean"&&(n!=="object"||typeof o.logger.logQuery!=="function")&&n!=="undefined")return!1;return!0}if("schema"in o){let n=typeof o.logger;if(n!=="object"&&n!=="undefined")return!1;return!0}if("casing"in o){let n=typeof o.logger;if(n!=="string"&&n!=="undefined")return!1;return!0}if("mode"in o){if(o.mode!=="default"||o.mode!=="planetscale"||o.mode!==void 0)return!1;return!0}if("connection"in o){let n=typeof o.connection;if(n!=="string"&&n!=="object"&&n!=="undefined")return!1;return!0}if("client"in o){let n=typeof o.client;if(n!=="object"&&n!=="function"&&n!=="undefined")return!1;return!0}if(Object.keys(o).length===0)return!0;return!1}class nT extends h{static[J]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(o){if(o){let{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){let{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}}class cM extends nT{static[J]="PgBigInt53Builder";constructor(o){super(o,"number","PgBigInt53")}build(o){return new xM(o,this.config)}}class xM extends V{static[J]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}}class iM extends nT{static[J]="PgBigInt64Builder";constructor(o){super(o,"bigint","PgBigInt64")}build(o){return new vM(o,this.config)}}class vM extends V{static[J]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(o){return BigInt(o)}}function pM(o,n){let{name:T,config:t}=So(o,n);if(t.mode==="number")return new cM(T);return new iM(T)}class qM extends h{static[J]="PgBigSerial53Builder";constructor(o){super(o,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new ZM(o,this.config)}}class ZM extends V{static[J]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}}class PM extends h{static[J]="PgBigSerial64Builder";constructor(o){super(o,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(o){return new gM(o,this.config)}}class gM extends V{static[J]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(o){return BigInt(o)}}function lM(o,n){let{name:T,config:t}=So(o,n);if(t.mode==="number")return new qM(T);return new PM(T)}class eM extends h{static[J]="PgBooleanBuilder";constructor(o){super(o,"boolean","PgBoolean")}build(o){return new dM(o,this.config)}}class dM extends V{static[J]="PgBoolean";getSQLType(){return"boolean"}}function Gt(o){return new eM(o??"")}class uM extends h{static[J]="PgCharBuilder";constructor(o,n){super(o,"string","PgChar");this.config.length=n.length,this.config.enumValues=n.enum}build(o){return new aM(o,this.config)}}class aM extends V{static[J]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function sM(o,n={}){let{name:T,config:t}=So(o,n);return new uM(T,t)}class oF extends h{static[J]="PgCidrBuilder";constructor(o){super(o,"string","PgCidr")}build(o){return new nF(o,this.config)}}class nF extends V{static[J]="PgCidr";getSQLType(){return"cidr"}}function TF(o){return new oF(o??"")}class tF extends h{static[J]="PgCustomColumnBuilder";constructor(o,n,T){super(o,"custom","PgCustomColumn");this.config.fieldConfig=n,this.config.customTypeParams=T}build(o){return new SF(o,this.config)}}class SF extends V{static[J]="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}}function fF(o){return(n,T)=>{let{name:t,config:S}=So(n,T);return new tF(t,S,o)}}class Pn extends h{static[J]="PgDateColumnBaseBuilder";defaultNow(){return this.default(R`now()`)}}class yF extends Pn{static[J]="PgDateBuilder";constructor(o){super(o,"date","PgDate")}build(o){return new GS(o,this.config)}}class GS extends V{static[J]="PgDate";getSQLType(){return"date"}mapFromDriverValue(o){return new Date(o)}mapToDriverValue(o){return o.toISOString()}}class AF extends Pn{static[J]="PgDateStringBuilder";constructor(o){super(o,"string","PgDateString")}build(o){return new zS(o,this.config)}}class zS extends V{static[J]="PgDateString";getSQLType(){return"date"}}function MF(o,n){let{name:T,config:t}=So(o,n);if(t?.mode==="date")return new yF(T);return new AF(T)}class FF extends h{static[J]="PgDoublePrecisionBuilder";constructor(o){super(o,"number","PgDoublePrecision")}build(o){return new $F(o,this.config)}}class $F extends V{static[J]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseFloat(o);return o}}function kF(o){return new FF(o??"")}class JF extends h{static[J]="PgInetBuilder";constructor(o){super(o,"string","PgInet")}build(o){return new RF(o,this.config)}}class RF extends V{static[J]="PgInet";getSQLType(){return"inet"}}function WF(o){return new JF(o??"")}class OF extends nT{static[J]="PgIntegerBuilder";constructor(o){super(o,"number","PgInteger")}build(o){return new _F(o,this.config)}}class _F extends V{static[J]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseInt(o);return o}}function HS(o){return new OF(o??"")}class wF extends h{static[J]="PgIntervalBuilder";constructor(o,n){super(o,"string","PgInterval");this.config.intervalConfig=n}build(o){return new KF(o,this.config)}}class KF extends V{static[J]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let o=this.fields?` ${this.fields}`:"",n=this.precision?`(${this.precision})`:"";return`interval${o}${n}`}}function XF(o,n={}){let{name:T,config:t}=So(o,n);return new wF(T,t)}class EF extends h{static[J]="PgJsonBuilder";constructor(o){super(o,"json","PgJson")}build(o){return new mS(o,this.config)}}class mS extends V{static[J]="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 YF(o){return new EF(o??"")}class GF extends h{static[J]="PgJsonbBuilder";constructor(o){super(o,"json","PgJsonb")}build(o){return new QS(o,this.config)}}class QS extends V{static[J]="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 zF(o){return new GF(o??"")}class HF extends h{static[J]="PgLineBuilder";constructor(o){super(o,"array","PgLine")}build(o){return new mF(o,this.config)}}class mF extends V{static[J]="PgLine";getSQLType(){return"line"}mapFromDriverValue(o){let[n,T,t]=o.slice(1,-1).split(",");return[Number.parseFloat(n),Number.parseFloat(T),Number.parseFloat(t)]}mapToDriverValue(o){return`{${o[0]},${o[1]},${o[2]}}`}}class QF extends h{static[J]="PgLineABCBuilder";constructor(o){super(o,"json","PgLineABC")}build(o){return new DF(o,this.config)}}class DF extends V{static[J]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(o){let[n,T,t]=o.slice(1,-1).split(",");return{a:Number.parseFloat(n),b:Number.parseFloat(T),c:Number.parseFloat(t)}}mapToDriverValue(o){return`{${o.a},${o.b},${o.c}}`}}function UF(o,n){let{name:T,config:t}=So(o,n);if(!t?.mode||t.mode==="tuple")return new HF(T);return new QF(T)}class VF extends h{static[J]="PgMacaddrBuilder";constructor(o){super(o,"string","PgMacaddr")}build(o){return new BF(o,this.config)}}class BF extends V{static[J]="PgMacaddr";getSQLType(){return"macaddr"}}function CF(o){return new VF(o??"")}class LF extends h{static[J]="PgMacaddr8Builder";constructor(o){super(o,"string","PgMacaddr8")}build(o){return new IF(o,this.config)}}class IF extends V{static[J]="PgMacaddr8";getSQLType(){return"macaddr8"}}function rF(o){return new LF(o??"")}class jF extends h{static[J]="PgNumericBuilder";constructor(o,n,T){super(o,"string","PgNumeric");this.config.precision=n,this.config.scale=T}build(o){return new DS(o,this.config)}}class DS extends V{static[J]="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 NF(o,n){let{name:T,config:t}=So(o,n);return new jF(T,t?.precision,t?.scale)}class hF extends h{static[J]="PgPointTupleBuilder";constructor(o){super(o,"array","PgPointTuple")}build(o){return new bF(o,this.config)}}class bF extends V{static[J]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(o){if(typeof o==="string"){let[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 cF extends h{static[J]="PgPointObjectBuilder";constructor(o){super(o,"json","PgPointObject")}build(o){return new xF(o,this.config)}}class xF extends V{static[J]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(o){if(typeof o==="string"){let[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 iF(o,n){let{name:T,config:t}=So(o,n);if(!t?.mode||t.mode==="tuple")return new hF(T);return new cF(T)}function eJ(o){let 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 vF(o,n){let T=new ArrayBuffer(8),t=new DataView(T);for(let S=0;S<8;S++)t.setUint8(S,o[n+S]);return t.getFloat64(0,!0)}function ny(o){let n=eJ(o),T=0,t=n[T];T+=1;let S=new DataView(n.buffer),f=S.getUint32(T,t===1);T+=4;let y;if(f&536870912)y=S.getUint32(T,t===1),T+=4;if((f&65535)===1){let A=vF(n,T);T+=8;let M=vF(n,T);return T+=8,[A,M]}throw new Error("Unsupported geometry type")}class pF extends h{static[J]="PgGeometryBuilder";constructor(o){super(o,"array","PgGeometry")}build(o){return new qF(o,this.config)}}class qF extends V{static[J]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(o){return ny(o)}mapToDriverValue(o){return`point(${o[0]} ${o[1]})`}}class ZF extends h{static[J]="PgGeometryObjectBuilder";constructor(o){super(o,"json","PgGeometryObject")}build(o){return new PF(o,this.config)}}class PF extends V{static[J]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(o){let n=ny(o);return{x:n[0],y:n[1]}}mapToDriverValue(o){return`point(${o.x} ${o.y})`}}function gF(o,n){let{name:T,config:t}=So(o,n);if(!t?.mode||t.mode==="tuple")return new pF(T);return new ZF(T)}class lF extends h{static[J]="PgRealBuilder";constructor(o,n){super(o,"number","PgReal");this.config.length=n}build(o){return new eF(o,this.config)}}class eF extends V{static[J]="PgReal";constructor(o,n){super(o,n)}getSQLType(){return"real"}mapFromDriverValue=(o)=>{if(typeof o==="string")return Number.parseFloat(o);return o}}function dF(o){return new lF(o??"")}class uF extends h{static[J]="PgSerialBuilder";constructor(o){super(o,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new aF(o,this.config)}}class aF extends V{static[J]="PgSerial";getSQLType(){return"serial"}}function sF(o){return new uF(o??"")}class o$ extends nT{static[J]="PgSmallIntBuilder";constructor(o){super(o,"number","PgSmallInt")}build(o){return new n$(o,this.config)}}class n$ extends V{static[J]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(o)=>{if(typeof o==="string")return Number(o);return o}}function T$(o){return new o$(o??"")}class t$ extends h{static[J]="PgSmallSerialBuilder";constructor(o){super(o,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new S$(o,this.config)}}class S$ extends V{static[J]="PgSmallSerial";getSQLType(){return"smallserial"}}function f$(o){return new t$(o??"")}class y$ extends h{static[J]="PgTextBuilder";constructor(o,n){super(o,"string","PgText");this.config.enumValues=n.enum}build(o){return new A$(o,this.config)}}class A$ extends V{static[J]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function M$(o,n={}){let{name:T,config:t}=So(o,n);return new y$(T,t)}class F$ 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[J]="PgTimeBuilder";build(o){return new US(o,this.config)}}class US extends V{static[J]="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 $$(o,n={}){let{name:T,config:t}=So(o,n);return new F$(T,t.withTimezone??!1,t.precision)}class k$ extends Pn{static[J]="PgTimestampBuilder";constructor(o,n,T){super(o,"date","PgTimestamp");this.config.withTimezone=n,this.config.precision=T}build(o){return new VS(o,this.config)}}class VS extends V{static[J]="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 J$ extends Pn{static[J]="PgTimestampStringBuilder";constructor(o,n,T){super(o,"string","PgTimestampString");this.config.withTimezone=n,this.config.precision=T}build(o){return new BS(o,this.config)}}class BS extends V{static[J]="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 Qn(o,n={}){let{name:T,config:t}=So(o,n);if(t?.mode==="string")return new J$(T,t.withTimezone??!1,t.precision);return new k$(T,t?.withTimezone??!1,t?.precision)}class R$ extends h{static[J]="PgUUIDBuilder";constructor(o){super(o,"string","PgUUID")}defaultRandom(){return this.default(R`gen_random_uuid()`)}build(o){return new CS(o,this.config)}}class CS extends V{static[J]="PgUUID";getSQLType(){return"uuid"}}function kn(o){return new R$(o??"")}class W$ extends h{static[J]="PgVarcharBuilder";constructor(o,n){super(o,"string","PgVarchar");this.config.length=n.length,this.config.enumValues=n.enum}build(o){return new O$(o,this.config)}}class O$ extends V{static[J]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function xo(o,n={}){let{name:T,config:t}=So(o,n);return new W$(T,t)}class _$ extends h{static[J]="PgBinaryVectorBuilder";constructor(o,n){super(o,"string","PgBinaryVector");this.config.dimensions=n.dimensions}build(o){return new w$(o,this.config)}}class w$ extends V{static[J]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function K$(o,n){let{name:T,config:t}=So(o,n);return new _$(T,t)}class X$ extends h{static[J]="PgHalfVectorBuilder";constructor(o,n){super(o,"array","PgHalfVector");this.config.dimensions=n.dimensions}build(o){return new E$(o,this.config)}}class E$ extends V{static[J]="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 Y$(o,n){let{name:T,config:t}=So(o,n);return new X$(T,t)}class G$ extends h{static[J]="PgSparseVectorBuilder";constructor(o,n){super(o,"string","PgSparseVector");this.config.dimensions=n.dimensions}build(o){return new z$(o,this.config)}}class z$ extends V{static[J]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function H$(o,n){let{name:T,config:t}=So(o,n);return new G$(T,t)}class m$ extends h{static[J]="PgVectorBuilder";constructor(o,n){super(o,"array","PgVector");this.config.dimensions=n.dimensions}build(o){return new Q$(o,this.config)}}class Q$ extends V{static[J]="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 D$(o,n){let{name:T,config:t}=So(o,n);return new m$(T,t)}function U$(){return{bigint:pM,bigserial:lM,boolean:Gt,char:sM,cidr:TF,customType:fF,date:MF,doublePrecision:kF,inet:WF,integer:HS,interval:XF,json:YF,jsonb:zF,line:UF,macaddr:CF,macaddr8:rF,numeric:NF,point:iF,geometry:gF,real:dF,serial:sF,smallint:T$,smallserial:f$,text:M$,time:$$,timestamp:Qn,uuid:kn,varchar:xo,bit:K$,halfvec:Y$,sparsevec:H$,vector:D$}}var Ty=Symbol.for("drizzle:PgInlineForeignKeys"),V$=Symbol.for("drizzle:EnableRLS");class io extends L{static[J]="PgTable";static Symbol=Object.assign({},L.Symbol,{InlineForeignKeys:Ty,EnableRLS:V$});[Ty]=[];[V$]=!1;[L.Symbol.ExtraConfigBuilder]=void 0}function dJ(o,n,T,t,S=o){let f=new io(o,t,S),y=typeof n==="function"?n(U$()):n,A=Object.fromEntries(Object.entries(y).map(([$,W])=>{let O=W;O.setName($);let G=O.build(f);return f[Ty].push(...O.buildForeignKeys(G,f)),[$,G]})),M=Object.fromEntries(Object.entries(y).map(([$,W])=>{let O=W;O.setName($);let G=O.buildExtraConfigColumn(f);return[$,G]})),F=Object.assign(f,A);if(F[L.Symbol.Columns]=A,F[L.Symbol.ExtraConfigColumns]=M,T)F[io.Symbol.ExtraConfigBuilder]=T;return Object.assign(F,{enableRLS:()=>{return F[io.Symbol.EnableRLS]=!0,F}})}var TT=(o,n,T)=>{return dJ(o,n,T,void 0)};function B$(...o){if(o[0].columns)return new zt(o[0].columns,o[0].name);return new zt(o)}class zt{static[J]="PgPrimaryKeyBuilder";columns;name;constructor(o,n){this.columns=o,this.name=n}build(o){return new C$(o,this.columns,this.name)}}class C${constructor(o,n,T){this.table=o,this.columns=n,this.name=T}static[J]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[io.Symbol.Name]}_${this.columns.map((o)=>o.name).join("_")}_pk`}}class ty{constructor(o,n,T){this.sourceTable=o,this.referencedTable=n,this.relationName=T,this.referencedTableName=n[L.Symbol.Name]}static[J]="Relation";referencedTableName;fieldName}class L${constructor(o,n){this.table=o,this.config=n}static[J]="Relations"}class tT extends ty{constructor(o,n,T,t){super(o,n,T?.relationName);this.config=T,this.isNullable=t}static[J]="One";withFieldName(o){let n=new tT(this.sourceTable,this.referencedTable,this.config,this.isNullable);return n.fieldName=o,n}}class Ht extends ty{constructor(o,n,T){super(o,n,T?.relationName);this.config=T}static[J]="Many";withFieldName(o){let n=new Ht(this.sourceTable,this.referencedTable,this.config);return n.fieldName=o,n}}function I$(){return{and:Et,between:QM,eq:IT,exists:HM,gt:_M,gte:wM,ilike:BM,inArray:EM,isNull:GM,isNotNull:zM,like:UM,lt:KM,lte:XM,ne:RM,not:OM,notBetween:DM,notExists:mM,notLike:VM,notIlike:CM,notInArray:YM,or:WM,sql:R}}function r$(){return{sql:R,asc:LM,desc:IM}}function j$(o,n){if(Object.keys(o).length===1&&"default"in o&&!X(o.default,L))o=o.default;let T={},t={},S={};for(let[f,y]of Object.entries(o))if(X(y,L)){let A=kT(y),M=t[A];T[A]=f,S[f]={tsName:f,dbName:y[L.Symbol.Name],schema:y[L.Symbol.Schema],columns:y[L.Symbol.Columns],relations:M?.relations??{},primaryKey:M?.primaryKey??[]};for(let $ of Object.values(y[L.Symbol.Columns]))if($.primary)S[f].primaryKey.push($);let F=y[L.Symbol.ExtraConfigBuilder]?.(y[L.Symbol.ExtraConfigColumns]);if(F){for(let $ of Object.values(F))if(X($,zt))S[f].primaryKey.push(...$.columns)}}else if(X(y,L$)){let A=kT(y.table),M=T[A],F=y.config(n(y.table)),$;for(let[W,O]of Object.entries(F))if(M){let G=S[M];if(G.relations[W]=O,$)G.primaryKey.push(...$)}else{if(!(A in t))t[A]={relations:{},primaryKey:$};t[A].relations[W]=O}}return{tables:S,tableNamesMap:T}}function uJ(o){return function n(T,t){return new tT(o,T,t,t?.fields.reduce((S,f)=>S&&f.notNull,!0)??!1)}}function aJ(o){return function n(T,t){return new Ht(o,T,t)}}function N$(o,n,T){if(X(T,tT)&&T.config)return{fields:T.config.fields,references:T.config.references};let t=n[kT(T.referencedTable)];if(!t)throw new Error(`Table "${T.referencedTable[L.Symbol.Name]}" not found in schema`);let S=o[t];if(!S)throw new Error(`Table "${t}" not found in schema`);let f=T.sourceTable,y=n[kT(f)];if(!y)throw new Error(`Table "${f[L.Symbol.Name]}" not found in schema`);let A=[];for(let M of Object.values(S.relations))if(T.relationName&&T!==M&&M.relationName===T.relationName||!T.relationName&&M.referencedTable===T.sourceTable)A.push(M);if(A.length>1)throw T.relationName?new Error(`There are multiple relations with name "${T.relationName}" in table "${t}"`):new Error(`There are multiple relations between "${t}" and "${T.sourceTable[L.Symbol.Name]}". Please specify relation name`);if(A[0]&&X(A[0],tT)&&A[0].config)return{fields:A[0].config.references,references:A[0].config.fields};throw new Error(`There is not enough information to infer relation "${y}.${T.fieldName}"`)}function h$(o){return{one:uJ(o),many:aJ(o)}}function LS(o,n,T,t,S=(f)=>f){let f={};for(let[y,A]of t.entries())if(A.isJson){let M=n.relations[A.tsKey],F=T[y],$=typeof F==="string"?JSON.parse(F):F;f[A.tsKey]=X(M,tT)?$&&LS(o,o[A.relationTableTsKey],$,A.selection,S):$.map((W)=>LS(o,o[A.relationTableTsKey],W,A.selection,S))}else{let M=S(T[y]),F=A.field,$;if(X(F,Ro))$=F;else if(X(F,r))$=F.decoder;else $=F.sql.decoder;f[A.tsKey]=M===null?null:$.mapFromDriverValue(M)}return f}import{readFileSync as u$}from"fs";import{resolve as Fy}from"path";var Mo;(function(o){o.assertEqual=(S)=>S;function n(S){}o.assertIs=n;function T(S){throw new Error}o.assertNever=T,o.arrayToEnum=(S)=>{let f={};for(let y of S)f[y]=y;return f},o.getValidEnumValues=(S)=>{let f=o.objectKeys(S).filter((A)=>typeof S[S[A]]!=="number"),y={};for(let A of f)y[A]=S[A];return o.objectValues(y)},o.objectValues=(S)=>{return o.objectKeys(S).map(function(f){return S[f]})},o.objectKeys=typeof Object.keys==="function"?(S)=>Object.keys(S):(S)=>{let f=[];for(let y in S)if(Object.prototype.hasOwnProperty.call(S,y))f.push(y);return f},o.find=(S,f)=>{for(let y of S)if(f(y))return y;return},o.isInteger=typeof Number.isInteger==="function"?(S)=>Number.isInteger(S):(S)=>typeof S==="number"&&isFinite(S)&&Math.floor(S)===S;function t(S,f=" | "){return S.map((y)=>typeof y==="string"?`'${y}'`:y).join(f)}o.joinValues=t,o.jsonStringifyReplacer=(S,f)=>{if(typeof f==="bigint")return f.toString();return f}})(Mo||(Mo={}));var fy;(function(o){o.mergeShapes=(n,T)=>{return{...n,...T}}})(fy||(fy={}));var j=Mo.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 j.undefined;case"string":return j.string;case"number":return isNaN(o)?j.nan:j.number;case"boolean":return j.boolean;case"function":return j.function;case"bigint":return j.bigint;case"symbol":return j.symbol;case"object":if(Array.isArray(o))return j.array;if(o===null)return j.null;if(o.then&&typeof o.then==="function"&&o.catch&&typeof o.catch==="function")return j.promise;if(typeof Map!=="undefined"&&o instanceof Map)return j.map;if(typeof Set!=="undefined"&&o instanceof Set)return j.set;if(typeof Date!=="undefined"&&o instanceof Date)return j.date;return j.object;default:return j.unknown}},Q=Mo.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"]),sJ=(o)=>{return JSON.stringify(o,null,2).replace(/"([^"]+)":/g,"$1:")};class Jn extends Error{constructor(o){super();this.issues=[],this.addIssue=(T)=>{this.issues=[...this.issues,T]},this.addIssues=(T=[])=>{this.issues=[...this.issues,...T]};let 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){let n=o||function(S){return S.message},T={_errors:[]},t=(S)=>{for(let f of S.issues)if(f.code==="invalid_union")f.unionErrors.map(t);else if(f.code==="invalid_return_type")t(f.returnTypeError);else if(f.code==="invalid_arguments")t(f.argumentsError);else if(f.path.length===0)T._errors.push(n(f));else{let y=T,A=0;while(A<f.path.length){let M=f.path[A];if(A!==f.path.length-1)y[M]=y[M]||{_errors:[]};else y[M]=y[M]||{_errors:[]},y[M]._errors.push(n(f));y=y[M],A++}}};return t(this),T}static assert(o){if(!(o instanceof Jn))throw new Error(`Not a ZodError: ${o}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Mo.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(o=(n)=>n.message){let n={},T=[];for(let t of this.issues)if(t.path.length>0)n[t.path[0]]=n[t.path[0]]||[],n[t.path[0]].push(o(t));else T.push(o(t));return{formErrors:T,fieldErrors:n}}get formErrors(){return this.flatten()}}Jn.create=(o)=>{return new Jn(o)};var hT=(o,n)=>{let T;switch(o.code){case Q.invalid_type:if(o.received===j.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,Mo.jsonStringifyReplacer)}`;break;case Q.unrecognized_keys:T=`Unrecognized key(s) in object: ${Mo.joinValues(o.keys,", ")}`;break;case Q.invalid_union:T="Invalid input";break;case Q.invalid_union_discriminator:T=`Invalid discriminator value. Expected ${Mo.joinValues(o.options)}`;break;case Q.invalid_enum_value:T=`Invalid enum value. Expected ${Mo.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 Mo.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,Mo.assertNever(o)}return{message:T}},x$=hT;function oR(o){x$=o}function IS(){return x$}var rS=(o)=>{let{data:n,path:T,errorMaps:t,issueData:S}=o,f=[...T,...S.path||[]],y={...S,path:f};if(S.message!==void 0)return{...S,path:f,message:S.message};let A="",M=t.filter((F)=>!!F).slice().reverse();for(let F of M)A=F(y,{data:n,defaultError:A}).message;return{...S,path:f,message:A}},nR=[];function I(o,n){let T=IS(),t=rS({issueData:n,data:o.data,path:o.path,errorMaps:[o.common.contextualErrorMap,o.schemaErrorMap,T,T===hT?void 0:hT].filter((S)=>!!S)});o.common.issues.push(t)}class eo{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(o,n){let T=[];for(let t of n){if(t.status==="aborted")return u;if(t.status==="dirty")o.dirty();T.push(t.value)}return{status:o.value,value:T}}static async mergeObjectAsync(o,n){let T=[];for(let t of n){let S=await t.key,f=await t.value;T.push({key:S,value:f})}return eo.mergeObjectSync(o,T)}static mergeObjectSync(o,n){let T={};for(let t of n){let{key:S,value:f}=t;if(S.status==="aborted")return u;if(f.status==="aborted")return u;if(S.status==="dirty")o.dirty();if(f.status==="dirty")o.dirty();if(S.value!=="__proto__"&&(typeof f.value!=="undefined"||t.alwaysSet))T[S.value]=f.value}return{status:o.value,value:T}}}var u=Object.freeze({status:"aborted"}),jT=(o)=>({status:"dirty",value:o}),nn=(o)=>({status:"valid",value:o}),yy=(o)=>o.status==="aborted",Ay=(o)=>o.status==="dirty",Dt=(o)=>o.status==="valid",Ut=(o)=>typeof Promise!=="undefined"&&o instanceof Promise;function jS(o,n,T,t){if(T==="a"&&!t)throw new TypeError("Private accessor was defined without a getter");if(typeof n==="function"?o!==n||!t:!n.has(o))throw new TypeError("Cannot read private member from an object whose class did not declare it");return T==="m"?t:T==="a"?t.call(o):t?t.value:n.get(o)}function i$(o,n,T,t,S){if(t==="m")throw new TypeError("Private method is not writable");if(t==="a"&&!S)throw new TypeError("Private accessor was defined without a setter");if(typeof n==="function"?o!==n||!S:!n.has(o))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t==="a"?S.call(o,T):S?S.value=T:n.set(o,T),T}var p;(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})(p||(p={}));var mt,Qt;class Bn{constructor(o,n,T,t){this._cachedPath=[],this.parent=o,this.data=n,this._path=T,this._key=t}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 b$=(o,n)=>{if(Dt(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;let T=new Jn(o.common.issues);return this._error=T,this._error}}}};function oo(o){if(!o)return{};let{errorMap:n,invalid_type_error:T,required_error:t,description:S}=o;if(n&&(T||t))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(n)return{errorMap:n,description:S};return{errorMap:(y,A)=>{var M,F;let{message:$}=o;if(y.code==="invalid_enum_value")return{message:$!==null&&$!==void 0?$:A.defaultError};if(typeof A.data==="undefined")return{message:(M=$!==null&&$!==void 0?$:t)!==null&&M!==void 0?M:A.defaultError};if(y.code!=="invalid_type")return{message:A.defaultError};return{message:(F=$!==null&&$!==void 0?$:T)!==null&&F!==void 0?F:A.defaultError}},description:S}}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 eo,ctx:{common:o.parent.common,data:o.data,parsedType:ST(o.data),schemaErrorMap:this._def.errorMap,path:o.path,parent:o.parent}}}_parseSync(o){let n=this._parse(o);if(Ut(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(o){let n=this._parse(o);return Promise.resolve(n)}parse(o,n){let T=this.safeParse(o,n);if(T.success)return T.data;throw T.error}safeParse(o,n){var T;let t={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)},S=this._parseSync({data:o,path:t.path,parent:t});return b$(t,S)}async parseAsync(o,n){let T=await this.safeParseAsync(o,n);if(T.success)return T.data;throw T.error}async safeParseAsync(o,n){let 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)},t=this._parse({data:o,path:T.path,parent:T}),S=await(Ut(t)?t:Promise.resolve(t));return b$(T,S)}refine(o,n){let T=(t)=>{if(typeof n==="string"||typeof n==="undefined")return{message:n};else if(typeof n==="function")return n(t);else return n};return this._refinement((t,S)=>{let f=o(t),y=()=>S.addIssue({code:Q.custom,...T(t)});if(typeof Promise!=="undefined"&&f instanceof Promise)return f.then((A)=>{if(!A)return y(),!1;else return!0});if(!f)return y(),!1;else return!0})}refinement(o,n){return this._refinement((T,t)=>{if(!o(T))return t.addIssue(typeof n==="function"?n(T,t):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 ln.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Un.create(this,this._def)}promise(){return OT.create(this,this._def)}or(o){return iT.create([this,o],this._def)}and(o){return vT.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){let n=typeof o==="function"?o:()=>o;return new PT({...oo(this._def),innerType:this,defaultValue:n,typeName:e.ZodDefault})}brand(){return new hS({typeName:e.ZodBranded,type:this,...oo(this._def)})}catch(o){let n=typeof o==="function"?o:()=>o;return new gT({...oo(this._def),innerType:this,catchValue:n,typeName:e.ZodCatch})}describe(o){return new this.constructor({...this._def,description:o})}pipe(o){return rt.create(this,o)}readonly(){return lT.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var TR=/^c[^\s-]{8,}$/i,tR=/^[0-9a-z]+$/,SR=/^[0-9A-HJKMNP-TV-Z]{26}$/,fR=/^[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,yR=/^[a-z0-9_-]{21}$/i,AR=/^[-+]?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)?)??$/,MR=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,FR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Sy,$R=/^(?:(?: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])$/,kR=/^(([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}=))?$/,v$="((\\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])))",RR=new RegExp(`^${v$}$`);function p$(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 WR(o){return new RegExp(`^${p$(o)}$`)}function q$(o){let n=`${v$}T${p$(o)}`,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 OR(o,n){if((n==="v4"||!n)&&$R.test(o))return!0;if((n==="v6"||!n)&&kR.test(o))return!0;return!1}class Dn extends no{_parse(o){if(this._def.coerce)o.data=String(o.data);if(this._getType(o)!==j.string){let S=this._getOrReturnCtx(o);return I(S,{code:Q.invalid_type,expected:j.string,received:S.parsedType}),u}let T=new eo,t=void 0;for(let S of this._def.checks)if(S.kind==="min"){if(o.data.length<S.value)t=this._getOrReturnCtx(o,t),I(t,{code:Q.too_small,minimum:S.value,type:"string",inclusive:!0,exact:!1,message:S.message}),T.dirty()}else if(S.kind==="max"){if(o.data.length>S.value)t=this._getOrReturnCtx(o,t),I(t,{code:Q.too_big,maximum:S.value,type:"string",inclusive:!0,exact:!1,message:S.message}),T.dirty()}else if(S.kind==="length"){let f=o.data.length>S.value,y=o.data.length<S.value;if(f||y){if(t=this._getOrReturnCtx(o,t),f)I(t,{code:Q.too_big,maximum:S.value,type:"string",inclusive:!0,exact:!0,message:S.message});else if(y)I(t,{code:Q.too_small,minimum:S.value,type:"string",inclusive:!0,exact:!0,message:S.message});T.dirty()}}else if(S.kind==="email"){if(!MR.test(o.data))t=this._getOrReturnCtx(o,t),I(t,{validation:"email",code:Q.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="emoji"){if(!Sy)Sy=new RegExp(FR,"u");if(!Sy.test(o.data))t=this._getOrReturnCtx(o,t),I(t,{validation:"emoji",code:Q.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="uuid"){if(!fR.test(o.data))t=this._getOrReturnCtx(o,t),I(t,{validation:"uuid",code:Q.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="nanoid"){if(!yR.test(o.data))t=this._getOrReturnCtx(o,t),I(t,{validation:"nanoid",code:Q.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="cuid"){if(!TR.test(o.data))t=this._getOrReturnCtx(o,t),I(t,{validation:"cuid",code:Q.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="cuid2"){if(!tR.test(o.data))t=this._getOrReturnCtx(o,t),I(t,{validation:"cuid2",code:Q.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="ulid"){if(!SR.test(o.data))t=this._getOrReturnCtx(o,t),I(t,{validation:"ulid",code:Q.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="url")try{new URL(o.data)}catch(f){t=this._getOrReturnCtx(o,t),I(t,{validation:"url",code:Q.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="regex"){if(S.regex.lastIndex=0,!S.regex.test(o.data))t=this._getOrReturnCtx(o,t),I(t,{validation:"regex",code:Q.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="trim")o.data=o.data.trim();else if(S.kind==="includes"){if(!o.data.includes(S.value,S.position))t=this._getOrReturnCtx(o,t),I(t,{code:Q.invalid_string,validation:{includes:S.value,position:S.position},message:S.message}),T.dirty()}else if(S.kind==="toLowerCase")o.data=o.data.toLowerCase();else if(S.kind==="toUpperCase")o.data=o.data.toUpperCase();else if(S.kind==="startsWith"){if(!o.data.startsWith(S.value))t=this._getOrReturnCtx(o,t),I(t,{code:Q.invalid_string,validation:{startsWith:S.value},message:S.message}),T.dirty()}else if(S.kind==="endsWith"){if(!o.data.endsWith(S.value))t=this._getOrReturnCtx(o,t),I(t,{code:Q.invalid_string,validation:{endsWith:S.value},message:S.message}),T.dirty()}else if(S.kind==="datetime"){if(!q$(S).test(o.data))t=this._getOrReturnCtx(o,t),I(t,{code:Q.invalid_string,validation:"datetime",message:S.message}),T.dirty()}else if(S.kind==="date"){if(!RR.test(o.data))t=this._getOrReturnCtx(o,t),I(t,{code:Q.invalid_string,validation:"date",message:S.message}),T.dirty()}else if(S.kind==="time"){if(!WR(S).test(o.data))t=this._getOrReturnCtx(o,t),I(t,{code:Q.invalid_string,validation:"time",message:S.message}),T.dirty()}else if(S.kind==="duration"){if(!AR.test(o.data))t=this._getOrReturnCtx(o,t),I(t,{validation:"duration",code:Q.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="ip"){if(!OR(o.data,S.version))t=this._getOrReturnCtx(o,t),I(t,{validation:"ip",code:Q.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="base64"){if(!JR.test(o.data))t=this._getOrReturnCtx(o,t),I(t,{validation:"base64",code:Q.invalid_string,message:S.message}),T.dirty()}else Mo.assertNever(S);return{status:T.value,value:o.data}}_regex(o,n,T){return this.refinement((t)=>o.test(t),{validation:n,code:Q.invalid_string,...p.errToObj(T)})}_addCheck(o){return new Dn({...this._def,checks:[...this._def.checks,o]})}email(o){return this._addCheck({kind:"email",...p.errToObj(o)})}url(o){return this._addCheck({kind:"url",...p.errToObj(o)})}emoji(o){return this._addCheck({kind:"emoji",...p.errToObj(o)})}uuid(o){return this._addCheck({kind:"uuid",...p.errToObj(o)})}nanoid(o){return this._addCheck({kind:"nanoid",...p.errToObj(o)})}cuid(o){return this._addCheck({kind:"cuid",...p.errToObj(o)})}cuid2(o){return this._addCheck({kind:"cuid2",...p.errToObj(o)})}ulid(o){return this._addCheck({kind:"ulid",...p.errToObj(o)})}base64(o){return this._addCheck({kind:"base64",...p.errToObj(o)})}ip(o){return this._addCheck({kind:"ip",...p.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,...p.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,...p.errToObj(o===null||o===void 0?void 0:o.message)})}duration(o){return this._addCheck({kind:"duration",...p.errToObj(o)})}regex(o,n){return this._addCheck({kind:"regex",regex:o,...p.errToObj(n)})}includes(o,n){return this._addCheck({kind:"includes",value:o,position:n===null||n===void 0?void 0:n.position,...p.errToObj(n===null||n===void 0?void 0:n.message)})}startsWith(o,n){return this._addCheck({kind:"startsWith",value:o,...p.errToObj(n)})}endsWith(o,n){return this._addCheck({kind:"endsWith",value:o,...p.errToObj(n)})}min(o,n){return this._addCheck({kind:"min",value:o,...p.errToObj(n)})}max(o,n){return this._addCheck({kind:"max",value:o,...p.errToObj(n)})}length(o,n){return this._addCheck({kind:"length",value:o,...p.errToObj(n)})}nonempty(o){return this.min(1,p.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)})};function _R(o,n){let T=(o.toString().split(".")[1]||"").length,t=(n.toString().split(".")[1]||"").length,S=T>t?T:t,f=parseInt(o.toFixed(S).replace(".","")),y=parseInt(n.toFixed(S).replace(".",""));return f%y/Math.pow(10,S)}class yT 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)!==j.number){let S=this._getOrReturnCtx(o);return I(S,{code:Q.invalid_type,expected:j.number,received:S.parsedType}),u}let T=void 0,t=new eo;for(let S of this._def.checks)if(S.kind==="int"){if(!Mo.isInteger(o.data))T=this._getOrReturnCtx(o,T),I(T,{code:Q.invalid_type,expected:"integer",received:"float",message:S.message}),t.dirty()}else if(S.kind==="min"){if(S.inclusive?o.data<S.value:o.data<=S.value)T=this._getOrReturnCtx(o,T),I(T,{code:Q.too_small,minimum:S.value,type:"number",inclusive:S.inclusive,exact:!1,message:S.message}),t.dirty()}else if(S.kind==="max"){if(S.inclusive?o.data>S.value:o.data>=S.value)T=this._getOrReturnCtx(o,T),I(T,{code:Q.too_big,maximum:S.value,type:"number",inclusive:S.inclusive,exact:!1,message:S.message}),t.dirty()}else if(S.kind==="multipleOf"){if(_R(o.data,S.value)!==0)T=this._getOrReturnCtx(o,T),I(T,{code:Q.not_multiple_of,multipleOf:S.value,message:S.message}),t.dirty()}else if(S.kind==="finite"){if(!Number.isFinite(o.data))T=this._getOrReturnCtx(o,T),I(T,{code:Q.not_finite,message:S.message}),t.dirty()}else Mo.assertNever(S);return{status:t.value,value:o.data}}gte(o,n){return this.setLimit("min",o,!0,p.toString(n))}gt(o,n){return this.setLimit("min",o,!1,p.toString(n))}lte(o,n){return this.setLimit("max",o,!0,p.toString(n))}lt(o,n){return this.setLimit("max",o,!1,p.toString(n))}setLimit(o,n,T,t){return new yT({...this._def,checks:[...this._def.checks,{kind:o,value:n,inclusive:T,message:p.toString(t)}]})}_addCheck(o){return new yT({...this._def,checks:[...this._def.checks,o]})}int(o){return this._addCheck({kind:"int",message:p.toString(o)})}positive(o){return this._addCheck({kind:"min",value:0,inclusive:!1,message:p.toString(o)})}negative(o){return this._addCheck({kind:"max",value:0,inclusive:!1,message:p.toString(o)})}nonpositive(o){return this._addCheck({kind:"max",value:0,inclusive:!0,message:p.toString(o)})}nonnegative(o){return this._addCheck({kind:"min",value:0,inclusive:!0,message:p.toString(o)})}multipleOf(o,n){return this._addCheck({kind:"multipleOf",value:o,message:p.toString(n)})}finite(o){return this._addCheck({kind:"finite",message:p.toString(o)})}safe(o){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:p.toString(o)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:p.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"&&Mo.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)}}yT.create=(o)=>{return new yT({checks:[],typeName:e.ZodNumber,coerce:(o===null||o===void 0?void 0:o.coerce)||!1,...oo(o)})};class AT 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)!==j.bigint){let S=this._getOrReturnCtx(o);return I(S,{code:Q.invalid_type,expected:j.bigint,received:S.parsedType}),u}let T=void 0,t=new eo;for(let S of this._def.checks)if(S.kind==="min"){if(S.inclusive?o.data<S.value:o.data<=S.value)T=this._getOrReturnCtx(o,T),I(T,{code:Q.too_small,type:"bigint",minimum:S.value,inclusive:S.inclusive,message:S.message}),t.dirty()}else if(S.kind==="max"){if(S.inclusive?o.data>S.value:o.data>=S.value)T=this._getOrReturnCtx(o,T),I(T,{code:Q.too_big,type:"bigint",maximum:S.value,inclusive:S.inclusive,message:S.message}),t.dirty()}else if(S.kind==="multipleOf"){if(o.data%S.value!==BigInt(0))T=this._getOrReturnCtx(o,T),I(T,{code:Q.not_multiple_of,multipleOf:S.value,message:S.message}),t.dirty()}else Mo.assertNever(S);return{status:t.value,value:o.data}}gte(o,n){return this.setLimit("min",o,!0,p.toString(n))}gt(o,n){return this.setLimit("min",o,!1,p.toString(n))}lte(o,n){return this.setLimit("max",o,!0,p.toString(n))}lt(o,n){return this.setLimit("max",o,!1,p.toString(n))}setLimit(o,n,T,t){return new AT({...this._def,checks:[...this._def.checks,{kind:o,value:n,inclusive:T,message:p.toString(t)}]})}_addCheck(o){return new AT({...this._def,checks:[...this._def.checks,o]})}positive(o){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:p.toString(o)})}negative(o){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:p.toString(o)})}nonpositive(o){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:p.toString(o)})}nonnegative(o){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:p.toString(o)})}multipleOf(o,n){return this._addCheck({kind:"multipleOf",value:o,message:p.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}}AT.create=(o)=>{var n;return new AT({checks:[],typeName:e.ZodBigInt,coerce:(n=o===null||o===void 0?void 0:o.coerce)!==null&&n!==void 0?n:!1,...oo(o)})};class bT extends no{_parse(o){if(this._def.coerce)o.data=Boolean(o.data);if(this._getType(o)!==j.boolean){let T=this._getOrReturnCtx(o);return I(T,{code:Q.invalid_type,expected:j.boolean,received:T.parsedType}),u}return nn(o.data)}}bT.create=(o)=>{return new bT({typeName:e.ZodBoolean,coerce:(o===null||o===void 0?void 0:o.coerce)||!1,...oo(o)})};class JT extends no{_parse(o){if(this._def.coerce)o.data=new Date(o.data);if(this._getType(o)!==j.date){let S=this._getOrReturnCtx(o);return I(S,{code:Q.invalid_type,expected:j.date,received:S.parsedType}),u}if(isNaN(o.data.getTime())){let S=this._getOrReturnCtx(o);return I(S,{code:Q.invalid_date}),u}let T=new eo,t=void 0;for(let S of this._def.checks)if(S.kind==="min"){if(o.data.getTime()<S.value)t=this._getOrReturnCtx(o,t),I(t,{code:Q.too_small,message:S.message,inclusive:!0,exact:!1,minimum:S.value,type:"date"}),T.dirty()}else if(S.kind==="max"){if(o.data.getTime()>S.value)t=this._getOrReturnCtx(o,t),I(t,{code:Q.too_big,message:S.message,inclusive:!0,exact:!1,maximum:S.value,type:"date"}),T.dirty()}else Mo.assertNever(S);return{status:T.value,value:new Date(o.data.getTime())}}_addCheck(o){return new JT({...this._def,checks:[...this._def.checks,o]})}min(o,n){return this._addCheck({kind:"min",value:o.getTime(),message:p.toString(n)})}max(o,n){return this._addCheck({kind:"max",value:o.getTime(),message:p.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}}JT.create=(o)=>{return new JT({checks:[],coerce:(o===null||o===void 0?void 0:o.coerce)||!1,typeName:e.ZodDate,...oo(o)})};class Vt extends no{_parse(o){if(this._getType(o)!==j.symbol){let T=this._getOrReturnCtx(o);return I(T,{code:Q.invalid_type,expected:j.symbol,received:T.parsedType}),u}return nn(o.data)}}Vt.create=(o)=>{return new Vt({typeName:e.ZodSymbol,...oo(o)})};class cT extends no{_parse(o){if(this._getType(o)!==j.undefined){let T=this._getOrReturnCtx(o);return I(T,{code:Q.invalid_type,expected:j.undefined,received:T.parsedType}),u}return nn(o.data)}}cT.create=(o)=>{return new cT({typeName:e.ZodUndefined,...oo(o)})};class xT extends no{_parse(o){if(this._getType(o)!==j.null){let T=this._getOrReturnCtx(o);return I(T,{code:Q.invalid_type,expected:j.null,received:T.parsedType}),u}return nn(o.data)}}xT.create=(o)=>{return new xT({typeName:e.ZodNull,...oo(o)})};class RT extends no{constructor(){super(...arguments);this._any=!0}_parse(o){return nn(o.data)}}RT.create=(o)=>{return new RT({typeName:e.ZodAny,...oo(o)})};class fT extends no{constructor(){super(...arguments);this._unknown=!0}_parse(o){return nn(o.data)}}fT.create=(o)=>{return new fT({typeName:e.ZodUnknown,...oo(o)})};class Nn extends no{_parse(o){let n=this._getOrReturnCtx(o);return I(n,{code:Q.invalid_type,expected:j.never,received:n.parsedType}),u}}Nn.create=(o)=>{return new Nn({typeName:e.ZodNever,...oo(o)})};class Bt extends no{_parse(o){if(this._getType(o)!==j.undefined){let T=this._getOrReturnCtx(o);return I(T,{code:Q.invalid_type,expected:j.void,received:T.parsedType}),u}return nn(o.data)}}Bt.create=(o)=>{return new Bt({typeName:e.ZodVoid,...oo(o)})};class Un extends no{_parse(o){let{ctx:n,status:T}=this._processInputParams(o),t=this._def;if(n.parsedType!==j.array)return I(n,{code:Q.invalid_type,expected:j.array,received:n.parsedType}),u;if(t.exactLength!==null){let f=n.data.length>t.exactLength.value,y=n.data.length<t.exactLength.value;if(f||y)I(n,{code:f?Q.too_big:Q.too_small,minimum:y?t.exactLength.value:void 0,maximum:f?t.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:t.exactLength.message}),T.dirty()}if(t.minLength!==null){if(n.data.length<t.minLength.value)I(n,{code:Q.too_small,minimum:t.minLength.value,type:"array",inclusive:!0,exact:!1,message:t.minLength.message}),T.dirty()}if(t.maxLength!==null){if(n.data.length>t.maxLength.value)I(n,{code:Q.too_big,maximum:t.maxLength.value,type:"array",inclusive:!0,exact:!1,message:t.maxLength.message}),T.dirty()}if(n.common.async)return Promise.all([...n.data].map((f,y)=>{return t.type._parseAsync(new Bn(n,f,n.path,y))})).then((f)=>{return eo.mergeArray(T,f)});let S=[...n.data].map((f,y)=>{return t.type._parseSync(new Bn(n,f,n.path,y))});return eo.mergeArray(T,S)}get element(){return this._def.type}min(o,n){return new Un({...this._def,minLength:{value:o,message:p.toString(n)}})}max(o,n){return new Un({...this._def,maxLength:{value:o,message:p.toString(n)}})}length(o,n){return new Un({...this._def,exactLength:{value:o,message:p.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)})};function rT(o){if(o instanceof Do){let n={};for(let T in o.shape){let t=o.shape[T];n[T]=Vn.create(rT(t))}return new Do({...o._def,shape:()=>n})}else if(o instanceof Un)return new Un({...o._def,type:rT(o.element)});else if(o instanceof Vn)return Vn.create(rT(o.unwrap()));else if(o instanceof ln)return ln.create(rT(o.unwrap()));else if(o instanceof hn)return hn.create(o.items.map((n)=>rT(n)));else return o}class Do extends no{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let o=this._def.shape(),n=Mo.objectKeys(o);return this._cached={shape:o,keys:n}}_parse(o){if(this._getType(o)!==j.object){let M=this._getOrReturnCtx(o);return I(M,{code:Q.invalid_type,expected:j.object,received:M.parsedType}),u}let{status:T,ctx:t}=this._processInputParams(o),{shape:S,keys:f}=this._getCached(),y=[];if(!(this._def.catchall instanceof Nn&&this._def.unknownKeys==="strip")){for(let M in t.data)if(!f.includes(M))y.push(M)}let A=[];for(let M of f){let F=S[M],$=t.data[M];A.push({key:{status:"valid",value:M},value:F._parse(new Bn(t,$,t.path,M)),alwaysSet:M in t.data})}if(this._def.catchall instanceof Nn){let M=this._def.unknownKeys;if(M==="passthrough")for(let F of y)A.push({key:{status:"valid",value:F},value:{status:"valid",value:t.data[F]}});else if(M==="strict"){if(y.length>0)I(t,{code:Q.unrecognized_keys,keys:y}),T.dirty()}else if(M==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let M=this._def.catchall;for(let F of y){let $=t.data[F];A.push({key:{status:"valid",value:F},value:M._parse(new Bn(t,$,t.path,F)),alwaysSet:F in t.data})}}if(t.common.async)return Promise.resolve().then(async()=>{let M=[];for(let F of A){let $=await F.key,W=await F.value;M.push({key:$,value:W,alwaysSet:F.alwaysSet})}return M}).then((M)=>{return eo.mergeObjectSync(T,M)});else return eo.mergeObjectSync(T,A)}get shape(){return this._def.shape()}strict(o){return p.errToObj,new Do({...this._def,unknownKeys:"strict",...o!==void 0?{errorMap:(n,T)=>{var t,S,f,y;let A=(f=(S=(t=this._def).errorMap)===null||S===void 0?void 0:S.call(t,n,T).message)!==null&&f!==void 0?f:T.defaultError;if(n.code==="unrecognized_keys")return{message:(y=p.errToObj(o).message)!==null&&y!==void 0?y:A};return{message:A}}}:{}})}strip(){return new Do({...this._def,unknownKeys:"strip"})}passthrough(){return new Do({...this._def,unknownKeys:"passthrough"})}extend(o){return new Do({...this._def,shape:()=>({...this._def.shape(),...o})})}merge(o){return new Do({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 Do({...this._def,catchall:o})}pick(o){let n={};return Mo.objectKeys(o).forEach((T)=>{if(o[T]&&this.shape[T])n[T]=this.shape[T]}),new Do({...this._def,shape:()=>n})}omit(o){let n={};return Mo.objectKeys(this.shape).forEach((T)=>{if(!o[T])n[T]=this.shape[T]}),new Do({...this._def,shape:()=>n})}deepPartial(){return rT(this)}partial(o){let n={};return Mo.objectKeys(this.shape).forEach((T)=>{let t=this.shape[T];if(o&&!o[T])n[T]=t;else n[T]=t.optional()}),new Do({...this._def,shape:()=>n})}required(o){let n={};return Mo.objectKeys(this.shape).forEach((T)=>{if(o&&!o[T])n[T]=this.shape[T];else{let S=this.shape[T];while(S instanceof Vn)S=S._def.innerType;n[T]=S}}),new Do({...this._def,shape:()=>n})}keyof(){return Z$(Mo.objectKeys(this.shape))}}Do.create=(o,n)=>{return new Do({shape:()=>o,unknownKeys:"strip",catchall:Nn.create(),typeName:e.ZodObject,...oo(n)})};Do.strictCreate=(o,n)=>{return new Do({shape:()=>o,unknownKeys:"strict",catchall:Nn.create(),typeName:e.ZodObject,...oo(n)})};Do.lazycreate=(o,n)=>{return new Do({shape:o,unknownKeys:"strip",catchall:Nn.create(),typeName:e.ZodObject,...oo(n)})};class iT extends no{_parse(o){let{ctx:n}=this._processInputParams(o),T=this._def.options;function t(S){for(let y of S)if(y.result.status==="valid")return y.result;for(let y of S)if(y.result.status==="dirty")return n.common.issues.push(...y.ctx.common.issues),y.result;let f=S.map((y)=>new Jn(y.ctx.common.issues));return I(n,{code:Q.invalid_union,unionErrors:f}),u}if(n.common.async)return Promise.all(T.map(async(S)=>{let f={...n,common:{...n.common,issues:[]},parent:null};return{result:await S._parseAsync({data:n.data,path:n.path,parent:f}),ctx:f}})).then(t);else{let S=void 0,f=[];for(let A of T){let M={...n,common:{...n.common,issues:[]},parent:null},F=A._parseSync({data:n.data,path:n.path,parent:M});if(F.status==="valid")return F;else if(F.status==="dirty"&&!S)S={result:F,ctx:M};if(M.common.issues.length)f.push(M.common.issues)}if(S)return n.common.issues.push(...S.ctx.common.issues),S.result;let y=f.map((A)=>new Jn(A));return I(n,{code:Q.invalid_union,unionErrors:y}),u}}get options(){return this._def.options}}iT.create=(o,n)=>{return new iT({options:o,typeName:e.ZodUnion,...oo(n)})};var gn=(o)=>{if(o instanceof pT)return gn(o.schema);else if(o instanceof Kn)return gn(o.innerType());else if(o instanceof qT)return[o.value];else if(o instanceof MT)return o.options;else if(o instanceof ZT)return Mo.objectValues(o.enum);else if(o instanceof PT)return gn(o._def.innerType);else if(o instanceof cT)return[void 0];else if(o instanceof xT)return[null];else if(o instanceof Vn)return[void 0,...gn(o.unwrap())];else if(o instanceof ln)return[null,...gn(o.unwrap())];else if(o instanceof hS)return gn(o.unwrap());else if(o instanceof lT)return gn(o.unwrap());else if(o instanceof gT)return gn(o._def.innerType);else return[]};class NS extends no{_parse(o){let{ctx:n}=this._processInputParams(o);if(n.parsedType!==j.object)return I(n,{code:Q.invalid_type,expected:j.object,received:n.parsedType}),u;let T=this.discriminator,t=n.data[T],S=this.optionsMap.get(t);if(!S)return I(n,{code:Q.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[T]}),u;if(n.common.async)return S._parseAsync({data:n.data,path:n.path,parent:n});else return S._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){let t=new Map;for(let S of n){let f=gn(S.shape[o]);if(!f.length)throw new Error(`A discriminator value for key \`${o}\` could not be extracted from all schema options`);for(let y of f){if(t.has(y))throw new Error(`Discriminator property ${String(o)} has duplicate value ${String(y)}`);t.set(y,S)}}return new NS({typeName:e.ZodDiscriminatedUnion,discriminator:o,options:n,optionsMap:t,...oo(T)})}}function My(o,n){let T=ST(o),t=ST(n);if(o===n)return{valid:!0,data:o};else if(T===j.object&&t===j.object){let S=Mo.objectKeys(n),f=Mo.objectKeys(o).filter((A)=>S.indexOf(A)!==-1),y={...o,...n};for(let A of f){let M=My(o[A],n[A]);if(!M.valid)return{valid:!1};y[A]=M.data}return{valid:!0,data:y}}else if(T===j.array&&t===j.array){if(o.length!==n.length)return{valid:!1};let S=[];for(let f=0;f<o.length;f++){let y=o[f],A=n[f],M=My(y,A);if(!M.valid)return{valid:!1};S.push(M.data)}return{valid:!0,data:S}}else if(T===j.date&&t===j.date&&+o===+n)return{valid:!0,data:o};else return{valid:!1}}class vT extends no{_parse(o){let{status:n,ctx:T}=this._processInputParams(o),t=(S,f)=>{if(yy(S)||yy(f))return u;let y=My(S.value,f.value);if(!y.valid)return I(T,{code:Q.invalid_intersection_types}),u;if(Ay(S)||Ay(f))n.dirty();return{status:n.value,value:y.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(([S,f])=>t(S,f));else return t(this._def.left._parseSync({data:T.data,path:T.path,parent:T}),this._def.right._parseSync({data:T.data,path:T.path,parent:T}))}}vT.create=(o,n,T)=>{return new vT({left:o,right:n,typeName:e.ZodIntersection,...oo(T)})};class hn extends no{_parse(o){let{status:n,ctx:T}=this._processInputParams(o);if(T.parsedType!==j.array)return I(T,{code:Q.invalid_type,expected:j.array,received:T.parsedType}),u;if(T.data.length<this._def.items.length)return I(T,{code:Q.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),u;if(!this._def.rest&&T.data.length>this._def.items.length)I(T,{code:Q.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty();let S=[...T.data].map((f,y)=>{let A=this._def.items[y]||this._def.rest;if(!A)return null;return A._parse(new Bn(T,f,T.path,y))}).filter((f)=>!!f);if(T.common.async)return Promise.all(S).then((f)=>{return eo.mergeArray(n,f)});else return eo.mergeArray(n,S)}get items(){return this._def.items}rest(o){return new hn({...this._def,rest:o})}}hn.create=(o,n)=>{if(!Array.isArray(o))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new hn({items:o,typeName:e.ZodTuple,rest:null,...oo(n)})};class Ct extends no{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(o){let{status:n,ctx:T}=this._processInputParams(o);if(T.parsedType!==j.object)return I(T,{code:Q.invalid_type,expected:j.object,received:T.parsedType}),u;let t=[],S=this._def.keyType,f=this._def.valueType;for(let y in T.data)t.push({key:S._parse(new Bn(T,y,T.path,y)),value:f._parse(new Bn(T,T.data[y],T.path,y)),alwaysSet:y in T.data});if(T.common.async)return eo.mergeObjectAsync(n,t);else return eo.mergeObjectSync(n,t)}get element(){return this._def.valueType}static create(o,n,T){if(n instanceof no)return new Ct({keyType:o,valueType:n,typeName:e.ZodRecord,...oo(T)});return new Ct({keyType:Dn.create(),valueType:o,typeName:e.ZodRecord,...oo(n)})}}class Lt extends no{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(o){let{status:n,ctx:T}=this._processInputParams(o);if(T.parsedType!==j.map)return I(T,{code:Q.invalid_type,expected:j.map,received:T.parsedType}),u;let t=this._def.keyType,S=this._def.valueType,f=[...T.data.entries()].map(([y,A],M)=>{return{key:t._parse(new Bn(T,y,T.path,[M,"key"])),value:S._parse(new Bn(T,A,T.path,[M,"value"]))}});if(T.common.async){let y=new Map;return Promise.resolve().then(async()=>{for(let A of f){let M=await A.key,F=await A.value;if(M.status==="aborted"||F.status==="aborted")return u;if(M.status==="dirty"||F.status==="dirty")n.dirty();y.set(M.value,F.value)}return{status:n.value,value:y}})}else{let y=new Map;for(let A of f){let{key:M,value:F}=A;if(M.status==="aborted"||F.status==="aborted")return u;if(M.status==="dirty"||F.status==="dirty")n.dirty();y.set(M.value,F.value)}return{status:n.value,value:y}}}}Lt.create=(o,n,T)=>{return new Lt({valueType:n,keyType:o,typeName:e.ZodMap,...oo(T)})};class WT extends no{_parse(o){let{status:n,ctx:T}=this._processInputParams(o);if(T.parsedType!==j.set)return I(T,{code:Q.invalid_type,expected:j.set,received:T.parsedType}),u;let t=this._def;if(t.minSize!==null){if(T.data.size<t.minSize.value)I(T,{code:Q.too_small,minimum:t.minSize.value,type:"set",inclusive:!0,exact:!1,message:t.minSize.message}),n.dirty()}if(t.maxSize!==null){if(T.data.size>t.maxSize.value)I(T,{code:Q.too_big,maximum:t.maxSize.value,type:"set",inclusive:!0,exact:!1,message:t.maxSize.message}),n.dirty()}let S=this._def.valueType;function f(A){let M=new Set;for(let F of A){if(F.status==="aborted")return u;if(F.status==="dirty")n.dirty();M.add(F.value)}return{status:n.value,value:M}}let y=[...T.data.values()].map((A,M)=>S._parse(new Bn(T,A,T.path,M)));if(T.common.async)return Promise.all(y).then((A)=>f(A));else return f(y)}min(o,n){return new WT({...this._def,minSize:{value:o,message:p.toString(n)}})}max(o,n){return new WT({...this._def,maxSize:{value:o,message:p.toString(n)}})}size(o,n){return this.min(o,n).max(o,n)}nonempty(o){return this.min(1,o)}}WT.create=(o,n)=>{return new WT({valueType:o,minSize:null,maxSize:null,typeName:e.ZodSet,...oo(n)})};class NT extends no{constructor(){super(...arguments);this.validate=this.implement}_parse(o){let{ctx:n}=this._processInputParams(o);if(n.parsedType!==j.function)return I(n,{code:Q.invalid_type,expected:j.function,received:n.parsedType}),u;function T(y,A){return rS({data:y,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,IS(),hT].filter((M)=>!!M),issueData:{code:Q.invalid_arguments,argumentsError:A}})}function t(y,A){return rS({data:y,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,IS(),hT].filter((M)=>!!M),issueData:{code:Q.invalid_return_type,returnTypeError:A}})}let S={errorMap:n.common.contextualErrorMap},f=n.data;if(this._def.returns instanceof OT){let y=this;return nn(async function(...A){let M=new Jn([]),F=await y._def.args.parseAsync(A,S).catch((O)=>{throw M.addIssue(T(A,O)),M}),$=await Reflect.apply(f,this,F);return await y._def.returns._def.type.parseAsync($,S).catch((O)=>{throw M.addIssue(t($,O)),M})})}else{let y=this;return nn(function(...A){let M=y._def.args.safeParse(A,S);if(!M.success)throw new Jn([T(A,M.error)]);let F=Reflect.apply(f,this,M.data),$=y._def.returns.safeParse(F,S);if(!$.success)throw new Jn([t(F,$.error)]);return $.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...o){return new NT({...this._def,args:hn.create(o).rest(fT.create())})}returns(o){return new NT({...this._def,returns:o})}implement(o){return this.parse(o)}strictImplement(o){return this.parse(o)}static create(o,n,T){return new NT({args:o?o:hn.create([]).rest(fT.create()),returns:n||fT.create(),typeName:e.ZodFunction,...oo(T)})}}class pT extends no{get schema(){return this._def.getter()}_parse(o){let{ctx:n}=this._processInputParams(o);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}pT.create=(o,n)=>{return new pT({getter:o,typeName:e.ZodLazy,...oo(n)})};class qT extends no{_parse(o){if(o.data!==this._def.value){let n=this._getOrReturnCtx(o);return I(n,{received:n.data,code:Q.invalid_literal,expected:this._def.value}),u}return{status:"valid",value:o.data}}get value(){return this._def.value}}qT.create=(o,n)=>{return new qT({value:o,typeName:e.ZodLiteral,...oo(n)})};function Z$(o,n){return new MT({values:o,typeName:e.ZodEnum,...oo(n)})}class MT extends no{constructor(){super(...arguments);mt.set(this,void 0)}_parse(o){if(typeof o.data!=="string"){let n=this._getOrReturnCtx(o),T=this._def.values;return I(n,{expected:Mo.joinValues(T),received:n.parsedType,code:Q.invalid_type}),u}if(!jS(this,mt,"f"))i$(this,mt,new Set(this._def.values),"f");if(!jS(this,mt,"f").has(o.data)){let n=this._getOrReturnCtx(o),T=this._def.values;return I(n,{received:n.data,code:Q.invalid_enum_value,options:T}),u}return nn(o.data)}get options(){return this._def.values}get enum(){let o={};for(let n of this._def.values)o[n]=n;return o}get Values(){let o={};for(let n of this._def.values)o[n]=n;return o}get Enum(){let o={};for(let n of this._def.values)o[n]=n;return o}extract(o,n=this._def){return MT.create(o,{...this._def,...n})}exclude(o,n=this._def){return MT.create(this.options.filter((T)=>!o.includes(T)),{...this._def,...n})}}mt=new WeakMap;MT.create=Z$;class ZT extends no{constructor(){super(...arguments);Qt.set(this,void 0)}_parse(o){let n=Mo.getValidEnumValues(this._def.values),T=this._getOrReturnCtx(o);if(T.parsedType!==j.string&&T.parsedType!==j.number){let t=Mo.objectValues(n);return I(T,{expected:Mo.joinValues(t),received:T.parsedType,code:Q.invalid_type}),u}if(!jS(this,Qt,"f"))i$(this,Qt,new Set(Mo.getValidEnumValues(this._def.values)),"f");if(!jS(this,Qt,"f").has(o.data)){let t=Mo.objectValues(n);return I(T,{received:T.data,code:Q.invalid_enum_value,options:t}),u}return nn(o.data)}get enum(){return this._def.values}}Qt=new WeakMap;ZT.create=(o,n)=>{return new ZT({values:o,typeName:e.ZodNativeEnum,...oo(n)})};class OT extends no{unwrap(){return this._def.type}_parse(o){let{ctx:n}=this._processInputParams(o);if(n.parsedType!==j.promise&&n.common.async===!1)return I(n,{code:Q.invalid_type,expected:j.promise,received:n.parsedType}),u;let T=n.parsedType===j.promise?n.data:Promise.resolve(n.data);return nn(T.then((t)=>{return this._def.type.parseAsync(t,{path:n.path,errorMap:n.common.contextualErrorMap})}))}}OT.create=(o,n)=>{return new OT({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){let{status:n,ctx:T}=this._processInputParams(o),t=this._def.effect||null,S={addIssue:(f)=>{if(I(T,f),f.fatal)n.abort();else n.dirty()},get path(){return T.path}};if(S.addIssue=S.addIssue.bind(S),t.type==="preprocess"){let f=t.transform(T.data,S);if(T.common.async)return Promise.resolve(f).then(async(y)=>{if(n.value==="aborted")return u;let A=await this._def.schema._parseAsync({data:y,path:T.path,parent:T});if(A.status==="aborted")return u;if(A.status==="dirty")return jT(A.value);if(n.value==="dirty")return jT(A.value);return A});else{if(n.value==="aborted")return u;let y=this._def.schema._parseSync({data:f,path:T.path,parent:T});if(y.status==="aborted")return u;if(y.status==="dirty")return jT(y.value);if(n.value==="dirty")return jT(y.value);return y}}if(t.type==="refinement"){let f=(y)=>{let A=t.refinement(y,S);if(T.common.async)return Promise.resolve(A);if(A instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return y};if(T.common.async===!1){let y=this._def.schema._parseSync({data:T.data,path:T.path,parent:T});if(y.status==="aborted")return u;if(y.status==="dirty")n.dirty();return f(y.value),{status:n.value,value:y.value}}else return this._def.schema._parseAsync({data:T.data,path:T.path,parent:T}).then((y)=>{if(y.status==="aborted")return u;if(y.status==="dirty")n.dirty();return f(y.value).then(()=>{return{status:n.value,value:y.value}})})}if(t.type==="transform")if(T.common.async===!1){let f=this._def.schema._parseSync({data:T.data,path:T.path,parent:T});if(!Dt(f))return f;let y=t.transform(f.value,S);if(y instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:y}}else return this._def.schema._parseAsync({data:T.data,path:T.path,parent:T}).then((f)=>{if(!Dt(f))return f;return Promise.resolve(t.transform(f.value,S)).then((y)=>({status:n.value,value:y}))});Mo.assertNever(t)}}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)===j.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:e.ZodOptional,...oo(n)})};class ln extends no{_parse(o){if(this._getType(o)===j.null)return nn(null);return this._def.innerType._parse(o)}unwrap(){return this._def.innerType}}ln.create=(o,n)=>{return new ln({innerType:o,typeName:e.ZodNullable,...oo(n)})};class PT extends no{_parse(o){let{ctx:n}=this._processInputParams(o),T=n.data;if(n.parsedType===j.undefined)T=this._def.defaultValue();return this._def.innerType._parse({data:T,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}PT.create=(o,n)=>{return new PT({innerType:o,typeName:e.ZodDefault,defaultValue:typeof n.default==="function"?n.default:()=>n.default,...oo(n)})};class gT extends no{_parse(o){let{ctx:n}=this._processInputParams(o),T={...n,common:{...n.common,issues:[]}},t=this._def.innerType._parse({data:T.data,path:T.path,parent:{...T}});if(Ut(t))return t.then((S)=>{return{status:"valid",value:S.status==="valid"?S.value:this._def.catchValue({get error(){return new Jn(T.common.issues)},input:T.data})}});else return{status:"valid",value:t.status==="valid"?t.value:this._def.catchValue({get error(){return new Jn(T.common.issues)},input:T.data})}}removeCatch(){return this._def.innerType}}gT.create=(o,n)=>{return new gT({innerType:o,typeName:e.ZodCatch,catchValue:typeof n.catch==="function"?n.catch:()=>n.catch,...oo(n)})};class It extends no{_parse(o){if(this._getType(o)!==j.nan){let T=this._getOrReturnCtx(o);return I(T,{code:Q.invalid_type,expected:j.nan,received:T.parsedType}),u}return{status:"valid",value:o.data}}}It.create=(o)=>{return new It({typeName:e.ZodNaN,...oo(o)})};var wR=Symbol("zod_brand");class hS extends no{_parse(o){let{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 rt extends no{_parse(o){let{status:n,ctx:T}=this._processInputParams(o);if(T.common.async)return(async()=>{let S=await this._def.in._parseAsync({data:T.data,path:T.path,parent:T});if(S.status==="aborted")return u;if(S.status==="dirty")return n.dirty(),jT(S.value);else return this._def.out._parseAsync({data:S.value,path:T.path,parent:T})})();else{let t=this._def.in._parseSync({data:T.data,path:T.path,parent:T});if(t.status==="aborted")return u;if(t.status==="dirty")return n.dirty(),{status:"dirty",value:t.value};else return this._def.out._parseSync({data:t.value,path:T.path,parent:T})}}static create(o,n){return new rt({in:o,out:n,typeName:e.ZodPipeline})}}class lT extends no{_parse(o){let n=this._def.innerType._parse(o),T=(t)=>{if(Dt(t))t.value=Object.freeze(t.value);return t};return Ut(n)?n.then((t)=>T(t)):T(n)}unwrap(){return this._def.innerType}}lT.create=(o,n)=>{return new lT({innerType:o,typeName:e.ZodReadonly,...oo(n)})};function P$(o,n={},T){if(o)return RT.create().superRefine((t,S)=>{var f,y;if(!o(t)){let A=typeof n==="function"?n(t):typeof n==="string"?{message:n}:n,M=(y=(f=A.fatal)!==null&&f!==void 0?f:T)!==null&&y!==void 0?y:!0,F=typeof A==="string"?{message:A}:A;S.addIssue({code:"custom",...F,fatal:M})}});return RT.create()}var KR={object:Do.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 XR=(o,n={message:`Input not instance of ${o.name}`})=>P$((T)=>T instanceof o,n),g$=Dn.create,l$=yT.create,ER=It.create,YR=AT.create,e$=bT.create,GR=JT.create,zR=Vt.create,HR=cT.create,mR=xT.create,QR=RT.create,DR=fT.create,UR=Nn.create,VR=Bt.create,BR=Un.create,jt=Do.create,CR=Do.strictCreate,LR=iT.create,IR=NS.create,rR=vT.create,jR=hn.create,NR=Ct.create,hR=Lt.create,bR=WT.create,cR=NT.create,xR=pT.create,iR=qT.create,vR=MT.create,pR=ZT.create,qR=OT.create,c$=Kn.create,ZR=Vn.create,PR=ln.create,gR=Kn.createWithPreprocess,lR=rt.create,eR=()=>g$().optional(),dR=()=>l$().optional(),uR=()=>e$().optional(),aR={string:(o)=>Dn.create({...o,coerce:!0}),number:(o)=>yT.create({...o,coerce:!0}),boolean:(o)=>bT.create({...o,coerce:!0}),bigint:(o)=>AT.create({...o,coerce:!0}),date:(o)=>JT.create({...o,coerce:!0})},sR=u,Go=Object.freeze({__proto__:null,defaultErrorMap:hT,setErrorMap:oR,getErrorMap:IS,makeIssue:rS,EMPTY_PATH:nR,addIssueToContext:I,ParseStatus:eo,INVALID:u,DIRTY:jT,OK:nn,isAborted:yy,isDirty:Ay,isValid:Dt,isAsync:Ut,get util(){return Mo},get objectUtil(){return fy},ZodParsedType:j,getParsedType:ST,ZodType:no,datetimeRegex:q$,ZodString:Dn,ZodNumber:yT,ZodBigInt:AT,ZodBoolean:bT,ZodDate:JT,ZodSymbol:Vt,ZodUndefined:cT,ZodNull:xT,ZodAny:RT,ZodUnknown:fT,ZodNever:Nn,ZodVoid:Bt,ZodArray:Un,ZodObject:Do,ZodUnion:iT,ZodDiscriminatedUnion:NS,ZodIntersection:vT,ZodTuple:hn,ZodRecord:Ct,ZodMap:Lt,ZodSet:WT,ZodFunction:NT,ZodLazy:pT,ZodLiteral:qT,ZodEnum:MT,ZodNativeEnum:ZT,ZodPromise:OT,ZodEffects:Kn,ZodTransformer:Kn,ZodOptional:Vn,ZodNullable:ln,ZodDefault:PT,ZodCatch:gT,ZodNaN:It,BRAND:wR,ZodBranded:hS,ZodPipeline:rt,ZodReadonly:lT,custom:P$,Schema:no,ZodSchema:no,late:KR,get ZodFirstPartyTypeKind(){return e},coerce:aR,any:QR,array:BR,bigint:YR,boolean:e$,date:GR,discriminatedUnion:IR,effect:c$,enum:vR,function:cR,instanceof:XR,intersection:rR,lazy:xR,literal:iR,map:hR,nan:ER,nativeEnum:pR,never:UR,null:mR,nullable:PR,number:l$,object:jt,oboolean:uR,onumber:dR,optional:ZR,ostring:eR,pipeline:lR,preprocess:gR,promise:qR,record:NR,set:bR,strictObject:CR,string:g$,symbol:zR,transformer:c$,tuple:jR,undefined:HR,union:LR,unknown:DR,void:VR,NEVER:sR,ZodIssueCode:Q,quotelessJson:sJ,ZodError:Jn});function d$(o){let n=o.runtimeEnvStrict??o.runtimeEnv??process.env;if(o.emptyStringAsUndefined??!1){for(let[K,m]of Object.entries(n))if(m==="")delete n[K]}if(!!o.skipValidation)return n;let S=typeof o.client==="object"?o.client:{},f=typeof o.server==="object"?o.server:{},y=typeof o.shared==="object"?o.shared:{},A=jt(S),M=jt(f),F=jt(y),$=o.isServer??(typeof window==="undefined"||("Deno"in window)),W=A.merge(F),O=M.merge(F).merge(A),G=$?O.safeParse(n):W.safeParse(n),D=o.onValidationError??((K)=>{throw console.error("\u274C Invalid environment variables:",K.flatten().fieldErrors),new Error("Invalid environment variables")}),z=o.onInvalidAccess??((K)=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(G.success===!1)return D(G.error);let Y=(K)=>{if(!o.clientPrefix)return!0;return!K.startsWith(o.clientPrefix)&&!(K in F.shape)},B=(K)=>{return $||!Y(K)},v=(K)=>{return K==="__esModule"||K==="$$typeof"},x=(o.extends??[]).reduce((K,m)=>{return Object.assign(K,m)},{}),a=Object.assign(G.data,x);return new Proxy(a,{get(K,m){if(typeof m!=="string")return;if(v(m))return;if(!B(m))return z(m);return Reflect.get(K,m)}})}var o0="__vite_start_time"in globalThis,n0=typeof window!=="undefined",d7="vitest"in globalThis,Cn=d$({isServer:!o0&&!n0,server:{CI:Go.string().transform((o)=>!0).optional(),POSTGRES_USER:Go.string(),POSTGRES_PASSWORD:Go.string(),POSTGRES_DATABASE:Go.string(),POSTGRES_HOST:Go.string(),POSTGRES_PORT:Go.string().transform((o)=>Number.parseInt(o,10)),BACKEND_PORT:Go.string().transform((o)=>Number.parseInt(o,10)),RUN_WORKERS_FROM_SOURCE:Go.union([Go.literal("true"),Go.literal("false")]).optional().transform((o)=>o==="true"),FRONTEND_PORT:Go.string().transform((o)=>Number.parseInt(o,10)),FRONTEND_ORIGINS:Go.string().transform((o)=>JSON.parse(o)).pipe(Go.array(Go.string())),OPENAI_API_KEY:Go.string().optional()},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:Go.string(),VITE_USE_SELF_SIGNED_CERTIFICATE:Go.union([Go.literal("true"),Go.literal("false")]).optional().transform((o)=>o==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var a$=Fy(import.meta.dirname,"../dev"),s$=Cn.VITE_USE_SELF_SIGNED_CERTIFICATE?{cert:u$(Fy(a$,"./cert.pem"),"utf-8"),key:u$(Fy(a$,"./key.pem"),"utf-8")}:void 0;import l0 from"path";import m0 from"os";import Q0 from"fs";var bS=new Map,$y=new Map,ky=Symbol("OriginError"),eT={};class Xn extends Promise{constructor(o,n,T,t,S={}){let f,y;super((A,M)=>{f=A,y=M});this.tagged=Array.isArray(o.raw),this.strings=o,this.args=n,this.handler=T,this.canceller=t,this.options=S,this.state=null,this.statement=null,this.resolve=(A)=>(this.active=!1,f(A)),this.reject=(A)=>(this.active=!1,y(A)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[ky]=this.handler.debug?new Error:this.tagged&&T0(this.strings)}get origin(){return(this.handler.debug?this[ky].stack:this.tagged&&$y.has(this.strings)?$y.get(this.strings):$y.set(this.strings,this[ky].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();let t=new Promise((S,f)=>{this.cursorFn=(y)=>{return S({value:y,done:!1}),new Promise((A)=>T=A)},this.resolve=()=>(this.active=!1,S({done:!0})),this.reject=(y)=>(this.active=!1,f(y))});return this.execute(),t},return(){return T&&T(eT),{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 T0(o){if(bS.has(o))return bS.get(o);let n=Error.stackTraceLimit;return Error.stackTraceLimit=4,bS.set(o,new Error),Error.stackTraceLimit=n,bS.get(o)}class dT extends Error{constructor(o){super(o.message);this.name=this.constructor.name,Object.assign(this,o)}}var Lo={connection:ok,postgres:nk,generic:Tk,notSupported:tk};function ok(o,n,T){let{host:t,port:S}=T||n,f=Object.assign(new Error("write "+o+" "+(n.path||t+":"+S)),{code:o,errno:o,address:n.path||t},n.path?{}:{port:S});return Error.captureStackTrace(f,ok),f}function nk(o){let n=new dT(o);return Error.captureStackTrace(n,nk),n}function Tk(o,n){let T=Object.assign(new Error(o+": "+n),{code:o});return Error.captureStackTrace(T,Tk),T}function tk(o){let n=Object.assign(new Error(o+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:o});return Error.captureStackTrace(n,tk),n}var t0={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 iS{then(){Jy()}catch(){Jy()}finally(){Jy()}}class ct extends iS{constructor(o){super();this.value=qS(o)}}class bn extends iS{constructor(o,n,T){super();this.value=o,this.type=n,this.array=T}}class vS extends iS{constructor(o,n){super();this.first=o,this.rest=n}build(o,n,T,t){let S=S0.map(([f,y])=>({fn:y,i:o.search(f)})).sort((f,y)=>f.i-y.i).pop();return S.i===-1?wy(this.first,t):S.fn(this.first,this.rest,n,T,t)}}function pS(o,n,T,t){let S=o instanceof bn?o.value:o;if(S===void 0){if(o instanceof bn?o.value=t.transform.undefined:S=o=t.transform.undefined,S===void 0)throw Lo.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+T.push(o instanceof bn?(n.push(o.value),o.array?o.array[o.type||xS(o.value)]||o.type||Ak(o.value):o.type):(n.push(o),xS(o)))}var fk=Fk(t0);function Oy(o,n,T,t,S,f){for(let y=1;y<o.strings.length;y++)n+=_y(n,T,t,S,f)+o.strings[y],T=o.args[y];return n}function _y(o,n,T,t,S){return n instanceof vS?n.build(o,T,t,S):n instanceof Xn?Wy(n,T,t,S):n instanceof ct?n.value:n&&n[0]instanceof Xn?n.reduce((f,y)=>f+" "+Wy(y,T,t,S),""):pS(n,T,t,S)}function Wy(o,n,T,t){return o.fragment=!0,Oy(o,o.strings[0],o.args[0],n,T,t)}function yk(o,n,T,t,S){return o.map((f)=>"("+t.map((y)=>_y("values",f[y],n,T,S)).join(",")+")").join(",")}function Sk(o,n,T,t,S){let f=Array.isArray(o[0]),y=n.length?n.flat():Object.keys(f?o[0]:o);return yk(f?o:[o],T,t,y,S)}function cS(o,n,T,t,S){if(typeof o==="string"&&(o=[o].concat(n)),Array.isArray(o))return wy(o,S);let f;return(n.length?n.flat():Object.keys(o)).map((A)=>{return f=o[A],(f instanceof Xn?Wy(f,T,t,S):f instanceof ct?f.value:pS(f,T,t,S))+" as "+qS(S.transform.column.to?S.transform.column.to(A):A)}).join(",")}var S0=Object.entries({values:Sk,in:(...o)=>{let n=Sk(...o);return n==="()"?"(null)":n},select:cS,as:cS,returning:cS,"\\(":cS,update(o,n,T,t,S){return(n.length?n.flat():Object.keys(o)).map((f)=>qS(S.transform.column.to?S.transform.column.to(f):f)+"="+_y("values",o[f],T,t,S))},insert(o,n,T,t,S){let f=n.length?n.flat():Object.keys(Array.isArray(o)?o[0]:o);return"("+wy(f,S)+")values"+yk(Array.isArray(o)?o:[o],T,t,f,S)}}).map(([o,n])=>[new RegExp("((?:^|[\\s(])"+o+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),n]);function Jy(){throw Lo.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:f0,parsers:y0}=fk;function Ak(o){if(Array.isArray(o))return Ak(o[0]);return typeof o==="string"?1009:0}var Mk=function(o){let n=Fk(o||{});return{serializers:Object.assign({},f0,n.serializers),parsers:Object.assign({},y0,n.parsers)}};function Fk(o){return Object.keys(o).reduce((n,T)=>{if(o[T].from&&[].concat(o[T].from).forEach((t)=>n.parsers[t]=o[T].parse),o[T].serialize)n.serializers[o[T].to]=o[T].serialize,o[T].from&&[].concat(o[T].from).forEach((t)=>n.serializers[t]=o[T].serialize);return n},{parsers:{},serializers:{}})}function wy(o,{transform:{column:n}}){return o.map((T)=>qS(n.to?n.to(T):T)).join(",")}var qS=function o(n){return'"'+n.replace(/"/g,'""').replace(/\./g,'"."')+'"'},xS=function o(n){return n instanceof bn?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},A0=/\\/g,M0=/"/g;function F0(o){return o.replace(A0,"\\\\").replace(M0,"\\\"")}var $k=function o(n,T,t,S){if(Array.isArray(n)===!1)return n;if(!n.length)return"{}";let f=n[0],y=S===1020?";":",";if(Array.isArray(f)&&!f.type)return"{"+n.map((A)=>o(A,T,t,S)).join(y)+"}";return"{"+n.map((A)=>{if(A===void 0){if(A=t.transform.undefined,A===void 0)throw Lo.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return A===null?"null":'"'+F0(T?T(A.type?A.value:A):""+A)+'"'}).join(y)+"}"},Ry={i:0,char:null,str:"",quoted:!1,last:0},kk=function o(n,T,t){return Ry.i=Ry.last=0,Jk(Ry,n,T,t)};function Jk(o,n,T,t){let S=[],f=t===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==='"')S.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,S.push(Jk(o,n,T,t));else if(o.char==="}"){o.quoted=!1,o.last<o.i&&S.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===f&&o.p!=="}"&&o.p!=='"')S.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&&S.push(T?T(n.slice(o.last,o.i+1)):n.slice(o.last,o.i+1)),S}var _T=(o)=>{let n=o[0];for(let T=1;T<o.length;T++)n+=o[T]==="_"?o[++T].toUpperCase():o[T];return n},wT=(o)=>{let n=o[0].toUpperCase();for(let T=1;T<o.length;T++)n+=o[T]==="_"?o[++T].toUpperCase():o[T];return n},KT=(o)=>o.replace(/_/g,"-"),Nt=(o)=>o.replace(/([A-Z])/g,"_$1").toLowerCase(),ht=(o)=>(o.slice(0,1)+o.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),bt=(o)=>o.replace(/-/g,"_");function Ky(o){return function n(T,t){return typeof T==="object"&&T!==null&&(t.type===114||t.type===3802)?Array.isArray(T)?T.map((S)=>n(S,t)):Object.entries(T).reduce((S,[f,y])=>Object.assign(S,{[o(f)]:n(y,t)}),{}):T}}_T.column={from:_T};_T.value={from:Ky(_T)};Nt.column={to:Nt};var Xy={..._T};Xy.column.to=Nt;wT.column={from:wT};wT.value={from:Ky(wT)};ht.column={to:ht};var Ey={...wT};Ey.column.to=ht;KT.column={from:KT};KT.value={from:Ky(KT)};bt.column={to:bt};var Yy={...KT};Yy.column.to=bt;import Rk from"net";import R0 from"tls";import xt from"crypto";import Gy from"stream";import{performance as Wk}from"perf_hooks";class XT extends Array{constructor(){super();Object.defineProperties(this,{count:{value:null,writable:!0},state:{value:null,writable:!0},command:{value:null,writable:!0},columns:{value:null,writable:!0},statement:{value:null,writable:!0}})}static get[Symbol.species](){return Array}}var Rn=$0;function $0(o=[]){let n=o.slice(),T=0;return{get length(){return n.length-T},remove:(t)=>{let S=n.indexOf(t);return S===-1?null:(n.splice(S,1),t)},push:(t)=>(n.push(t),t),shift:()=>{let t=n[T++];if(T===n.length)T=0,n=[];else n[T-1]=void 0;return t}}}var uo=Buffer.allocUnsafe(256),k0="BCcDdEFfHPpQSX".split("").reduce((o,n)=>{let T=n.charCodeAt(0);return o[n]=()=>{return uo[0]=T,Jo.i=5,Jo},o},{}),Jo=Object.assign(J0,k0,{N:String.fromCharCode(0),i:0,inc(o){return Jo.i+=o,Jo},str(o){let n=Buffer.byteLength(o);return ZS(n),Jo.i+=uo.write(o,Jo.i,n,"utf8"),Jo},i16(o){return ZS(2),uo.writeUInt16BE(o,Jo.i),Jo.i+=2,Jo},i32(o,n){if(n||n===0)return uo.writeUInt32BE(o,n),Jo;return ZS(4),uo.writeUInt32BE(o,Jo.i),Jo.i+=4,Jo},z(o){return ZS(o),uo.fill(0,Jo.i,Jo.i+o),Jo.i+=o,Jo},raw(o){return uo=Buffer.concat([uo.subarray(0,Jo.i),o]),Jo.i=uo.length,Jo},end(o=1){uo.writeUInt32BE(Jo.i-o,o);let n=uo.subarray(0,Jo.i);return Jo.i=0,uo=Buffer.allocUnsafe(256),n}}),P=Jo;function ZS(o){if(uo.length-Jo.i<o){let n=uo,T=n.length;uo=Buffer.allocUnsafe(T+(T>>1)+o),n.copy(uo)}}function J0(){return Jo.i=0,Jo}var my=wk,W0=1,FT=P().S().end(),Ok=P().H().end(),O0=P().i32(8).i32(80877103).end(8),_0=Buffer.concat([P().E().str(P.N).i32(0).end(),FT]),w0=P().D().str("S").str(P.N).end(),uT=()=>{},K0=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),X0={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 wk(o,n={},{onopen:T=uT,onend:t=uT,onclose:S=uT}={}){let{ssl:f,max:y,user:A,host:M,port:F,database:$,parsers:W,transform:O,onnotice:G,onnotify:D,onparameter:z,max_pipeline:Y,keep_alive:B,backoff:v,target_session_attrs:x}=o,a=Rn(),E=W0++,K={pid:null,secret:null},m=Hy(Sf,o.idle_timeout),c=Hy(Sf,o.max_lifetime),b=Hy(ck,o.connect_timeout),w=null,i,N=new XT,q=Buffer.alloc(0),ko=o.fetch_types,Oo={},Sn={},cn=Math.random().toString(36).slice(2),H=1,Z=0,Fo=0,zo=0,Io=0,To=0,_o=0,Co=0,mo=null,Ko=null,po=!1,wo=null,En=null,qo=null,en=null,ro=null,Xo=null,Yn=null,Ln=null,C=null,nt=null,Zo={queue:n.closed,idleTimer:m,connect(k){qo=k||!0,ay()},terminate:tt,execute:Tt,cancel:jk,end:Sf,count:0,id:E};return n.closed&&n.closed.push(Zo),Zo;async function rk(){let k;try{k=o.socket?await Promise.resolve(o.socket(o)):new Rk.Socket}catch(_){zT(_);return}return k.on("error",zT),k.on("close",sy),k.on("drain",dy),k}async function jk({pid:k,secret:_},g,$o){try{i=P().i32(16).i32(80877102).i32(k).i32(_).end(16),await uy(),w.once("error",$o),w.once("close",g)}catch(Uo){$o(Uo)}}function Tt(k){if(po)return lt(k,Lo.connection("CONNECTION_DESTROYED",o));if(k.cancelled)return;try{return k.state=K,C?a.push(k):(C=k,C.active=!0),bk(k),co(Nk(k))&&!k.describeFirst&&!k.cursorFn&&a.length<Y&&(!k.options.onexecute||k.options.onexecute(Zo))}catch(_){return a.length===0&&co(FT),In(_),!0}}function Nk(k){if(k.parameters.length>=65534)throw Lo.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return k.options.simple?P().Q().str(k.statement.string+P.N).end():k.describeFirst?Buffer.concat([gy(k),Ok]):k.prepare?k.prepared?gt(k):Buffer.concat([gy(k),gt(k)]):hk(k)}function gy(k){return Buffer.concat([nA(k.statement.string,k.parameters,k.statement.types,k.statement.name),zJ("S",k.statement.name)])}function gt(k){return Buffer.concat([GJ(k.parameters,k.statement.types,k.statement.name,k.cursorName),k.cursorFn?TA("",k.cursorRows):_0])}function hk(k){return Buffer.concat([nA(k.statement.string,k.parameters,k.statement.types),w0,gt(k)])}function bk(k){let _=[],g=[],$o=Oy(k,k.strings[0],k.args[0],_,g,o);!k.tagged&&k.args.forEach((Uo)=>pS(Uo,_,g,o)),k.prepare=o.prepare&&("prepare"in k.options?k.options.prepare:!0),k.string=$o,k.signature=k.prepare&&g+$o,k.onlyDescribe&&delete Sn[k.signature],k.parameters=k.parameters||_,k.prepared=k.prepare&&k.signature in Sn,k.describeFirst=k.onlyDescribe||_.length&&!k.prepared,k.statement=k.prepared?Sn[k.signature]:{string:$o,types:g,name:k.prepare?cn+H++:""},typeof o.debug==="function"&&o.debug(E,$o,_,g)}function co(k,_){if(Xo=Xo?Buffer.concat([Xo,k]):Buffer.from(k),_||Xo.length>=1024)return ly(_);return Ko===null&&(Ko=setImmediate(ly)),!0}function ly(k){let _=w.write(Xo,k);return Ko!==null&&clearImmediate(Ko),Xo=Ko=null,_}function ck(){In(Lo.connection("CONNECT_TIMEOUT",o,w)),w.destroy()}async function ey(){if(co(O0),!await new Promise((_)=>w.once("data",(g)=>_(g[0]===83)))&&f==="prefer")return GT();w.removeAllListeners(),w=R0.connect({socket:w,servername:Rk.isIP(w.host)?void 0:w.host,...f==="require"||f==="allow"||f==="prefer"?{rejectUnauthorized:!1}:f==="verify-full"?{}:typeof f==="object"?f:{}}),w.on("secureConnect",GT),w.on("error",zT),w.on("close",sy),w.on("drain",dy)}function dy(){!C&&T(Zo)}function tf(k){if(wo){if(wo.push(k),Fo-=k.length,Fo>=0)return}q=wo?Buffer.concat(wo,To-Fo):q.length===0?k:Buffer.concat([q,k],q.length+k.length);while(q.length>4){if(To=q.readUInt32BE(1),To>=q.length){Fo=To-q.length,wo=[q];break}try{xk(q.subarray(0,To+1))}catch(_){C&&(C.cursorFn||C.describeFirst)&&co(FT),In(_)}q=q.subarray(To+1),Fo=0,wo=null}}async function uy(){if(po=!1,Oo={},w||(w=await rk()),!w)return;if(b.start(),o.socket)return f?ey():GT();if(w.on("connect",f?ey:GT),o.path)return w.connect(o.path);w.ssl=f,w.connect(F[zo],M[zo]),w.host=M[zo],w.port=F[zo],zo=(zo+1)%F.length}function ay(){setTimeout(uy,Z?Z+_o-Wk.now():0)}function GT(){try{Sn={},ko=o.fetch_types,cn=Math.random().toString(36).slice(2),H=1,c.start(),w.on("data",tf),B&&w.setKeepAlive&&w.setKeepAlive(!0,1000*B);let k=mJ();co(k)}catch(k){zT(k)}}function zT(k){if(Zo.queue===n.connecting&&o.host[Io+1])return;In(k);while(a.length)lt(a.shift(),k)}function In(k){ro&&(ro.destroy(k),ro=null),C&<(C,k),qo&&(lt(qo,k),qo=null)}function lt(k,_){"query"in _||"parameters"in _||Object.defineProperties(_,{stack:{value:_.stack+k.origin.replace(/.*\n/,`
|
|
10
|
+
`),enumerable:o.debug},query:{value:k.string,enumerable:o.debug},parameters:{value:k.parameters,enumerable:o.debug},args:{value:k.args,enumerable:o.debug},types:{value:k.statement&&k.statement.types,enumerable:o.debug}}),k.reject(_)}function Sf(){return en||(!Zo.reserved&&t(Zo),!Zo.reserved&&!qo&&!C&&a.length===0?(tt(),new Promise((k)=>w&&w.readyState!=="closed"?w.once("close",k):k())):en=new Promise((k)=>Yn=k))}function tt(){if(po=!0,ro||C||qo||a.length)zT(Lo.connection("CONNECTION_DESTROYED",o));if(clearImmediate(Ko),w)w.removeListener("data",tf),w.removeListener("connect",GT),w.readyState==="open"&&w.end(P().X().end());Yn&&(Yn(),en=Yn=null)}async function sy(k){if(q=Buffer.alloc(0),Fo=0,wo=null,clearImmediate(Ko),w.removeListener("data",tf),w.removeListener("connect",GT),m.cancel(),c.cancel(),b.cancel(),w.removeAllListeners(),w=null,qo)return ay();!k&&(C||a.length)&&zT(Lo.connection("CONNECTION_CLOSED",o,w)),Z=Wk.now(),k&&o.shared.retries++,_o=(typeof v==="function"?v(o.shared.retries):v)*1000,S(Zo,Lo.connection("CONNECTION_CLOSED",o,w))}function xk(k,_=k[0]){(_===68?ik:_===100?WJ:_===65?MJ:_===83?vk:_===90?pk:_===67?qk:_===50?oA:_===49?Zk:_===116?Pk:_===84?gk:_===82?lk:_===110?oJ:_===75?nJ:_===69?yJ:_===115?FJ:_===51?$J:_===71?kJ:_===78?_J:_===72?JJ:_===99?OJ:_===73?wJ:_===86?KJ:_===118?XJ:_===87?RJ:EJ)(k)}function ik(k){let _=7,g,$o,Uo,Po=C.isRaw?new Array(C.statement.columns.length):{};for(let ao=0;ao<C.statement.columns.length;ao++)$o=C.statement.columns[ao],g=k.readInt32BE(_),_+=4,Uo=g===-1?null:C.isRaw===!0?k.subarray(_,_+=g):$o.parser===void 0?k.toString("utf8",_,_+=g):$o.parser.array===!0?$o.parser(k.toString("utf8",_+1,_+=g)):$o.parser(k.toString("utf8",_,_+=g)),C.isRaw?Po[ao]=C.isRaw===!0?Uo:O.value.from?O.value.from(Uo,$o):Uo:Po[$o.name]=O.value.from?O.value.from(Uo,$o):Uo;C.forEachFn?C.forEachFn(O.row.from?O.row.from(Po):Po,N):N[Co++]=O.row.from?O.row.from(Po):Po}function vk(k){let[_,g]=k.toString("utf8",5,k.length-1).split(P.N);if(Oo[_]=g,o.parameters[_]!==g)o.parameters[_]=g,z&&z(_,g)}function pk(k){if(C&&C.options.simple&&C.resolve(En||N),C=En=null,N=new XT,b.cancel(),qo){if(x){if(!Oo.in_hot_standby||!Oo.default_transaction_read_only)return fJ();else if(SJ(x,Oo))return tt()}if(ko)return qo===!0&&(qo=null),TJ();qo!==!0&&Tt(qo),o.shared.retries=Io=0,qo=null;return}while(a.length&&(C=a.shift())&&(C.active=!0,C.cancelled))wk(o).cancel(C.state,C.cancelled.resolve,C.cancelled.reject);if(C)return;Zo.reserved?!Zo.reserved.release&&k[5]===73?en?tt():(Zo.reserved=null,T(Zo)):Zo.reserved():en?tt():T(Zo)}function qk(k){Co=0;for(let _=k.length-1;_>0;_--){if(k[_]===32&&k[_+1]<58&&N.count===null)N.count=+k.toString("utf8",_+1,k.length-1);if(k[_-1]>=65){N.command=k.toString("utf8",5,_),N.state=K;break}}if(nt&&(nt(),nt=null),N.command==="BEGIN"&&y!==1&&!Zo.reserved)return In(Lo.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(C.options.simple)return oA();if(C.cursorFn)N.count&&C.cursorFn(N),co(FT);C.resolve(N)}function Zk(){C.parsing=!1}function oA(){!N.statement&&(N.statement=C.statement),N.columns=C.statement.columns}function Pk(k){let _=k.readUInt16BE(5);for(let g=0;g<_;++g)!C.statement.types[g]&&(C.statement.types[g]=k.readUInt32BE(7+g*4));C.prepare&&(Sn[C.signature]=C.statement),C.describeFirst&&!C.onlyDescribe&&(co(gt(C)),C.describeFirst=!1)}function gk(k){if(N.command)En=En||[N],En.push(N=new XT),N.count=null,C.statement.columns=null;let _=k.readUInt16BE(5),g=7,$o;C.statement.columns=Array(_);for(let Uo=0;Uo<_;++Uo){$o=g;while(k[g++]!==0);let Po=k.readUInt32BE(g),ao=k.readUInt16BE(g+4),dn=k.readUInt32BE(g+6);C.statement.columns[Uo]={name:O.column.from?O.column.from(k.toString("utf8",$o,g-1)):k.toString("utf8",$o,g-1),parser:W[dn],table:Po,number:ao,type:dn},g+=18}if(N.statement=C.statement,C.onlyDescribe)return C.resolve(C.statement),co(FT)}async function lk(k,_=k.readUInt32BE(5)){(_===3?ek:_===5?dk:_===10?uk:_===11?ak:_===12?sk:_!==0?YJ:uT)(k,_)}async function ek(){let k=await ff();co(P().p().str(k).z(1).end())}async function dk(k){let _="md5"+await _k(Buffer.concat([Buffer.from(await _k(await ff()+A)),k.subarray(9)]));co(P().p().str(_).z(1).end())}async function uk(){Ln=(await xt.randomBytes(18)).toString("base64"),P().p().str("SCRAM-SHA-256"+P.N);let k=P.i;co(P.inc(4).str("n,,n=*,r="+Ln).i32(P.i-k-4,k).end())}async function ak(k){let _=k.toString("utf8",9).split(",").reduce((ao,dn)=>(ao[dn[0]]=dn.slice(2),ao),{}),g=await xt.pbkdf2Sync(await ff(),Buffer.from(_.s,"base64"),parseInt(_.i),32,"sha256"),$o=await PS(g,"Client Key"),Uo="n=*,r="+Ln+",r="+_.r+",s="+_.s+",i="+_.i+",c=biws,r="+_.r;mo=(await PS(await PS(g,"Server Key"),Uo)).toString("base64");let Po="c=biws,r="+_.r+",p="+Y0($o,Buffer.from(await PS(await E0($o),Uo))).toString("base64");co(P().p().str(Po).end())}function sk(k){if(k.toString("utf8",9).split(P.N,1)[0].slice(2)===mo)return;In(Lo.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),w.destroy()}function ff(){return Promise.resolve(typeof o.pass==="function"?o.pass():o.pass)}function oJ(){if(N.statement=C.statement,N.statement.columns=[],C.onlyDescribe)return C.resolve(C.statement),co(FT)}function nJ(k){K.pid=k.readUInt32BE(5),K.secret=k.readUInt32BE(9)}async function TJ(){ko=!1,(await new Xn([`
|
|
4
11
|
select b.oid, b.typarray
|
|
5
12
|
from pg_catalog.pg_type a
|
|
6
13
|
left join pg_catalog.pg_type b on b.oid = a.typelem
|
|
7
14
|
where a.typcategory = 'A'
|
|
8
15
|
group by b.oid, b.typarray
|
|
9
16
|
order by b.oid
|
|
10
|
-
`],[],
|
|
17
|
+
`],[],Tt)).forEach(({oid:_,typarray:g})=>tJ(_,g))}function tJ(k,_){if(!!o.parsers[_]&&!!o.serializers[_])return;let g=o.parsers[k];o.shared.typeArrayMap[k]=_,o.parsers[_]=($o)=>kk($o,g,_),o.parsers[_].array=!0,o.serializers[_]=($o)=>$k($o,o.serializers[k],o,_)}function SJ(k,_){return k==="read-write"&&_.default_transaction_read_only==="on"||k==="read-only"&&_.default_transaction_read_only==="off"||k==="primary"&&_.in_hot_standby==="on"||k==="standby"&&_.in_hot_standby==="off"||k==="prefer-standby"&&_.in_hot_standby==="off"&&o.host[Io]}function fJ(){let k=new Xn([`
|
|
11
18
|
show transaction_read_only;
|
|
12
19
|
select pg_catalog.pg_is_in_recovery()
|
|
13
|
-
`],[],
|
|
20
|
+
`],[],Tt,null,{simple:!0});k.resolve=([[_],[g]])=>{Oo.default_transaction_read_only=_.transaction_read_only,Oo.in_hot_standby=g.pg_is_in_recovery?"on":"off"},k.execute()}function yJ(k){C&&(C.cursorFn||C.describeFirst)&&co(FT);let _=Lo.postgres(zy(k));C&&C.retried?In(C.retried):C&&C.prepared&&K0.has(_.routine)?AJ(C,_):In(_)}function AJ(k,_){delete Sn[k.signature],k.retried=_,Tt(k)}function MJ(k){if(!D)return;let _=9;while(k[_++]!==0);D(k.toString("utf8",9,_-1),k.toString("utf8",_,k.length-1))}async function FJ(){try{let k=await Promise.resolve(C.cursorFn(N));Co=0,k===eT?co(HJ(C.portal)):(N=new XT,co(TA("",C.cursorRows)))}catch(k){co(FT),C.reject(k)}}function $J(){N.count&&C.cursorFn(N),C.resolve(N)}function kJ(){ro=new Gy.Writable({autoDestroy:!0,write(k,_,g){w.write(P().d().raw(k).end(),g)},destroy(k,_){_(k),w.write(P().f().str(k+P.N).end()),ro=null},final(k){w.write(P().c().end()),nt=k}}),C.resolve(ro)}function JJ(){ro=new Gy.Readable({read(){w.resume()}}),C.resolve(ro)}function RJ(){ro=new Gy.Duplex({autoDestroy:!0,read(){w.resume()},write(k,_,g){w.write(P().d().raw(k).end(),g)},destroy(k,_){_(k),w.write(P().f().str(k+P.N).end()),ro=null},final(k){w.write(P().c().end()),nt=k}}),C.resolve(ro)}function WJ(k){ro&&(ro.push(k.subarray(5))||w.pause())}function OJ(){ro&&ro.push(null),ro=null}function _J(k){G?G(zy(k)):console.log(zy(k))}function wJ(){}function KJ(){In(Lo.notSupported("FunctionCallResponse"))}function XJ(){In(Lo.notSupported("NegotiateProtocolVersion"))}function EJ(k){console.error("Postgres.js : Unknown Message:",k[0])}function YJ(k,_){console.error("Postgres.js : Unknown Auth:",_)}function GJ(k,_,g="",$o=""){let Uo,Po;return P().B().str($o+P.N).str(g+P.N).i16(0).i16(k.length),k.forEach((ao,dn)=>{if(ao===null)return P.i32(4294967295);Po=_[dn],k[dn]=ao=Po in o.serializers?o.serializers[Po](ao):""+ao,Uo=P.i,P.inc(4).str(ao).i32(P.i-Uo-4,Uo)}),P.i16(0),P.end()}function nA(k,_,g,$o=""){return P().P().str($o+P.N).str(k+P.N).i16(_.length),_.forEach((Uo,Po)=>P.i32(g[Po]||0)),P.end()}function zJ(k,_=""){return P().D().str(k).str(_+P.N).end()}function TA(k="",_=0){return Buffer.concat([P().E().str(k+P.N).i32(_).end(),Ok])}function HJ(k=""){return Buffer.concat([P().C().str("P").str(k+P.N).end(),P().S().end()])}function mJ(){return i||P().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:A,database:$,client_encoding:"UTF8"},o.connection)).filter(([,k])=>k).map(([k,_])=>k+P.N+_).join(P.N)).z(2).end(0)}}function zy(o){let n={},T=5;for(let t=5;t<o.length-1;t++)if(o[t]===0)n[X0[o[T]]]=o.toString("utf8",T+1,t),T=t+1;return n}function _k(o){return xt.createHash("md5").update(o).digest("hex")}function PS(o,n){return xt.createHmac("sha256",o).update(n).digest()}function E0(o){return xt.createHash("sha256").update(o).digest()}function Y0(o,n){let T=Math.max(o.length,n.length),t=Buffer.allocUnsafe(T);for(let S=0;S<T;S++)t[S]=o[S]^n[S];return t}function Hy(o,n){if(n=typeof n==="function"?n():n,!n)return{cancel:uT,start:uT};let T;return{cancel(){T&&(clearTimeout(T),T=null)},start(){T&&clearTimeout(T),T=setTimeout(t,n*1000,arguments)}};function t(S){o.apply(null,S),T=null}}var Kk=()=>{};function Qy(o,n){let T=new Map,t="postgresjs_"+Math.random().toString(36).slice(2),S={},f,y,A=!1,M=W.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(A)return;y=null,S.pid=S.secret=void 0,O(await G(M,t,n.publications)),T.forEach((z)=>z.forEach(({onsubscribe:Y})=>Y()))},no_subscribe:!0}),F=M.end,$=M.close;return M.end=async()=>{return A=!0,y&&await new Promise((z)=>(y.once("close",z),y.end())),F()},M.close=async()=>{return y&&await new Promise((z)=>(y.once("close",z),y.end())),$()},W;async function W(z,Y,B=Kk,v=Kk){if(z=H0(z),!f)f=G(M,t,n.publications);let x={fn:Y,onsubscribe:B},a=T.has(z)?T.get(z).add(x):T.set(z,new Set([x])).get(z),E=()=>{a.delete(x),a.size===0&&T.delete(z)};return f.then((K)=>{return O(K),B(),y&&y.on("error",v),{unsubscribe:E,state:S,sql:M}})}function O(z){y=z.stream,S.pid=z.state.pid,S.secret=z.state.secret}async function G(z,Y,B){if(!B)throw new Error("Missing publication names");let v=await z.unsafe(`CREATE_REPLICATION_SLOT ${Y} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[x]=v,a=await z.unsafe(`START_REPLICATION SLOT ${Y} LOGICAL ${x.consistent_point} (proto_version '1', publication_names '${B}')`).writable(),E={lsn:Buffer.concat(x.consistent_point.split("/").map((w)=>Buffer.from(("00000000"+w).slice(-8),"hex")))};return a.on("data",m),a.on("error",K),a.on("close",z.close),{stream:a,state:v.state};function K(w){console.error("Unexpected error during logical streaming - reconnecting",w)}function m(w){if(w[0]===119)z0(w.subarray(25),E,z.options.parsers,c,n.transform);else if(w[0]===107&&w[17])E.lsn=w.subarray(1,9),b()}function c(w,i){let N=i.relation.schema+"."+i.relation.table;D("*",w,i),D("*:"+N,w,i),i.relation.keys.length&&D("*:"+N+"="+i.relation.keys.map((q)=>w[q.name]),w,i),D(i.command,w,i),D(i.command+":"+N,w,i),i.relation.keys.length&&D(i.command+":"+N+"="+i.relation.keys.map((q)=>w[q.name]),w,i)}function b(){let w=Buffer.alloc(34);w[0]=114,w.fill(E.lsn,1),w.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),a.write(w)}}function D(z,Y,B){T.has(z)&&T.get(z).forEach(({fn:v})=>v(Y,B,z))}}function G0(o){return new Date(Date.UTC(2000,0,1)+Number(o/BigInt(1000)))}function z0(o,n,T,t,S){let f=(y,[A,M])=>(y[A.charCodeAt(0)]=M,y);Object.entries({R:(y)=>{let A=1,M=n[y.readUInt32BE(A)]={schema:y.toString("utf8",A+=4,A=y.indexOf(0,A))||"pg_catalog",table:y.toString("utf8",A+1,A=y.indexOf(0,A+1)),columns:Array(y.readUInt16BE(A+=2)),keys:[]};A+=2;let F=0,$;while(A<y.length)$=M.columns[F++]={key:y[A++],name:S.column.from?S.column.from(y.toString("utf8",A,A=y.indexOf(0,A))):y.toString("utf8",A,A=y.indexOf(0,A)),type:y.readUInt32BE(A+=1),parser:T[y.readUInt32BE(A)],atttypmod:y.readUInt32BE(A+=4)},$.key&&M.keys.push($),A+=4},Y:()=>{},O:()=>{},B:(y)=>{n.date=G0(y.readBigInt64BE(9)),n.lsn=y.subarray(1,9)},I:(y)=>{let A=1,M=n[y.readUInt32BE(A)],{row:F}=gS(y,M.columns,A+=7,S);t(F,{command:"insert",relation:M})},D:(y)=>{let A=1,M=n[y.readUInt32BE(A)];A+=4;let F=y[A]===75;t(F||y[A]===79?gS(y,M.columns,A+=3,S).row:null,{command:"delete",relation:M,key:F})},U:(y)=>{let A=1,M=n[y.readUInt32BE(A)];A+=4;let F=y[A]===75,$=F||y[A]===79?gS(y,M.columns,A+=3,S):null;$&&(A=$.i);let{row:W}=gS(y,M.columns,A+3,S);t(W,{command:"update",relation:M,key:F,old:$&&$.row})},T:()=>{},C:()=>{}}).reduce(f,{})[o[0]](o)}function gS(o,n,T,t){let S,f,y,A=t.raw?new Array(n.length):{};for(let M=0;M<n.length;M++)S=o[T++],f=n[M],y=S===110?null:S===117?void 0:f.parser===void 0?o.toString("utf8",T+4,T+=4+o.readUInt32BE(T)):f.parser.array===!0?f.parser(o.toString("utf8",T+5,T+=4+o.readUInt32BE(T))):f.parser(o.toString("utf8",T+4,T+=4+o.readUInt32BE(T))),t.raw?A[M]=t.raw===!0?y:t.value.from?t.value.from(y,f):y:A[f.name]=t.value.from?t.value.from(y,f):y;return{i:T,row:t.row.from?t.row.from(A):A}}function H0(o){let n=o.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!n)throw new Error("Malformed subscribe pattern: "+o);let[,T,t,S]=n;return(T||"*")+(t?":"+(t.indexOf(".")===-1?"public."+t:t):"")+(S?"="+S:"")}import Xk from"stream";function Dy(o,n,T=393216){return new Promise(async(t,S)=>{await o.begin(async(f)=>{let y;!n&&([{oid:n}]=await f`select lo_creat(-1) as oid`);let[{fd:A}]=await f`select lo_open(${n}, ${T}) as fd`,M={writable:$,readable:F,close:()=>f`select lo_close(${A})`.then(y),tell:()=>f`select lo_tell64(${A})`,read:(W)=>f`select loread(${A}, ${W}) as data`,write:(W)=>f`select lowrite(${A}, ${W})`,truncate:(W)=>f`select lo_truncate64(${A}, ${W})`,seek:(W,O=0)=>f`select lo_lseek64(${A}, ${W}, ${O})`,size:()=>f`
|
|
14
21
|
select
|
|
15
22
|
lo_lseek64(${A}, location, 0) as position,
|
|
16
23
|
seek.size
|
|
@@ -20,10 +27,10 @@ var QJ=Object.create;var{getPrototypeOf:DJ,defineProperty:nf,getOwnPropertyNames
|
|
|
20
27
|
tell.location
|
|
21
28
|
from (select lo_tell64($1) as location) tell
|
|
22
29
|
) seek
|
|
23
|
-
`};return T(M),new Promise(async(W)=>y=W);async function F({highWaterMark:W=16384,start:O=0,end:E=1/0}={}){let Q=E-O;return O&&await M.seek(O),new K$.Readable({highWaterMark:W,async read(z){let G=z>Q?z-Q:z;Q-=z;let[{data:V}]=await M.read(G);if(this.push(V),V.length<z)this.push(null)}})}async function k({highWaterMark:W=16384,start:O=0}={}){return O&&await M.seek(O),new K$.Writable({highWaterMark:W,write(E,Q,z){M.write(E).then(()=>z(),z)}})}}).catch(S)})}Object.assign(pS,{PostgresError:gt,toPascal:_t,pascal:wy,toCamel:Ot,camel:_y,toKebab:wt,kebab:Ky,fromPascal:jT,fromCamel:IT,fromKebab:bT,BigInt:{to:20,from:[20],parse:(o)=>BigInt(o),serialize:(o)=>o.toString()}});var ut=pS;function pS(o,n){let t=D0(o,n),T=t.no_subscribe||zy(pS,{...t}),S=!1,f=Rn(),y=Rn(),A=Rn(),M=Rn(),F=Rn(),k=Rn(),W=Rn(),O=Rn(),E={connecting:y,reserved:A,closed:M,ended:F,open:k,busy:W,full:O},Q=[...Array(t.max)].map(()=>Gy(t,E,{onopen:_o,onend:no,onclose:Mn})),z=G(p);return Object.assign(z,{get parameters(){return t.parameters},largeObject:Hy.bind(null,z),subscribe:T,CLOSE:lt,END:lt,PostgresError:gt,options:t,reserve:c,listen:V,begin:P,close:j,end:v}),z;function G(H){return H.debug=t.debug,Object.entries(t.types).reduce((So,[wo,Co])=>{return So[wo]=(mo)=>new cn(mo,Co.to),So},i),Object.assign(fo,{types:i,typed:i,unsafe:Ro,notify:x,array:U,json:K,file:Io}),fo;function i(So,wo){return new cn(So,wo)}function fo(So,...wo){return So&&Array.isArray(So.raw)?new En(So,wo,H,w):typeof So==="string"&&!wo.length?new NT(t.transform.column.to?t.transform.column.to(So):So):new NS(So,wo)}function Ro(So,wo=[],Co={}){return arguments.length===2&&!Array.isArray(wo)&&(Co=wo,wo=[]),new En([So],wo,H,w,{prepare:!1,...Co,simple:"simple"in Co?Co.simple:wo.length===0})}function Io(So,wo=[],Co={}){return arguments.length===2&&!Array.isArray(wo)&&(Co=wo,wo=[]),new En([],wo,(Eo)=>{Q0.readFile(So,"utf8",(vo,Ko)=>{if(vo)return Eo.reject(vo);Eo.strings=[Ko],H(Eo)})},w,{...Co,simple:"simple"in Co?Co.simple:wo.length===0})}}async function V(H,i,fo){let Ro={fn:i,onlisten:fo},Io=V.sql||(V.sql=pS({...t,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(V.channels).forEach(([Eo,{listeners:vo}])=>{delete V.channels[Eo],Promise.all(vo.map((Ko)=>V(Eo,Ko.fn,Ko.onlisten).catch(()=>{})))})},onnotify(Eo,vo){Eo in V.channels&&V.channels[Eo].listeners.forEach((Ko)=>Ko.fn(vo))}})),So=V.channels||(V.channels={});if(H in So){So[H].listeners.push(Ro);let Eo=await So[H].result;return Ro.onlisten&&Ro.onlisten(),{state:Eo.state,unlisten:mo}}So[H]={result:Io`listen ${Io.unsafe('"'+H.replace(/"/g,'""')+'"')}`,listeners:[Ro]};let Co=await So[H].result;return Ro.onlisten&&Ro.onlisten(),{state:Co.state,unlisten:mo};async function mo(){if(H in So===!1)return;if(So[H].listeners=So[H].listeners.filter((Eo)=>Eo!==Ro),So[H].listeners.length)return;return delete So[H],Io`unlisten ${Io.unsafe('"'+H.replace(/"/g,'""')+'"')}`}}async function x(H,i){return await z`select pg_notify(${H}, ${""+i})`}async function c(){let H=Rn(),i=k.length?k.shift():await new Promise((Io)=>{f.push({reserve:Io}),M.length&&oo(M.shift())});Y(i,A),i.reserved=()=>H.length?i.execute(H.shift()):Y(i,A),i.reserved.release=!0;let fo=G(Ro);return fo.release=()=>{i.reserved=null,_o(i)},fo;function Ro(Io){i.queue===O?H.push(Io):i.execute(Io)||Y(i,O)}}async function P(H,i){!i&&(i=H,H="");let fo=Rn(),Ro=0,Io,So=null;try{return await z.unsafe("begin "+H.replace(/[^a-z ]/ig,""),[],{onexecute:Co}).execute(),await Promise.race([wo(Io,i),new Promise((mo,Eo)=>Io.onclose=Eo)])}catch(mo){throw mo}async function wo(mo,Eo,vo){let Ko=G(jo);Ko.savepoint=ln,Ko.prepare=(Yo)=>So=Yo.replace(/[^a-z0-9$-_. ]/gi);let Yn,po;vo&&await Ko`savepoint ${Ko(vo)}`;try{if(po=await new Promise((Yo,Gn)=>{let Ln=Eo(Ko);Promise.resolve(Array.isArray(Ln)?Promise.all(Ln):Ln).then(Yo,Gn)}),Yn)throw Yn}catch(Yo){throw await(vo?Ko`rollback to ${Ko(vo)}`:Ko`rollback`),Yo instanceof gt&&Yo.code==="25P02"&&Yn||Yo}if(!vo)So?await Ko`prepare transaction '${Ko.unsafe(So)}'`:await Ko`commit`;return po;function ln(Yo,Gn){if(Yo&&Array.isArray(Yo.raw))return ln((Ln)=>Ln.apply(Ln,arguments));return arguments.length===1&&(Gn=Yo,Yo=null),wo(mo,Gn,"s"+Ro+++(Yo?"_"+Yo:""))}function jo(Yo){Yo.catch((Gn)=>Yn||(Yn=Gn)),mo.queue===O?fo.push(Yo):mo.execute(Yo)||Y(mo,O)}}function Co(mo){Io=mo,Y(mo,A),mo.reserved=()=>fo.length?mo.execute(fo.shift()):Y(mo,A)}}function Y(H,i){return H.queue.remove(H),i.push(H),H.queue=i,i===k?H.idleTimer.start():H.idleTimer.cancel(),H}function K(H){return new cn(H,3802)}function U(H,i){if(!Array.isArray(H))return U(Array.from(arguments));return new cn(H,i||(H.length?jS(H)||25:0),t.shared.typeArrayMap)}function p(H){if(S)return H.reject(Lo.connection("CONNECTION_ENDED",t,t));if(k.length)return b(k.shift(),H);if(M.length)return oo(M.shift(),H);W.length?b(W.shift(),H):f.push(H)}function b(H,i){return H.execute(i)?Y(H,W):Y(H,O)}function w(H){return new Promise((i,fo)=>{H.state?H.active?Gy(t).cancel(H.state,i,fo):H.cancelled={resolve:i,reject:fo}:(f.remove(H),H.cancelled=!0,H.reject(Lo.generic("57014","canceling statement due to user request")),i())})}async function v({timeout:H=null}={}){if(S)return S;await 1;let i;return S=Promise.race([new Promise((fo)=>H!==null&&(i=setTimeout(a,H*1000,fo))),Promise.all(Q.map((fo)=>fo.end()).concat(V.sql?V.sql.end({timeout:0}):[],T.sql?T.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(i))}async function j(){await Promise.all(Q.map((H)=>H.end()))}async function a(H){await Promise.all(Q.map((i)=>i.terminate()));while(f.length)f.shift().reject(Lo.connection("CONNECTION_DESTROYED",t));H()}function oo(H,i){return Y(H,y),H.connect(i),H}function no(H){Y(H,F)}function _o(H){if(f.length===0)return Y(H,k);let i=Math.ceil(f.length/(y.length+1)),fo=!0;while(fo&&f.length&&i-- >0){let Ro=f.shift();if(Ro.reserve)return Ro.reserve(H);fo=H.execute(Ro)}fo?Y(H,W):Y(H,O)}function Mn(H,i){Y(H,M),H.reserved=null,H.onclose&&(H.onclose(i),H.onclose=null),t.onclose&&t.onclose(H.id),f.length&&oo(H,f.shift())}}function D0(o,n){if(o&&o.shared)return o;let t=process.env,T=(!o||typeof o==="string"?n:o)||{},{url:S,multihost:f}=C0(o),y=[...S.searchParams].reduce((O,[E,Q])=>(O[E]=Q,O),{}),A=T.hostname||T.host||f||S.hostname||t.PGHOST||"localhost",M=T.port||S.port||t.PGPORT||5432,F=T.user||T.username||S.username||t.PGUSERNAME||t.PGUSER||L0();T.no_prepare&&(T.prepare=!1),y.sslmode&&(y.ssl=y.sslmode,delete y.sslmode),"timeout"in T&&(console.log("The timeout option is deprecated, use idle_timeout instead"),T.idle_timeout=T.timeout),y.sslrootcert==="system"&&(y.ssl="verify-full");let k=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],W={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:r0,max_pipeline:100,backoff:V0,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(A)?A:A.split(",").map((O)=>O.split(":")[0]),port:Array.isArray(M)?M:A.split(",").map((O)=>parseInt(O.split(":")[1]||M)),path:T.path||A.indexOf("/")>-1&&A+"/.s.PGSQL."+M,database:T.database||T.db||(S.pathname||"").slice(1)||t.PGDATABASE||F,user:F,pass:T.pass||T.password||S.password||t.PGPASSWORD||"",...Object.entries(W).reduce((O,[E,Q])=>{let z=E in T?T[E]:(E in y)?y[E]==="disable"||y[E]==="false"?!1:y[E]:t["PG"+E.toUpperCase()]||Q;return O[E]=typeof z==="string"&&k.includes(E)?+z:z,O},{}),connection:{application_name:"postgres.js",...T.connection,...Object.entries(y).reduce((O,[E,Q])=>((E in W)||(O[E]=Q),O),{})},types:T.types||{},target_session_attrs:U0(T,S,t),onnotice:T.onnotice,onnotify:T.onnotify,onclose:T.onclose,onparameter:T.onparameter,socket:T.socket,transform:B0(T.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...A$(T.types)}}function U0(o,n,t){let T=o.target_session_attrs||n.searchParams.get("target_session_attrs")||t.PGTARGETSESSIONATTRS;if(!T||["read-write","read-only","primary","standby","prefer-standby"].includes(T))return T;throw new Error("target_session_attrs "+T+" is not supported")}function V0(o){return(0.5+Math.random()/2)*Math.min(3**o/100,20)}function r0(){return 60*(30+Math.random()*30)}function B0(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 C0(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));let 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 L0(){try{return m0.userInfo().username}catch(o){return process.env.USERNAME||"runner"}}class qS extends so{constructor(o,n,t,T){super();this.session=n,this.dialect=t,this.config={table:o,withList:T}}static[J]="PgDelete";config;where(o){return this.config.where=o,this}returning(o=this.config.table[L.Symbol.Columns]){return this.config.returning=wn(o),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{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 ZS{constructor(o,n,t,T){this.table=o,this.session=n,this.dialect=t,this.withList=T}static[J]="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");let n=o.map((t)=>{let T={},S=this.table[L.Symbol.Columns];for(let f of Object.keys(t)){let y=t[f];T[f]=X(y,h)?y:new kn(y,S[f])}return T});return new X$(this.table,n,this.session,this.dialect,this.withList)}}class X$ extends so{constructor(o,n,t,T,S){super();this.session=t,this.dialect=T,this.config={table:o,values:n,withList:S}}static[J]="PgInsert";config;returning(o=this.config.table[L.Symbol.Columns]){return this.config.returning=wn(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((T)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(T))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(o.target));let 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.');let n=o.where?R` where ${o.where}`:void 0,t=o.targetWhere?R` where ${o.targetWhere}`:void 0,T=o.setWhere?R` where ${o.setWhere}`:void 0,S=this.dialect.buildUpdateSet(this.config.table,_S(this.config.table,o.set)),f="";return f=Array.isArray(o.target)?o.target.map((y)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(y))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(o.target)),this.config.onConflict=R`(${R.raw(f)})${t} do update set ${S}${n}${T}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{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 I0(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((t)=>t.toLowerCase()).join("_")}function j0(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((t,T,S)=>{let f=S===0?T.toLowerCase():`${T[0].toUpperCase()}${T.slice(1)}`;return t+f},"")}function b0(o){return o}class my{static[J]="CasingCache";cache={};cachedTables={};convert;constructor(o){this.convert=o==="snake_case"?I0:o==="camelCase"?j0:b0}getColumnCasing(o){if(!o.keyAsName)return o.name;let n=o.table[L.Symbol.Schema]??"public",t=o.table[L.Symbol.OriginalName],T=`${n}.${t}.${o.name}`;if(!this.cache[T])this.cacheTable(o.table);return this.cache[T]}cacheTable(o){let n=o[L.Symbol.Schema]??"public",t=o[L.Symbol.OriginalName],T=`${n}.${t}`;if(!this.cachedTables[T]){for(let S of Object.values(o[L.Symbol.Columns])){let f=`${T}.${S.name}`;this.cache[f]=this.convert(S.name)}this.cachedTables[T]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class cT extends fn{static[J]="PgViewBase"}class Xt{static[J]="PgDialect";casing;constructor(o){this.casing=new my(o?.casing)}async migrate(o,n,t){let T=typeof t==="string"?"__drizzle_migrations":t.migrationsTable??"__drizzle_migrations",S=typeof t==="string"?"drizzle":t.migrationsSchema??"drizzle",f=R`
|
|
24
|
-
CREATE TABLE IF NOT EXISTS ${R.identifier(S)}.${R.identifier(
|
|
30
|
+
`};return t(M),new Promise(async(W)=>y=W);async function F({highWaterMark:W=16384,start:O=0,end:G=1/0}={}){let D=G-O;return O&&await M.seek(O),new Xk.Readable({highWaterMark:W,async read(z){let Y=z>D?z-D:z;D-=z;let[{data:B}]=await M.read(Y);if(this.push(B),B.length<z)this.push(null)}})}async function $({highWaterMark:W=16384,start:O=0}={}){return O&&await M.seek(O),new Xk.Writable({highWaterMark:W,write(G,D,z){M.write(G).then(()=>z(),z)}})}}).catch(S)})}Object.assign(lS,{PostgresError:dT,toPascal:wT,pascal:Ey,toCamel:_T,camel:Xy,toKebab:KT,kebab:Yy,fromPascal:ht,fromCamel:Nt,fromKebab:bt,BigInt:{to:20,from:[20],parse:(o)=>BigInt(o),serialize:(o)=>o.toString()}});var aT=lS;function lS(o,n){let T=D0(o,n),t=T.no_subscribe||Qy(lS,{...T}),S=!1,f=Rn(),y=Rn(),A=Rn(),M=Rn(),F=Rn(),$=Rn(),W=Rn(),O=Rn(),G={connecting:y,reserved:A,closed:M,ended:F,open:$,busy:W,full:O},D=[...Array(T.max)].map(()=>my(T,G,{onopen:Sn,onend:Oo,onclose:cn})),z=Y(c);return Object.assign(z,{get parameters(){return T.parameters},largeObject:Dy.bind(null,z),subscribe:t,CLOSE:eT,END:eT,PostgresError:dT,options:T,reserve:x,listen:B,begin:a,close:N,end:i}),z;function Y(H){return H.debug=T.debug,Object.entries(T.types).reduce((To,[_o,Co])=>{return To[_o]=(mo)=>new bn(mo,Co.to),To},Z),Object.assign(Fo,{types:Z,typed:Z,unsafe:zo,notify:v,array:m,json:K,file:Io}),Fo;function Z(To,_o){return new bn(To,_o)}function Fo(To,..._o){return To&&Array.isArray(To.raw)?new Xn(To,_o,H,w):typeof To==="string"&&!_o.length?new ct(T.transform.column.to?T.transform.column.to(To):To):new vS(To,_o)}function zo(To,_o=[],Co={}){return arguments.length===2&&!Array.isArray(_o)&&(Co=_o,_o=[]),new Xn([To],_o,H,w,{prepare:!1,...Co,simple:"simple"in Co?Co.simple:_o.length===0})}function Io(To,_o=[],Co={}){return arguments.length===2&&!Array.isArray(_o)&&(Co=_o,_o=[]),new Xn([],_o,(Ko)=>{Q0.readFile(To,"utf8",(po,wo)=>{if(po)return Ko.reject(po);Ko.strings=[wo],H(Ko)})},w,{...Co,simple:"simple"in Co?Co.simple:_o.length===0})}}async function B(H,Z,Fo){let zo={fn:Z,onlisten:Fo},Io=B.sql||(B.sql=lS({...T,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(B.channels).forEach(([Ko,{listeners:po}])=>{delete B.channels[Ko],Promise.all(po.map((wo)=>B(Ko,wo.fn,wo.onlisten).catch(()=>{})))})},onnotify(Ko,po){Ko in B.channels&&B.channels[Ko].listeners.forEach((wo)=>wo.fn(po))}})),To=B.channels||(B.channels={});if(H in To){To[H].listeners.push(zo);let Ko=await To[H].result;return zo.onlisten&&zo.onlisten(),{state:Ko.state,unlisten:mo}}To[H]={result:Io`listen ${Io.unsafe('"'+H.replace(/"/g,'""')+'"')}`,listeners:[zo]};let Co=await To[H].result;return zo.onlisten&&zo.onlisten(),{state:Co.state,unlisten:mo};async function mo(){if(H in To===!1)return;if(To[H].listeners=To[H].listeners.filter((Ko)=>Ko!==zo),To[H].listeners.length)return;return delete To[H],Io`unlisten ${Io.unsafe('"'+H.replace(/"/g,'""')+'"')}`}}async function v(H,Z){return await z`select pg_notify(${H}, ${""+Z})`}async function x(){let H=Rn(),Z=$.length?$.shift():await new Promise((Io)=>{f.push({reserve:Io}),M.length&&ko(M.shift())});E(Z,A),Z.reserved=()=>H.length?Z.execute(H.shift()):E(Z,A),Z.reserved.release=!0;let Fo=Y(zo);return Fo.release=()=>{Z.reserved=null,Sn(Z)},Fo;function zo(Io){Z.queue===O?H.push(Io):Z.execute(Io)||E(Z,O)}}async function a(H,Z){!Z&&(Z=H,H="");let Fo=Rn(),zo=0,Io,To=null;try{return await z.unsafe("begin "+H.replace(/[^a-z ]/ig,""),[],{onexecute:Co}).execute(),await Promise.race([_o(Io,Z),new Promise((mo,Ko)=>Io.onclose=Ko)])}catch(mo){throw mo}async function _o(mo,Ko,po){let wo=Y(ro);wo.savepoint=en,wo.prepare=(Xo)=>To=Xo.replace(/[^a-z0-9$-_. ]/gi);let En,qo;po&&await wo`savepoint ${wo(po)}`;try{if(qo=await new Promise((Xo,Yn)=>{let Ln=Ko(wo);Promise.resolve(Array.isArray(Ln)?Promise.all(Ln):Ln).then(Xo,Yn)}),En)throw En}catch(Xo){throw await(po?wo`rollback to ${wo(po)}`:wo`rollback`),Xo instanceof dT&&Xo.code==="25P02"&&En||Xo}if(!po)To?await wo`prepare transaction '${wo.unsafe(To)}'`:await wo`commit`;return qo;function en(Xo,Yn){if(Xo&&Array.isArray(Xo.raw))return en((Ln)=>Ln.apply(Ln,arguments));return arguments.length===1&&(Yn=Xo,Xo=null),_o(mo,Yn,"s"+zo+++(Xo?"_"+Xo:""))}function ro(Xo){Xo.catch((Yn)=>En||(En=Yn)),mo.queue===O?Fo.push(Xo):mo.execute(Xo)||E(mo,O)}}function Co(mo){Io=mo,E(mo,A),mo.reserved=()=>Fo.length?mo.execute(Fo.shift()):E(mo,A)}}function E(H,Z){return H.queue.remove(H),Z.push(H),H.queue=Z,Z===$?H.idleTimer.start():H.idleTimer.cancel(),H}function K(H){return new bn(H,3802)}function m(H,Z){if(!Array.isArray(H))return m(Array.from(arguments));return new bn(H,Z||(H.length?xS(H)||25:0),T.shared.typeArrayMap)}function c(H){if(S)return H.reject(Lo.connection("CONNECTION_ENDED",T,T));if($.length)return b($.shift(),H);if(M.length)return ko(M.shift(),H);W.length?b(W.shift(),H):f.push(H)}function b(H,Z){return H.execute(Z)?E(H,W):E(H,O)}function w(H){return new Promise((Z,Fo)=>{H.state?H.active?my(T).cancel(H.state,Z,Fo):H.cancelled={resolve:Z,reject:Fo}:(f.remove(H),H.cancelled=!0,H.reject(Lo.generic("57014","canceling statement due to user request")),Z())})}async function i({timeout:H=null}={}){if(S)return S;await 1;let Z;return S=Promise.race([new Promise((Fo)=>H!==null&&(Z=setTimeout(q,H*1000,Fo))),Promise.all(D.map((Fo)=>Fo.end()).concat(B.sql?B.sql.end({timeout:0}):[],t.sql?t.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(Z))}async function N(){await Promise.all(D.map((H)=>H.end()))}async function q(H){await Promise.all(D.map((Z)=>Z.terminate()));while(f.length)f.shift().reject(Lo.connection("CONNECTION_DESTROYED",T));H()}function ko(H,Z){return E(H,y),H.connect(Z),H}function Oo(H){E(H,F)}function Sn(H){if(f.length===0)return E(H,$);let Z=Math.ceil(f.length/(y.length+1)),Fo=!0;while(Fo&&f.length&&Z-- >0){let zo=f.shift();if(zo.reserve)return zo.reserve(H);Fo=H.execute(zo)}Fo?E(H,W):E(H,O)}function cn(H,Z){E(H,M),H.reserved=null,H.onclose&&(H.onclose(Z),H.onclose=null),T.onclose&&T.onclose(H.id),f.length&&ko(H,f.shift())}}function D0(o,n){if(o&&o.shared)return o;let T=process.env,t=(!o||typeof o==="string"?n:o)||{},{url:S,multihost:f}=L0(o),y=[...S.searchParams].reduce((O,[G,D])=>(O[G]=D,O),{}),A=t.hostname||t.host||f||S.hostname||T.PGHOST||"localhost",M=t.port||S.port||T.PGPORT||5432,F=t.user||t.username||S.username||T.PGUSERNAME||T.PGUSER||I0();t.no_prepare&&(t.prepare=!1),y.sslmode&&(y.ssl=y.sslmode,delete y.sslmode),"timeout"in t&&(console.log("The timeout option is deprecated, use idle_timeout instead"),t.idle_timeout=t.timeout),y.sslrootcert==="system"&&(y.ssl="verify-full");let $=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],W={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:B0,max_pipeline:100,backoff:V0,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(A)?A:A.split(",").map((O)=>O.split(":")[0]),port:Array.isArray(M)?M:A.split(",").map((O)=>parseInt(O.split(":")[1]||M)),path:t.path||A.indexOf("/")>-1&&A+"/.s.PGSQL."+M,database:t.database||t.db||(S.pathname||"").slice(1)||T.PGDATABASE||F,user:F,pass:t.pass||t.password||S.password||T.PGPASSWORD||"",...Object.entries(W).reduce((O,[G,D])=>{let z=G in t?t[G]:(G in y)?y[G]==="disable"||y[G]==="false"?!1:y[G]:T["PG"+G.toUpperCase()]||D;return O[G]=typeof z==="string"&&$.includes(G)?+z:z,O},{}),connection:{application_name:"postgres.js",...t.connection,...Object.entries(y).reduce((O,[G,D])=>((G in W)||(O[G]=D),O),{})},types:t.types||{},target_session_attrs:U0(t,S,T),onnotice:t.onnotice,onnotify:t.onnotify,onclose:t.onclose,onparameter:t.onparameter,socket:t.socket,transform:C0(t.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...Mk(t.types)}}function U0(o,n,T){let t=o.target_session_attrs||n.searchParams.get("target_session_attrs")||T.PGTARGETSESSIONATTRS;if(!t||["read-write","read-only","primary","standby","prefer-standby"].includes(t))return t;throw new Error("target_session_attrs "+t+" is not supported")}function V0(o){return(0.5+Math.random()/2)*Math.min(3**o/100,20)}function B0(){return 60*(30+Math.random()*30)}function C0(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 L0(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));let 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 I0(){try{return m0.userInfo().username}catch(o){return process.env.USERNAME||"runner"}}class eS extends on{constructor(o,n,T,t){super();this.session=n,this.dialect=T,this.config={table:o,withList:t}}static[J]="PgDelete";config;where(o){return this.config.where=o,this}returning(o=this.config.table[L.Symbol.Columns]){return this.config.returning=wn(o),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{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)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return Wo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o,this.authToken)})};$dynamic(){return this}}function r0(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((T)=>T.toLowerCase()).join("_")}function j0(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((T,t,S)=>{let f=S===0?t.toLowerCase():`${t[0].toUpperCase()}${t.slice(1)}`;return T+f},"")}function N0(o){return o}class Uy{static[J]="CasingCache";cache={};cachedTables={};convert;constructor(o){this.convert=o==="snake_case"?r0:o==="camelCase"?j0:N0}getColumnCasing(o){if(!o.keyAsName)return o.name;let n=o.table[L.Symbol.Schema]??"public",T=o.table[L.Symbol.OriginalName],t=`${n}.${T}.${o.name}`;if(!this.cache[t])this.cacheTable(o.table);return this.cache[t]}cacheTable(o){let n=o[L.Symbol.Schema]??"public",T=o[L.Symbol.OriginalName],t=`${n}.${T}`;if(!this.cachedTables[t]){for(let S of Object.values(o[L.Symbol.Columns])){let f=`${t}.${S.name}`;this.cache[f]=this.convert(S.name)}this.cachedTables[t]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class it extends An{static[J]="PgViewBase"}class ET{static[J]="PgDialect";casing;constructor(o){this.casing=new Uy(o?.casing)}async migrate(o,n,T){let t=typeof T==="string"?"__drizzle_migrations":T.migrationsTable??"__drizzle_migrations",S=typeof T==="string"?"drizzle":T.migrationsSchema??"drizzle",f=R`
|
|
31
|
+
CREATE TABLE IF NOT EXISTS ${R.identifier(S)}.${R.identifier(t)} (
|
|
25
32
|
id SERIAL PRIMARY KEY,
|
|
26
33
|
hash text NOT NULL,
|
|
27
34
|
created_at bigint
|
|
28
35
|
)
|
|
29
|
-
`;await n.execute(R`CREATE SCHEMA IF NOT EXISTS ${R.identifier(S)}`),await n.execute(f);let A=(await n.all(R`select id, hash, created_at from ${R.identifier(S)}.${R.identifier(T)} order by created_at desc limit 1`))[0];await n.transaction(async(M)=>{for await(let F of o)if(!A||Number(A.created_at)<F.folderMillis){for(let k of F.sql)await M.execute(R.raw(k));await M.execute(R`insert into ${R.identifier(S)}.${R.identifier(T)} ("hash", "created_at") values(${F.hash}, ${F.folderMillis})`)}})}escapeName(o){return`"${o}"`}escapeParam(o){return`\$${o+1}`}escapeString(o){return`'${o.replace(/'/g,"''")}'`}buildWithCTE(o){if(!o?.length)return;let n=[R`with `];for(let[t,T]of o.entries())if(n.push(R`${R.identifier(T._.alias)} as (${T._.sql})`),t<o.length-1)n.push(R`, `);return n.push(R` `),R.join(n)}buildDeleteQuery({table:o,where:n,returning:t,withList:T}){let S=this.buildWithCTE(T),f=t?R` returning ${this.buildSelection(t,{isSingleTable:!0})}`:void 0,y=n?R` where ${n}`:void 0;return R`${S}delete from ${o}${y}${f}`}buildUpdateSet(o,n){let t=o[L.Symbol.Columns],T=Object.keys(t).filter((f)=>n[f]!==void 0||t[f]?.onUpdateFn!==void 0),S=T.length;return R.join(T.flatMap((f,y)=>{let A=t[f],M=n[f]??R.param(A.onUpdateFn(),A),F=R`${R.identifier(this.casing.getColumnCasing(A))} = ${M}`;if(y<S-1)return[F,R.raw(", ")];return[F]}))}buildUpdateQuery({table:o,set:n,where:t,returning:T,withList:S}){let f=this.buildWithCTE(S),y=this.buildUpdateSet(o,n),A=T?R` returning ${this.buildSelection(T,{isSingleTable:!0})}`:void 0,M=t?R` where ${t}`:void 0;return R`${f}update ${o} set ${y}${M}${A}`}buildSelection(o,{isSingleTable:n=!1}={}){let t=o.length,T=o.flatMap(({field:S},f)=>{let y=[];if(X(S,h.Aliased)&&S.isSelectionField)y.push(R.identifier(S.fieldAlias));else if(X(S,h.Aliased)||X(S,h)){let A=X(S,h.Aliased)?S.sql:S;if(n)y.push(new h(A.queryChunks.map((M)=>{if(X(M,r))return R.identifier(this.casing.getColumnCasing(M));return M})));else y.push(A);if(X(S,h.Aliased))y.push(R` as ${R.identifier(S.fieldAlias)}`)}else if(X(S,Xo))if(n)y.push(R.identifier(this.casing.getColumnCasing(S)));else y.push(S);if(f<t-1)y.push(R`, `);return y});return R.join(T)}buildSelectQuery({withList:o,fields:n,fieldsFlat:t,where:T,having:S,table:f,joins:y,orderBy:A,groupBy:M,limit:F,offset:k,lockingClause:W,distinct:O,setOperators:E}){let Q=t??wn(n);for(let oo of Q)if(X(oo.field,Xo)&&_n(oo.field.table)!==(X(f,xo)?f._.alias:X(f,cT)?f[Do].name:X(f,h)?void 0:_n(f))&&!((no)=>y?.some(({alias:_o})=>_o===(no[L.Symbol.IsAlias]?_n(no):no[L.Symbol.BaseName])))(oo.field.table)){let no=_n(oo.field.table);throw new Error(`Your "${oo.path.join("->")}" field references a column "${no}"."${oo.field.name}", but the table "${no}" is not part of the query! Did you forget to join it?`)}let z=!y||y.length===0,G=this.buildWithCTE(o),V;if(O)V=O===!0?R` distinct`:R` distinct on (${R.join(O.on,R`, `)})`;let x=this.buildSelection(Q,{isSingleTable:z}),c=(()=>{if(X(f,L)&&f[L.Symbol.OriginalName]!==f[L.Symbol.Name]){let oo=R`${R.identifier(f[L.Symbol.OriginalName])}`;if(f[L.Symbol.Schema])oo=R`${R.identifier(f[L.Symbol.Schema])}.${oo}`;return R`${oo} ${R.identifier(f[L.Symbol.Name])}`}return f})(),P=[];if(y)for(let[oo,no]of y.entries()){if(oo===0)P.push(R` `);let _o=no.table,Mn=no.lateral?R` lateral`:void 0;if(X(_o,Kn)){let H=_o[Kn.Symbol.Name],i=_o[Kn.Symbol.Schema],fo=_o[Kn.Symbol.OriginalName],Ro=H===fo?void 0:no.alias;P.push(R`${R.raw(no.joinType)} join${Mn} ${i?R`${R.identifier(i)}.`:void 0}${R.identifier(fo)}${Ro&&R` ${R.identifier(Ro)}`} on ${no.on}`)}else if(X(_o,fn)){let H=_o[Do].name,i=_o[Do].schema,fo=_o[Do].originalName,Ro=H===fo?void 0:no.alias;P.push(R`${R.raw(no.joinType)} join${Mn} ${i?R`${R.identifier(i)}.`:void 0}${R.identifier(fo)}${Ro&&R` ${R.identifier(Ro)}`} on ${no.on}`)}else P.push(R`${R.raw(no.joinType)} join${Mn} ${_o} on ${no.on}`);if(oo<y.length-1)P.push(R` `)}let Y=R.join(P),K=T?R` where ${T}`:void 0,U=S?R` having ${S}`:void 0,p;if(A&&A.length>0)p=R` order by ${R.join(A,R`, `)}`;let b;if(M&&M.length>0)b=R` group by ${R.join(M,R`, `)}`;let w=typeof F==="object"||typeof F==="number"&&F>=0?R` limit ${F}`:void 0,v=k?R` offset ${k}`:void 0,j=R.empty();if(W){let oo=R` for ${R.raw(W.strength)}`;if(W.config.of)oo.append(R` of ${R.join(Array.isArray(W.config.of)?W.config.of:[W.config.of],R`, `)}`);if(W.config.noWait)oo.append(R` no wait`);else if(W.config.skipLocked)oo.append(R` skip locked`);j.append(oo)}let a=R`${G}select${V} ${x} from ${c}${Y}${K}${b}${U}${p}${w}${v}${j}`;if(E.length>0)return this.buildSetOperations(a,E);return a}buildSetOperations(o,n){let[t,...T]=n;if(!t)throw new Error("Cannot pass undefined values to any set operator");if(T.length===0)return this.buildSetOperationQuery({leftSelect:o,setOperator:t});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:o,setOperator:t}),T)}buildSetOperationQuery({leftSelect:o,setOperator:{type:n,isAll:t,rightSelect:T,limit:S,orderBy:f,offset:y}}){let A=R`(${o.getSQL()}) `,M=R`(${T.getSQL()})`,F;if(f&&f.length>0){let E=[];for(let Q of f)if(X(Q,r))E.push(R.identifier(Q.name));else if(X(Q,h)){for(let z=0;z<Q.queryChunks.length;z++){let G=Q.queryChunks[z];if(X(G,r))Q.queryChunks[z]=R.identifier(G.name)}E.push(R`${Q}`)}else E.push(R`${Q}`);F=R` order by ${R.join(E,R`, `)} `}let k=typeof S==="object"||typeof S==="number"&&S>=0?R` limit ${S}`:void 0,W=R.raw(`${n} ${t?"all ":""}`),O=y?R` offset ${y}`:void 0;return R`${A}${W}${M}${F}${k}${O}`}buildInsertQuery({table:o,values:n,onConflict:t,returning:T,withList:S}){let f=[],y=o[L.Symbol.Columns],A=Object.entries(y).filter(([E,Q])=>!Q.shouldDisableInsert()),M=A.map(([,E])=>R.identifier(this.casing.getColumnCasing(E)));for(let[E,Q]of n.entries()){let z=[];for(let[G,V]of A){let x=Q[G];if(x===void 0||X(x,kn)&&x.value===void 0)if(V.defaultFn!==void 0){let c=V.defaultFn(),P=X(c,h)?c:R.param(c,V);z.push(P)}else if(!V.default&&V.onUpdateFn!==void 0){let c=V.onUpdateFn(),P=X(c,h)?c:R.param(c,V);z.push(P)}else z.push(R`default`);else z.push(x)}if(f.push(z),E<n.length-1)f.push(R`, `)}let F=this.buildWithCTE(S),k=R.join(f),W=T?R` returning ${this.buildSelection(T,{isSingleTable:!0})}`:void 0,O=t?R` on conflict ${t}`:void 0;return R`${F}insert into ${o} ${M} values ${k}${O}${W}`}buildRefreshMaterializedViewQuery({view:o,concurrently:n,withNoData:t}){let T=n?R` concurrently`:void 0,S=t?R` with no data`:void 0;return R`refresh materialized view${T} ${o}${S}`}prepareTyping(o){if(X(o,YS)||X(o,ES))return"json";else if(X(o,GS))return"decimal";else if(X(o,zS))return"time";else if(X(o,HS)||X(o,mS))return"timestamp";else if(X(o,wS)||X(o,KS))return"date";else if(X(o,QS))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:T,tableConfig:S,queryConfig:f,tableAlias:y,nestedQueryRelation:A,joinOn:M}){let F=[],k,W,O=[],E,Q=[];if(f===!0)F=Object.entries(S.columns).map(([V,x])=>({dbKey:x.name,tsKey:V,field:bn(x,y),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let G=Object.fromEntries(Object.entries(S.columns).map(([K,U])=>[K,bn(U,y)]));if(f.where){let K=typeof f.where==="function"?f.where(G,Ck()):f.where;E=K&&KT(K,y)}let V=[],x=[];if(f.columns){let K=!1;for(let[U,p]of Object.entries(f.columns)){if(p===void 0)continue;if(U in S.columns){if(!K&&p===!0)K=!0;x.push(U)}}if(x.length>0)x=K?x.filter((U)=>f.columns?.[U]===!0):Object.keys(S.columns).filter((U)=>!x.includes(U))}else x=Object.keys(S.columns);for(let K of x){let U=S.columns[K];V.push({tsKey:K,value:U})}let c=[];if(f.with)c=Object.entries(f.with).filter((K)=>!!K[1]).map(([K,U])=>({tsKey:K,queryConfig:U,relation:S.relations[K]}));let P;if(f.extras){P=typeof f.extras==="function"?f.extras(G,{sql:R}):f.extras;for(let[K,U]of Object.entries(P))V.push({tsKey:K,value:Pf(U,y)})}for(let{tsKey:K,value:U}of V)F.push({dbKey:X(U,h.Aliased)?U.fieldAlias:S.columns[K].name,tsKey:K,field:X(U,Xo)?bn(U,y):U,relationTableTsKey:void 0,isJson:!1,selection:[]});let Y=typeof f.orderBy==="function"?f.orderBy(G,Lk()):f.orderBy??[];if(!Array.isArray(Y))Y=[Y];O=Y.map((K)=>{if(X(K,Xo))return bn(K,y);return KT(K,y)}),k=f.limit,W=f.offset;for(let{tsKey:K,queryConfig:U,relation:p}of c){let b=jk(n,t,p),w=kt(p.referencedTable),v=t[w],j=`${y}_${K}`,a=XT(...b.fields.map((_o,Mn)=>Ct(bn(b.references[Mn],j),bn(_o,y)))),oo=this.buildRelationalQueryWithoutPK({fullSchema:o,schema:n,tableNamesMap:t,table:o[v],tableConfig:n[v],queryConfig:X(p,tt)?U===!0?{limit:1}:{...U,limit:1}:U,tableAlias:j,joinOn:a,nestedQueryRelation:p}),no=R`${R.identifier(j)}.${R.identifier("data")}`.as(K);Q.push({on:R`true`,table:new xo(oo.sql,{},j),alias:j,joinType:"left",lateral:!0}),F.push({dbKey:K,tsKey:K,field:no,relationTableTsKey:v,isJson:!0,selection:oo.selection})}}if(F.length===0)throw new OS({message:`No fields selected for table "${S.tsName}" ("${y}")`});let z;if(E=XT(M,E),A){let G=R`json_build_array(${R.join(F.map(({field:c,tsKey:P,isJson:Y})=>Y?R`${R.identifier(`${y}_${P}`)}.${R.identifier("data")}`:X(c,h.Aliased)?c.sql:c),R`, `)})`;if(X(A,GT))G=R`coalesce(json_agg(${G}${O.length>0?R` order by ${R.join(O,R`, `)}`:void 0}), '[]'::json)`;let V=[{dbKey:"data",tsKey:"data",field:G.as("data"),isJson:!0,relationTableTsKey:S.tsName,selection:F}];if(k!==void 0||W!==void 0||O.length>0)z=this.buildSelectQuery({table:WS(T,y),fields:{},fieldsFlat:[{path:[],field:R.raw("*")}],where:E,limit:k,offset:W,orderBy:O,setOperators:[]}),E=void 0,k=void 0,W=void 0,O=[];else z=WS(T,y);z=this.buildSelectQuery({table:X(z,Kn)?z:new xo(z,{},y),fields:{},fieldsFlat:V.map(({field:c})=>({path:[],field:X(c,Xo)?bn(c,y):c})),joins:Q,where:E,limit:k,offset:W,orderBy:O,setOperators:[]})}else z=this.buildSelectQuery({table:WS(T,y),fields:{},fieldsFlat:F.map(({field:G})=>({path:[],field:X(G,Xo)?bn(G,y):G})),joins:Q,where:E,limit:k,offset:W,orderBy:O,setOperators:[]});return{tableTsKey:S.tsName,sql:z,selection:F}}}class An{static[J]="SelectionProxyHandler";config;constructor(o){this.config={...o}}get(o,n){if(n==="_")return{...o._,selectedFields:new Proxy(o._.selectedFields,this)};if(n===Do)return{...o[Do],selectedFields:new Proxy(o[Do].selectedFields,this)};if(typeof n==="symbol")return o[n];let T=(X(o,xo)?o._.selectedFields:X(o,fn)?o[Do].selectedFields:o)[n];if(X(T,h.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!T.isSelectionField)return T.sql;let S=T.clone();return S.isSelectionField=!0,S}if(X(T,h)){if(this.config.sqlBehavior==="sql")return T;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(T,Xo)){if(this.config.alias)return new Proxy(T,new Bt(new Proxy(T.table,new wT(this.config.alias,this.config.replaceOriginalName??!1))));return T}if(typeof T!=="object"||T===null)return T;return new Proxy(T,new An(this.config))}}class Qy{static[J]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class nn{static[J]="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){let n=!!this.fields,t;if(this.fields)t=this.fields;else if(X(o,xo))t=Object.fromEntries(Object.keys(o._.selectedFields).map((T)=>[T,o[T]]));else if(X(o,cT))t=o[Do].selectedFields;else if(X(o,h))t={};else t=bM(o);return new Dy({table:o,fields:t,isPartialSelect:n,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}}class E$ extends Qy{static[J]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:o,fields:n,isPartialSelect:t,session:T,dialect:S,withList:f,distinct:y}){super();this.config={withList:f,table:o,fields:{...n},distinct:y,setOperators:[]},this.isPartialSelect=t,this.session=T,this.dialect=S,this._={selectedFields:n},this.tableName=uf(o),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(o){return(n,t)=>{let T=this.tableName,S=uf(n);if(typeof S==="string"&&this.config.joins?.some((f)=>f.alias===S))throw new Error(`Alias "${S}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof T==="string")this.config.fields={[T]:this.config.fields};if(typeof S==="string"&&!X(n,h)){let f=X(n,xo)?n._.selectedFields:X(n,fn)?n[Do].selectedFields:n[L.Symbol.Columns];this.config.fields[S]=f}}if(typeof t==="function")t=t(new Proxy(this.config.fields,new An({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:t,table:n,joinType:o,alias:S}),typeof S==="string")switch(o){case"left":{this.joinsNotNullableMap[S]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([f])=>[f,!1])),this.joinsNotNullableMap[S]=!0;break}case"inner":{this.joinsNotNullableMap[S]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([f])=>[f,!1])),this.joinsNotNullableMap[S]=!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)=>{let T=typeof t==="function"?t(N0()):t;if(!df(this.getSelectedFields(),T.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:T}),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 An({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=o,this}having(o){if(typeof o==="function")o=o(new Proxy(this.config.fields,new An({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=o,this}groupBy(...o){if(typeof o[0]==="function"){let n=o[0](new Proxy(this.config.fields,new An({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"){let n=o[0](new Proxy(this.config.fields,new An({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{let 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(){let{typings:o,...n}=this.dialect.sqlToQuery(this.getSQL());return n}as(o){return new Proxy(new xo(this.getSQL(),this.config.fields,o),new An({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new An({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class Dy extends E${static[J]="PgSelect";_prepare(o){let{session:n,config:t,dialect:T,joinsNotNullableMap:S}=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",()=>{let f=wn(t.fields),y=n.prepareQuery(T.sqlToQuery(this.getSQL()),f,o,!0);return y.joinsNotNullableMap=S,y})}prepare(o){return this._prepare(o)}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o)})}}jM(Dy,[so]);function at(o,n){return(t,T,...S)=>{let f=[T,...S].map((y)=>({type:o,isAll:n,rightSelect:y}));for(let y of f)if(!df(t.getSelectedFields(),y.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(f)}}var N0=()=>({union:h0,unionAll:c0,intersect:x0,intersectAll:i0,except:v0,exceptAll:p0}),h0=at("union",!1),c0=at("union",!0),x0=at("intersect",!1),i0=at("intersect",!0),v0=at("except",!1),p0=at("except",!0);class Uy{static[J]="PgQueryBuilder";dialect;dialectConfig;constructor(o){this.dialect=X(o,Xt)?o:void 0,this.dialectConfig=X(o,Xt)?void 0:o}$with(o){let n=this;return{as(t){if(typeof t==="function")t=t(n);return new Proxy(new _T(t.getSQL(),t.getSelectedFields(),o,!0),new An({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}with(...o){let n=this;function t(f){return new nn({fields:f??void 0,session:void 0,dialect:n.getDialect(),withList:o})}function T(f){return new nn({fields:f??void 0,session:void 0,dialect:n.getDialect(),distinct:!0})}function S(f,y){return new nn({fields:y??void 0,session:void 0,dialect:n.getDialect(),distinct:{on:f}})}return{select:t,selectDistinct:T,selectDistinctOn:S}}select(o){return new nn({fields:o??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(o){return new nn({fields:o??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(o,n){return new nn({fields:n??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:o}})}getDialect(){if(!this.dialect)this.dialect=new Xt(this.dialectConfig);return this.dialect}}class Vy extends so{constructor(o,n,t){super();this.session=n,this.dialect=t,this.config={view:o}}static[J]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings: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 PS{constructor(o,n,t,T){this.table=o,this.session=n,this.dialect=t,this.withList=T}static[J]="PgUpdateBuilder";set(o){return new Y$(this.table,_S(this.table,o),this.session,this.dialect,this.withList)}}class Y$ extends so{constructor(o,n,t,T,S){super();this.session=t,this.dialect=T,this.config={set:n,table:o,withList:S}}static[J]="PgUpdate";config;where(o){return this.config.where=o,this}returning(o=this.config.table[L.Symbol.Columns]){return this.config.returning=wn(o),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{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 xT extends h{constructor(o){super(xT.buildEmbeddedCount(o.source,o.filters).queryChunks);this.params=o,this.mapWith(Number),this.session=o.session,this.sql=xT.buildCount(o.source,o.filters)}sql;static[J]="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 By{constructor(o,n,t,T,S,f,y){this.fullSchema=o,this.schema=n,this.tableNamesMap=t,this.table=T,this.tableConfig=S,this.dialect=f,this.session=y}static[J]="PgRelationalQueryBuilder";findMany(o){return new ry(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?o:{},"many")}findFirst(o){return new ry(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?{...o,limit:1}:{limit:1},"first")}}class ry extends so{constructor(o,n,t,T,S,f,y,A,M){super();this.fullSchema=o,this.schema=n,this.tableNamesMap=t,this.table=T,this.tableConfig=S,this.dialect=f,this.session=y,this.config=A,this.mode=M}static[J]="PgRelationalQuery";_prepare(o){return Oo.startActiveSpan("drizzle.prepareQuery",()=>{let{query:n,builtQuery:t}=this._toSQL();return this.session.prepareQuery(t,void 0,o,!0,(T,S)=>{let f=T.map((y)=>DS(this.schema,this.tableConfig,y,n.selection,S));if(this.mode==="first")return f[0];return f})})}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(){let 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 Cy extends so{constructor(o,n,t,T){super();this.execute=o,this.sql=n,this.query=t,this.mapBatchResult=T}static[J]="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 iT{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[T,S]of Object.entries(this._.schema))this.query[T]=new By(t.fullSchema,this._.schema,this._.tableNamesMap,t.fullSchema[T],S,o,n)}static[J]="PgDatabase";query;$with(o){let n=this;return{as(t){if(typeof t==="function")t=t(new Uy(n.dialect));return new Proxy(new _T(t.getSQL(),t.getSelectedFields(),o,!0),new An({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}$count(o,n){return new xT({source:o,filters:n,session:this.session})}with(...o){let n=this;function t(M){return new nn({fields:M??void 0,session:n.session,dialect:n.dialect,withList:o})}function T(M){return new nn({fields:M??void 0,session:n.session,dialect:n.dialect,withList:o,distinct:!0})}function S(M,F){return new nn({fields:F??void 0,session:n.session,dialect:n.dialect,withList:o,distinct:{on:M}})}function f(M){return new PS(M,n.session,n.dialect,o)}function y(M){return new ZS(M,n.session,n.dialect,o)}function A(M){return new qS(M,n.session,n.dialect,o)}return{select:t,selectDistinct:T,selectDistinctOn:S,update:f,insert:y,delete:A}}select(o){return new nn({fields:o??void 0,session:this.session,dialect:this.dialect})}selectDistinct(o){return new nn({fields:o??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(o,n){return new nn({fields:n??void 0,session:this.session,dialect:this.dialect,distinct:{on:o}})}update(o){return new PS(o,this.session,this.dialect)}insert(o){return new ZS(o,this.session,this.dialect)}delete(o){return new qS(o,this.session,this.dialect)}refreshMaterializedView(o){return new Vy(o,this.session,this.dialect)}execute(o){let n=typeof o==="string"?R.raw(o):o.getSQL(),t=this.dialect.sqlToQuery(n),T=this.session.prepareQuery(t,void 0,void 0,!1);return new Cy(()=>T.execute(),n,t,(S)=>T.mapResult(S,!0))}transaction(o,n){return this.session.transaction(o,n)}}class G${constructor(o,n){this.unique=o,this.name=n}static[J]="PgIndexBuilderOn";on(...o){return new eS(o.map((n)=>{if(X(n,h))return n;n=n;let t=new OT(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 eS(o.map((n)=>{if(X(n,h))return n;n=n;let t=new OT(n.name,!!n.keyAsName,n.columnType,n.indexConfig);return n.indexConfig=n.defaultConfig,t}),this.unique,!0,this.name)}using(o,...n){return new eS(n.map((t)=>{if(X(t,h))return t;t=t;let T=new OT(t.name,!!t.keyAsName,t.columnType,t.indexConfig);return t.indexConfig=JSON.parse(JSON.stringify(t.defaultConfig)),T}),this.unique,!0,this.name,o)}}class eS{static[J]="PgIndexBuilder";config;constructor(o,n,t,T,S="btree"){this.config={name:T,columns:o,unique:n,only:t,method:S}}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[J]="PgIndex";config;constructor(o,n){this.config={...o,table:n}}}function Ly(o){return new G$(!0,o)}class Iy{constructor(o){this.query=o}getQuery(){return this.query}mapResult(o,n){return o}static[J]="PgPreparedQuery";joinsNotNullableMap}class jy{constructor(o){this.dialect=o}static[J]="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){let n=await this.execute(o);return Number(n[0].count)}}class by extends iT{constructor(o,n,t,T=0){super(o,n,t);this.schema=t,this.nestedIndex=T}static[J]="PgTransaction";rollback(){throw new ef}getTransactionConfigSQL(o){let 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 H$ extends Iy{constructor(o,n,t,T,S,f,y){super({sql:n,params:t});this.client=o,this.queryString=n,this.params=t,this.logger=T,this.fields=S,this._isResponseInArrayMode=f,this.customResultMapper=y}static[J]="PostgresJsPreparedQuery";async execute(o={}){return Oo.startActiveSpan("drizzle.execute",async(n)=>{let t=Zf(this.params,o);n?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(t)}),this.logger.logQuery(this.queryString,t);let{fields:T,queryString:S,client:f,joinsNotNullableMap:y,customResultMapper:A}=this;if(!T&&!A)return Oo.startActiveSpan("drizzle.driver.execute",()=>{return f.unsafe(S,t)});let M=await Oo.startActiveSpan("drizzle.driver.execute",()=>{return n?.setAttributes({"drizzle.query.text":S,"drizzle.query.params":JSON.stringify(t)}),f.unsafe(S,t).values()});return Oo.startActiveSpan("drizzle.mapResponse",()=>{return A?A(M):M.map((F)=>IM(T,F,y))})})}all(o={}){return Oo.startActiveSpan("drizzle.execute",async(n)=>{let t=Zf(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 vT extends jy{constructor(o,n,t,T={}){super(n);this.client=o,this.schema=t,this.options=T,this.logger=T.logger??new gf}static[J]="PostgresJsSession";logger;prepareQuery(o,n,t,T,S){return new H$(this.client,o.sql,o.params,this.logger,n,T,S)}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)=>{let T=new vT(t,this.dialect,this.schema,this.options),S=new Ny(this.dialect,T,this.schema);if(n)await S.setTransaction(n);return o(S)})}}class Ny extends by{constructor(o,n,t,T=0){super(o,n,t,T);this.session=n}static[J]="PostgresJsTransaction";transaction(o){return this.session.client.savepoint((n)=>{let t=new vT(n,this.dialect,this.schema,this.session.options),T=new Ny(this.dialect,t,this.schema);return o(T)})}}class m$ extends iT{static[J]="PostgresJsDatabase"}function st(o,n={}){let t=(M)=>M;for(let M of["1184","1082","1083","1114"])o.options.parsers[M]=t,o.options.serializers[M]=t;o.options.serializers["114"]=t,o.options.serializers["3802"]=t;let T=new Xt({casing:n.casing}),S;if(n.logger===!0)S=new lf;else if(n.logger!==!1)S=n.logger;let f;if(n.schema){let M=Ik(n.schema,bk);f={fullSchema:n.schema,schema:M.tables,tableNamesMap:M.tableNamesMap}}let y=new vT(o,T,f,{logger:S}),A=new m$(T,y,f);return A.$client=o,A}function lS(...o){if(typeof o[0]==="string"){let n=ut(o[0]);return st(n,o[1])}if(NM(o[0])){let{connection:n,client:t,...T}=o[0];if(t)return st(t,T);if(typeof n==="object"&&n.url!==void 0){let{url:f,...y}=n,A=ut(f,y);return st(A,T)}let S=ut(n);return st(S,T)}return st(o[0],o[1])}((o)=>{function n(t){return st({},t)}o.mock=n})(lS||(lS={}));var cy={};rJ(cy,{users:()=>Et,userChanges:()=>Z0,untrackedUserColumnNames:()=>q0,twoFactorMethod:()=>r$,trackedUserColumnName:()=>V$,trackableUserColumnNames:()=>U$,role:()=>D$,players:()=>hy,passwordResetAttempts:()=>e0,loginHistory:()=>P0,games:()=>gS,banishedIps:()=>pT});function Q$(o){return R`lower(${o})`}var D$=$S("role",["admin","user"]),Et=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:Dn({withTimezone:!0}).notNull().defaultNow(),createdIp:io({length:45}).notNull(),isActive:ET().notNull().default(!1),verifiedAt:Dn({withTimezone:!0}),userRole:D$().default("user")},(o)=>[Ly("usernameUniqueIndex").on(Q$(o.username)),Ly("emailUniqueIndex").on(Q$(o.email))]),q0=["id","createdAt","createdIp","isActive","salt","verifiedAt"],U$=["username","email","hash","userRole"],V$=$S("trackedUserColumnName",U$),Z0=nt("userChanges",{id:$n().primaryKey().defaultRandom(),userId:$n().notNull().references(()=>Et.id),changedAt:Dn({withTimezone:!0}).notNull().defaultNow(),changedIp:io({length:45}).notNull(),changedColumn:V$().notNull(),oldValue:io({length:255}),newValue:io({length:255})}),gS=nt("games",{id:$n().primaryKey().defaultRandom()}),hy=nt("players",{userId:$n().notNull().references(()=>Et.id),gameId:$n().notNull().references(()=>gS.id),score:XS().notNull()},(o)=>[Vk({name:"players_userId_gameId_pk",columns:[o.userId,o.gameId]})]),P0=nt("loginHistory",{id:$n().primaryKey().defaultRandom(),userId:$n().references(()=>Et.id),loginTime:Dn({withTimezone:!0}).notNull().defaultNow(),ipAddress:io({length:45}).notNull(),userAgent:io({length:1024}),successful:ET().notNull().default(!1)}),r$=$S("twoFactorMethod",["email","phone"]),e0=nt("passwordResetAttempts",{id:$n().primaryKey().defaultRandom(),userId:$n().notNull().references(()=>Et.id),requestedIp:io({length:45}).notNull(),requestedAt:Dn({withTimezone:!0}).notNull().defaultNow(),succeededIp:io({length:45}),succeededAt:Dn({withTimezone:!0}),verificationMethod:r$().notNull()}),pT=nt("banishedIps",{ip:io({length:45}).primaryKey(),reason:io({length:2048}).notNull(),banishedAt:Dn({withTimezone:!0}).notNull().defaultNow(),banishedUntil:Dn({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class xy{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(l0.resolve(__dirname,"notify_update.sql"));let o=[_n(Et),_n(gS),_n(hy)];await this.sql`SELECT create_notify_triggers(${this.sql.array(o)})`,await this.sql.listen("table_update",(n)=>{let t=n.split(","),T=t[0],S=t[1],f=`${T}("${S}")`;if(this.observers.has(f))this.observers.get(f).next(f)})}constructor(o=!1,n={host:Cn.POSTGRES_HOST,port:Cn.POSTGRES_PORT,user:Cn.POSTGRES_USER,password:Cn.POSTGRES_PASSWORD,database:Cn.POSTGRES_DATABASE}){this.options=n,this.sql=ut(n),this.drizzle=lS(this.sql,{schema:cy,logger:o})}observe(o,n){if(!this.observers.has(o))this.observers.set(o,new s);this.observers.get(o).subscribe("SINGLETON",n)}}var dS={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"},iy=oA(dS).map(([o])=>zo.literal(Number(o))),g0=zo.union([iy[0],iy[1],...iy]),B$=zo.tuple([g0,zo.string()]);var py=new rf,{logger:tn}=py;Object.assign(console,tn,{log:tn.info});tn.info(" ready");var vy=L$(import.meta.dir,"..","app"),s0=new xy({logQuery(o,n){tn.info("\uD83D\uDCDD query",o,n)}});a0({hostname:"0.0.0.0",port:Cn.FRONTEND_PORT??3333,...ak??void 0,async fetch(o,n){try{let t=new Date,T=new URL(o.url),S=n.requestIP(o)?.address??"??";tn.info(t,S,o.method,T.pathname);let[f]=await s0.drizzle.select({banishedUntil:pT.banishedUntil}).from(pT).where(Ct(pT.ip,S)).limit(1),y=f?.banishedUntil===null,A=f?.banishedUntil&&f.banishedUntil>t;if(y||A)throw tn.info(`\uD83D\uDE45 request from banned ip ${S}`),[403,S];if(T.pathname==="/")return new Response(Bun.file(L$(vy,"index.html")));if(T.pathname==="/index.html")return Response.redirect("/");let M=d0(vy,T.pathname),F=u0(M);if(!F.startsWith(vy))throw[403,"Access Denied"];if(!await C$(F).exists())return Response.redirect("/");return new Response(C$(F))}catch(t){let T=B$.safeParse(t);if(T.success){let[S,f]=T.data,A=`${dS[S]}. ${f}`;return tn.info(`\u274C ${S}: ${A}`),new Response(A,{status:S})}if(t instanceof Error)tn.error(t.message);else{let S=Ut(t);tn.error("frontend server threw",S)}return new Response(dS[500],{status:500})}}});function uS(){tn.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{tn.info("\u2757 received SIGINT; exiting gracefully"),uS()});process.on("SIGTERM",()=>{tn.info("\u2757 received SIGTERM; exiting gracefully"),uS()});process.on("exit",()=>{tn.info("\u2757 received exit; exiting gracefully"),uS()});py.on("timeToStop",()=>{tn.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),uS()});tn.info(`\uD83D\uDEEB frontend server running at http://localhost:${Cn.FRONTEND_PORT}/`);py.emit("alive");
|
|
36
|
+
`;await n.execute(R`CREATE SCHEMA IF NOT EXISTS ${R.identifier(S)}`),await n.execute(f);let A=(await n.all(R`select id, hash, created_at from ${R.identifier(S)}.${R.identifier(t)} order by created_at desc limit 1`))[0];await n.transaction(async(M)=>{for await(let F of o)if(!A||Number(A.created_at)<F.folderMillis){for(let $ of F.sql)await M.execute(R.raw($));await M.execute(R`insert into ${R.identifier(S)}.${R.identifier(t)} ("hash", "created_at") values(${F.hash}, ${F.folderMillis})`)}})}escapeName(o){return`"${o}"`}escapeParam(o){return`$${o+1}`}escapeString(o){return`'${o.replace(/'/g,"''")}'`}buildWithCTE(o){if(!o?.length)return;let n=[R`with `];for(let[T,t]of o.entries())if(n.push(R`${R.identifier(t._.alias)} as (${t._.sql})`),T<o.length-1)n.push(R`, `);return n.push(R` `),R.join(n)}buildDeleteQuery({table:o,where:n,returning:T,withList:t}){let S=this.buildWithCTE(t),f=T?R` returning ${this.buildSelection(T,{isSingleTable:!0})}`:void 0,y=n?R` where ${n}`:void 0;return R`${S}delete from ${o}${y}${f}`}buildUpdateSet(o,n){let T=o[L.Symbol.Columns],t=Object.keys(T).filter((f)=>n[f]!==void 0||T[f]?.onUpdateFn!==void 0),S=t.length;return R.join(t.flatMap((f,y)=>{let A=T[f],M=n[f]??R.param(A.onUpdateFn(),A),F=R`${R.identifier(this.casing.getColumnCasing(A))} = ${M}`;if(y<S-1)return[F,R.raw(", ")];return[F]}))}buildUpdateQuery({table:o,set:n,where:T,returning:t,withList:S,from:f,joins:y}){let A=this.buildWithCTE(S),M=o[io.Symbol.Name],F=o[io.Symbol.Schema],$=o[io.Symbol.OriginalName],W=M===$?void 0:M,O=R`${F?R`${R.identifier(F)}.`:void 0}${R.identifier($)}${W&&R` ${R.identifier(W)}`}`,G=this.buildUpdateSet(o,n),D=f&&R.join([R.raw(" from "),this.buildFromTable(f)]),z=this.buildJoins(y),Y=t?R` returning ${this.buildSelection(t,{isSingleTable:!f})}`:void 0,B=T?R` where ${T}`:void 0;return R`${A}update ${O} set ${G}${D}${z}${B}${Y}`}buildSelection(o,{isSingleTable:n=!1}={}){let T=o.length,t=o.flatMap(({field:S},f)=>{let y=[];if(X(S,r.Aliased)&&S.isSelectionField)y.push(R.identifier(S.fieldAlias));else if(X(S,r.Aliased)||X(S,r)){let A=X(S,r.Aliased)?S.sql:S;if(n)y.push(new r(A.queryChunks.map((M)=>{if(X(M,V))return R.identifier(this.casing.getColumnCasing(M));return M})));else y.push(A);if(X(S,r.Aliased))y.push(R` as ${R.identifier(S.fieldAlias)}`)}else if(X(S,Ro))if(n)y.push(R.identifier(this.casing.getColumnCasing(S)));else y.push(S);if(f<T-1)y.push(R`, `);return y});return R.join(t)}buildJoins(o){if(!o||o.length===0)return;let n=[];for(let[T,t]of o.entries()){if(T===0)n.push(R` `);let S=t.table,f=t.lateral?R` lateral`:void 0;if(X(S,io)){let y=S[io.Symbol.Name],A=S[io.Symbol.Schema],M=S[io.Symbol.OriginalName],F=y===M?void 0:t.alias;n.push(R`${R.raw(t.joinType)} join${f} ${A?R`${R.identifier(A)}.`:void 0}${R.identifier(M)}${F&&R` ${R.identifier(F)}`} on ${t.on}`)}else if(X(S,An)){let y=S[Yo].name,A=S[Yo].schema,M=S[Yo].originalName,F=y===M?void 0:t.alias;n.push(R`${R.raw(t.joinType)} join${f} ${A?R`${R.identifier(A)}.`:void 0}${R.identifier(M)}${F&&R` ${R.identifier(F)}`} on ${t.on}`)}else n.push(R`${R.raw(t.joinType)} join${f} ${S} on ${t.on}`);if(T<o.length-1)n.push(R` `)}return R.join(n)}buildFromTable(o){if(X(o,L)&&o[L.Symbol.OriginalName]!==o[L.Symbol.Name]){let n=R`${R.identifier(o[L.Symbol.OriginalName])}`;if(o[L.Symbol.Schema])n=R`${R.identifier(o[L.Symbol.Schema])}.${n}`;return R`${n} ${R.identifier(o[L.Symbol.Name])}`}return o}buildSelectQuery({withList:o,fields:n,fieldsFlat:T,where:t,having:S,table:f,joins:y,orderBy:A,groupBy:M,limit:F,offset:$,lockingClause:W,distinct:O,setOperators:G}){let D=T??wn(n);for(let q of D)if(X(q.field,Ro)&&_n(q.field.table)!==(X(f,ho)?f._.alias:X(f,it)?f[Yo].name:X(f,r)?void 0:_n(f))&&!((ko)=>y?.some(({alias:Oo})=>Oo===(ko[L.Symbol.IsAlias]?_n(ko):ko[L.Symbol.BaseName])))(q.field.table)){let ko=_n(q.field.table);throw new Error(`Your "${q.path.join("->")}" field references a column "${ko}"."${q.field.name}", but the table "${ko}" is not part of the query! Did you forget to join it?`)}let z=!y||y.length===0,Y=this.buildWithCTE(o),B;if(O)B=O===!0?R` distinct`:R` distinct on (${R.join(O.on,R`, `)})`;let v=this.buildSelection(D,{isSingleTable:z}),x=this.buildFromTable(f),a=this.buildJoins(y),E=t?R` where ${t}`:void 0,K=S?R` having ${S}`:void 0,m;if(A&&A.length>0)m=R` order by ${R.join(A,R`, `)}`;let c;if(M&&M.length>0)c=R` group by ${R.join(M,R`, `)}`;let b=typeof F==="object"||typeof F==="number"&&F>=0?R` limit ${F}`:void 0,w=$?R` offset ${$}`:void 0,i=R.empty();if(W){let q=R` for ${R.raw(W.strength)}`;if(W.config.of)q.append(R` of ${R.join(Array.isArray(W.config.of)?W.config.of:[W.config.of],R`, `)}`);if(W.config.noWait)q.append(R` no wait`);else if(W.config.skipLocked)q.append(R` skip locked`);i.append(q)}let N=R`${Y}select${B} ${v} from ${x}${a}${E}${c}${K}${m}${b}${w}${i}`;if(G.length>0)return this.buildSetOperations(N,G);return N}buildSetOperations(o,n){let[T,...t]=n;if(!T)throw new Error("Cannot pass undefined values to any set operator");if(t.length===0)return this.buildSetOperationQuery({leftSelect:o,setOperator:T});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:o,setOperator:T}),t)}buildSetOperationQuery({leftSelect:o,setOperator:{type:n,isAll:T,rightSelect:t,limit:S,orderBy:f,offset:y}}){let A=R`(${o.getSQL()}) `,M=R`(${t.getSQL()})`,F;if(f&&f.length>0){let G=[];for(let D of f)if(X(D,V))G.push(R.identifier(D.name));else if(X(D,r)){for(let z=0;z<D.queryChunks.length;z++){let Y=D.queryChunks[z];if(X(Y,V))D.queryChunks[z]=R.identifier(Y.name)}G.push(R`${D}`)}else G.push(R`${D}`);F=R` order by ${R.join(G,R`, `)} `}let $=typeof S==="object"||typeof S==="number"&&S>=0?R` limit ${S}`:void 0,W=R.raw(`${n} ${T?"all ":""}`),O=y?R` offset ${y}`:void 0;return R`${A}${W}${M}${F}${$}${O}`}buildInsertQuery({table:o,values:n,onConflict:T,returning:t,withList:S,select:f,overridingSystemValue_:y}){let A=[],M=o[L.Symbol.Columns],F=Object.entries(M).filter(([Y,B])=>!B.shouldDisableInsert()),$=F.map(([,Y])=>R.identifier(this.casing.getColumnCasing(Y)));if(f){let Y=n;if(X(Y,r))A.push(Y);else A.push(Y.getSQL())}else{let Y=n;A.push(R.raw("values "));for(let[B,v]of Y.entries()){let x=[];for(let[a,E]of F){let K=v[a];if(K===void 0||X(K,$n)&&K.value===void 0)if(E.defaultFn!==void 0){let m=E.defaultFn(),c=X(m,r)?m:R.param(m,E);x.push(c)}else if(!E.default&&E.onUpdateFn!==void 0){let m=E.onUpdateFn(),c=X(m,r)?m:R.param(m,E);x.push(c)}else x.push(R`default`);else x.push(K)}if(A.push(x),B<Y.length-1)A.push(R`, `)}}let W=this.buildWithCTE(S),O=R.join(A),G=t?R` returning ${this.buildSelection(t,{isSingleTable:!0})}`:void 0,D=T?R` on conflict ${T}`:void 0,z=y===!0?R`overriding system value `:void 0;return R`${W}insert into ${o} ${$} ${z}${O}${D}${G}`}buildRefreshMaterializedViewQuery({view:o,concurrently:n,withNoData:T}){let t=n?R` concurrently`:void 0,S=T?R` with no data`:void 0;return R`refresh materialized view${t} ${o}${S}`}prepareTyping(o){if(X(o,QS)||X(o,mS))return"json";else if(X(o,DS))return"decimal";else if(X(o,US))return"time";else if(X(o,VS)||X(o,BS))return"timestamp";else if(X(o,GS)||X(o,zS))return"date";else if(X(o,CS))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:t,tableConfig:S,queryConfig:f,tableAlias:y,nestedQueryRelation:A,joinOn:M}){let F=[],$,W,O=[],G,D=[];if(f===!0)F=Object.entries(S.columns).map(([B,v])=>({dbKey:v.name,tsKey:B,field:jn(v,y),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let Y=Object.fromEntries(Object.entries(S.columns).map(([K,m])=>[K,jn(m,y)]));if(f.where){let K=typeof f.where==="function"?f.where(Y,I$()):f.where;G=K&&Xt(K,y)}let B=[],v=[];if(f.columns){let K=!1;for(let[m,c]of Object.entries(f.columns)){if(c===void 0)continue;if(m in S.columns){if(!K&&c===!0)K=!0;v.push(m)}}if(v.length>0)v=K?v.filter((m)=>f.columns?.[m]===!0):Object.keys(S.columns).filter((m)=>!v.includes(m))}else v=Object.keys(S.columns);for(let K of v){let m=S.columns[K];B.push({tsKey:K,value:m})}let x=[];if(f.with)x=Object.entries(f.with).filter((K)=>!!K[1]).map(([K,m])=>({tsKey:K,queryConfig:m,relation:S.relations[K]}));let a;if(f.extras){a=typeof f.extras==="function"?f.extras(Y,{sql:R}):f.extras;for(let[K,m]of Object.entries(a))B.push({tsKey:K,value:uf(m,y)})}for(let{tsKey:K,value:m}of B)F.push({dbKey:X(m,r.Aliased)?m.fieldAlias:S.columns[K].name,tsKey:K,field:X(m,Ro)?jn(m,y):m,relationTableTsKey:void 0,isJson:!1,selection:[]});let E=typeof f.orderBy==="function"?f.orderBy(Y,r$()):f.orderBy??[];if(!Array.isArray(E))E=[E];O=E.map((K)=>{if(X(K,Ro))return jn(K,y);return Xt(K,y)}),$=f.limit,W=f.offset;for(let{tsKey:K,queryConfig:m,relation:c}of x){let b=N$(n,T,c),w=kT(c.referencedTable),i=T[w],N=`${y}_${K}`,q=Et(...b.fields.map((Sn,cn)=>IT(jn(b.references[cn],N),jn(Sn,y)))),ko=this.buildRelationalQueryWithoutPK({fullSchema:o,schema:n,tableNamesMap:T,table:o[i],tableConfig:n[i],queryConfig:X(c,tT)?m===!0?{limit:1}:{...m,limit:1}:m,tableAlias:N,joinOn:q,nestedQueryRelation:c}),Oo=R`${R.identifier(N)}.${R.identifier("data")}`.as(K);D.push({on:R`true`,table:new ho(ko.sql,{},N),alias:N,joinType:"left",lateral:!0}),F.push({dbKey:K,tsKey:K,field:Oo,relationTableTsKey:i,isJson:!0,selection:ko.selection})}}if(F.length===0)throw new ES({message:`No fields selected for table "${S.tsName}" ("${y}")`});let z;if(G=Et(M,G),A){let Y=R`json_build_array(${R.join(F.map(({field:x,tsKey:a,isJson:E})=>E?R`${R.identifier(`${y}_${a}`)}.${R.identifier("data")}`:X(x,r.Aliased)?x.sql:x),R`, `)})`;if(X(A,Ht))Y=R`coalesce(json_agg(${Y}${O.length>0?R` order by ${R.join(O,R`, `)}`:void 0}), '[]'::json)`;let B=[{dbKey:"data",tsKey:"data",field:Y.as("data"),isJson:!0,relationTableTsKey:S.tsName,selection:F}];if($!==void 0||W!==void 0||O.length>0)z=this.buildSelectQuery({table:XS(t,y),fields:{},fieldsFlat:[{path:[],field:R.raw("*")}],where:G,limit:$,offset:W,orderBy:O,setOperators:[]}),G=void 0,$=void 0,W=void 0,O=[];else z=XS(t,y);z=this.buildSelectQuery({table:X(z,io)?z:new ho(z,{},y),fields:{},fieldsFlat:B.map(({field:x})=>({path:[],field:X(x,Ro)?jn(x,y):x})),joins:D,where:G,limit:$,offset:W,orderBy:O,setOperators:[]})}else z=this.buildSelectQuery({table:XS(t,y),fields:{},fieldsFlat:F.map(({field:Y})=>({path:[],field:X(Y,Ro)?jn(Y,y):Y})),joins:D,where:G,limit:$,offset:W,orderBy:O,setOperators:[]});return{tableTsKey:S.tsName,sql:z,selection:F}}}class vo{static[J]="SelectionProxyHandler";config;constructor(o){this.config={...o}}get(o,n){if(n==="_")return{...o._,selectedFields:new Proxy(o._.selectedFields,this)};if(n===Yo)return{...o[Yo],selectedFields:new Proxy(o[Yo].selectedFields,this)};if(typeof n==="symbol")return o[n];let t=(X(o,ho)?o._.selectedFields:X(o,An)?o[Yo].selectedFields:o)[n];if(X(t,r.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!t.isSelectionField)return t.sql;let S=t.clone();return S.isSelectionField=!0,S}if(X(t,r)){if(this.config.sqlBehavior==="sql")return t;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(t,Ro)){if(this.config.alias)return new Proxy(t,new LT(new Proxy(t.table,new Kt(this.config.alias,this.config.replaceOriginalName??!1))));return t}if(typeof t!=="object"||t===null)return t;return new Proxy(t,new vo(this.config))}}class Vy{static[J]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class Tn{static[J]="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}authToken;setToken(o){return this.authToken=o,this}from(o){let n=!!this.fields,T;if(this.fields)T=this.fields;else if(X(o,ho))T=Object.fromEntries(Object.keys(o._.selectedFields).map((t)=>[t,o[t]]));else if(X(o,it))T=o[Yo].selectedFields;else if(X(o,r))T={};else T=hM(o);return new By({table:o,fields:T,isPartialSelect:n,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class Ek extends Vy{static[J]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:o,fields:n,isPartialSelect:T,session:t,dialect:S,withList:f,distinct:y}){super();this.config={withList:f,table:o,fields:{...n},distinct:y,setOperators:[]},this.isPartialSelect=T,this.session=t,this.dialect=S,this._={selectedFields:n},this.tableName=Zn(o),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(o){return(n,T)=>{let t=this.tableName,S=Zn(n);if(typeof S==="string"&&this.config.joins?.some((f)=>f.alias===S))throw new Error(`Alias "${S}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof t==="string")this.config.fields={[t]:this.config.fields};if(typeof S==="string"&&!X(n,r)){let f=X(n,ho)?n._.selectedFields:X(n,An)?n[Yo].selectedFields:n[L.Symbol.Columns];this.config.fields[S]=f}}if(typeof T==="function")T=T(new Proxy(this.config.fields,new vo({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:T,table:n,joinType:o,alias:S}),typeof S==="string")switch(o){case"left":{this.joinsNotNullableMap[S]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([f])=>[f,!1])),this.joinsNotNullableMap[S]=!0;break}case"inner":{this.joinsNotNullableMap[S]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([f])=>[f,!1])),this.joinsNotNullableMap[S]=!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)=>{let t=typeof T==="function"?T(h0()):T;if(!Yt(this.getSelectedFields(),t.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:t}),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 vo({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=o,this}having(o){if(typeof o==="function")o=o(new Proxy(this.config.fields,new vo({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=o,this}groupBy(...o){if(typeof o[0]==="function"){let n=o[0](new Proxy(this.config.fields,new vo({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"){let n=o[0](new Proxy(this.config.fields,new vo({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{let 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(){let{typings:o,...n}=this.dialect.sqlToQuery(this.getSQL());return n}as(o){return new Proxy(new ho(this.getSQL(),this.config.fields,o),new vo({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new vo({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class By extends Ek{static[J]="PgSelect";_prepare(o){let{session:n,config:T,dialect:t,joinsNotNullableMap:S,authToken: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",()=>{let y=wn(T.fields),A=n.prepareQuery(t.sqlToQuery(this.getSQL()),y,o,!0);return A.joinsNotNullableMap=S,A.setToken(f)})}prepare(o){return this._prepare(o)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return Wo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o,this.authToken)})}}NM(By,[on]);function sT(o,n){return(T,t,...S)=>{let f=[t,...S].map((y)=>({type:o,isAll:n,rightSelect:y}));for(let y of f)if(!Yt(T.getSelectedFields(),y.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(f)}}var h0=()=>({union:b0,unionAll:c0,intersect:x0,intersectAll:i0,except:v0,exceptAll:p0}),b0=sT("union",!1),c0=sT("union",!0),x0=sT("intersect",!1),i0=sT("intersect",!0),v0=sT("except",!1),p0=sT("except",!0);class vt{static[J]="PgQueryBuilder";dialect;dialectConfig;constructor(o){this.dialect=X(o,ET)?o:void 0,this.dialectConfig=X(o,ET)?void 0:o}$with(o){let n=this;return{as(T){if(typeof T==="function")T=T(n);return new Proxy(new wt(T.getSQL(),T.getSelectedFields(),o,!0),new vo({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}with(...o){let n=this;function T(f){return new Tn({fields:f??void 0,session:void 0,dialect:n.getDialect(),withList:o})}function t(f){return new Tn({fields:f??void 0,session:void 0,dialect:n.getDialect(),distinct:!0})}function S(f,y){return new Tn({fields:y??void 0,session:void 0,dialect:n.getDialect(),distinct:{on:f}})}return{select:T,selectDistinct:t,selectDistinctOn:S}}select(o){return new Tn({fields:o??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(o){return new Tn({fields:o??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(o,n){return new Tn({fields:n??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:o}})}getDialect(){if(!this.dialect)this.dialect=new ET(this.dialectConfig);return this.dialect}}class dS{constructor(o,n,T,t,S){this.table=o,this.session=n,this.dialect=T,this.withList=t,this.overridingSystemValue_=S}static[J]="PgInsertBuilder";authToken;setToken(o){return this.authToken=o,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(o){if(o=Array.isArray(o)?o:[o],o.length===0)throw new Error("values() must be called with at least one value");let n=o.map((T)=>{let t={},S=this.table[L.Symbol.Columns];for(let f of Object.keys(T)){let y=T[f];t[f]=X(y,r)?y:new $n(y,S[f])}return t});return new Cy(this.table,n,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(o){let n=typeof o==="function"?o(new vt):o;if(!X(n,r)&&!Yt(this.table[_S],n._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new Cy(this.table,n,this.session,this.dialect,this.withList,!0)}}class Cy extends on{constructor(o,n,T,t,S,f,y){super();this.session=T,this.dialect=t,this.config={table:o,values:n,withList:S,select:f,overridingSystemValue_:y}}static[J]="PgInsert";config;returning(o=this.config.table[L.Symbol.Columns]){return this.config.returning=wn(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((t)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(t))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(o.target));let 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.');let n=o.where?R` where ${o.where}`:void 0,T=o.targetWhere?R` where ${o.targetWhere}`:void 0,t=o.setWhere?R` where ${o.setWhere}`:void 0,S=this.dialect.buildUpdateSet(this.config.table,YS(this.config.table,o.set)),f="";return f=Array.isArray(o.target)?o.target.map((y)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(y))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(o.target)),this.config.onConflict=R`(${R.raw(f)})${T} do update set ${S}${n}${t}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{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)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return Wo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o,this.authToken)})};$dynamic(){return this}}class Ly extends on{constructor(o,n,T){super();this.session=n,this.dialect=T,this.config={view:o}}static[J]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings: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)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return Wo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o,this.authToken)})}}class uS{constructor(o,n,T,t){this.table=o,this.session=n,this.dialect=T,this.withList=t}static[J]="PgUpdateBuilder";authToken;setToken(o){return this.authToken=o,this}set(o){return new Yk(this.table,YS(this.table,o),this.session,this.dialect,this.withList).setToken(this.authToken)}}class Yk extends on{constructor(o,n,T,t,S){super();this.session=T,this.dialect=t,this.config={set:n,table:o,withList:S,joins:[]},this.tableName=Zn(o),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[J]="PgUpdate";config;tableName;joinsNotNullableMap;from(o){let n=Zn(o);if(typeof n==="string")this.joinsNotNullableMap[n]=!0;return this.config.from=o,this}getTableLikeFields(o){if(X(o,io))return o[L.Symbol.Columns];else if(X(o,ho))return o._.selectedFields;return o[Yo].selectedFields}createJoin(o){return(n,T)=>{let t=Zn(n);if(typeof t==="string"&&this.config.joins.some((S)=>S.alias===t))throw new Error(`Alias "${t}" is already used in this query`);if(typeof T==="function"){let S=this.config.from&&!X(this.config.from,r)?this.getTableLikeFields(this.config.from):void 0;T=T(new Proxy(this.config.table[L.Symbol.Columns],new vo({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),S&&new Proxy(S,new vo({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:T,table:n,joinType:o,alias:t}),typeof t==="string")switch(o){case"left":{this.joinsNotNullableMap[t]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([S])=>[S,!1])),this.joinsNotNullableMap[t]=!0;break}case"inner":{this.joinsNotNullableMap[t]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([S])=>[S,!1])),this.joinsNotNullableMap[t]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(o){return this.config.where=o,this}returning(o){if(!o){if(o=Object.assign({},this.config.table[L.Symbol.Columns]),this.config.from){let n=Zn(this.config.from);if(typeof n==="string"&&this.config.from&&!X(this.config.from,r)){let T=this.getTableLikeFields(this.config.from);o[n]=T}for(let T of this.config.joins){let t=Zn(T.table);if(typeof t==="string"&&!X(T.table,r)){let S=this.getTableLikeFields(T.table);o[t]=S}}}}return this.config.returning=wn(o),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:o,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(o){let n=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,o,!0);return n.joinsNotNullableMap=this.joinsNotNullableMap,n}prepare(o){return this._prepare(o)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return this._prepare().execute(o,this.authToken)};$dynamic(){return this}}class pt extends r{constructor(o){super(pt.buildEmbeddedCount(o.source,o.filters).queryChunks);this.params=o,this.mapWith(Number),this.session=o.session,this.sql=pt.buildCount(o.source,o.filters)}sql;token;static[J]="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};`}setToken(o){return this.token=o,this}then(o,n){return Promise.resolve(this.session.count(this.sql,this.token)).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 ry{constructor(o,n,T,t,S,f,y){this.fullSchema=o,this.schema=n,this.tableNamesMap=T,this.table=t,this.tableConfig=S,this.dialect=f,this.session=y}static[J]="PgRelationalQueryBuilder";findMany(o){return new Iy(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?o:{},"many")}findFirst(o){return new Iy(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?{...o,limit:1}:{limit:1},"first")}}class Iy extends on{constructor(o,n,T,t,S,f,y,A,M){super();this.fullSchema=o,this.schema=n,this.tableNamesMap=T,this.table=t,this.tableConfig=S,this.dialect=f,this.session=y,this.config=A,this.mode=M}static[J]="PgRelationalQuery";_prepare(o){return Wo.startActiveSpan("drizzle.prepareQuery",()=>{let{query:n,builtQuery:T}=this._toSQL();return this.session.prepareQuery(T,void 0,o,!0,(t,S)=>{let f=t.map((y)=>LS(this.schema,this.tableConfig,y,n.selection,S));if(this.mode==="first")return f[0];return f})})}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(){let o=this._getQuery(),n=this.dialect.sqlToQuery(o.sql);return{query:o,builtQuery:n}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(o){return this.authToken=o,this}execute(){return Wo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class jy extends on{constructor(o,n,T,t){super();this.execute=o,this.sql=n,this.query=T,this.mapBatchResult=t}static[J]="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 qt{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[t,S]of Object.entries(this._.schema))this.query[t]=new ry(T.fullSchema,this._.schema,this._.tableNamesMap,T.fullSchema[t],S,o,n)}static[J]="PgDatabase";query;$with(o){let n=this;return{as(T){if(typeof T==="function")T=T(new vt(n.dialect));return new Proxy(new wt(T.getSQL(),T.getSelectedFields(),o,!0),new vo({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}$count(o,n){return new pt({source:o,filters:n,session:this.session})}with(...o){let n=this;function T(M){return new Tn({fields:M??void 0,session:n.session,dialect:n.dialect,withList:o})}function t(M){return new Tn({fields:M??void 0,session:n.session,dialect:n.dialect,withList:o,distinct:!0})}function S(M,F){return new Tn({fields:F??void 0,session:n.session,dialect:n.dialect,withList:o,distinct:{on:M}})}function f(M){return new uS(M,n.session,n.dialect,o)}function y(M){return new dS(M,n.session,n.dialect,o)}function A(M){return new eS(M,n.session,n.dialect,o)}return{select:T,selectDistinct:t,selectDistinctOn:S,update:f,insert:y,delete:A}}select(o){return new Tn({fields:o??void 0,session:this.session,dialect:this.dialect})}selectDistinct(o){return new Tn({fields:o??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(o,n){return new Tn({fields:n??void 0,session:this.session,dialect:this.dialect,distinct:{on:o}})}update(o){return new uS(o,this.session,this.dialect)}insert(o){return new dS(o,this.session,this.dialect)}delete(o){return new eS(o,this.session,this.dialect)}refreshMaterializedView(o){return new Ly(o,this.session,this.dialect)}authToken;execute(o){let n=typeof o==="string"?R.raw(o):o.getSQL(),T=this.dialect.sqlToQuery(n),t=this.session.prepareQuery(T,void 0,void 0,!1);return new jy(()=>t.execute(void 0,this.authToken),n,T,(S)=>t.mapResult(S,!0))}transaction(o,n){return this.session.transaction(o,n)}}class Gk{constructor(o,n){this.unique=o,this.name=n}static[J]="PgIndexBuilderOn";on(...o){return new aS(o.map((n)=>{if(X(n,r))return n;n=n;let T=new _t(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 aS(o.map((n)=>{if(X(n,r))return n;n=n;let T=new _t(n.name,!!n.keyAsName,n.columnType,n.indexConfig);return n.indexConfig=n.defaultConfig,T}),this.unique,!0,this.name)}using(o,...n){return new aS(n.map((T)=>{if(X(T,r))return T;T=T;let t=new _t(T.name,!!T.keyAsName,T.columnType,T.indexConfig);return T.indexConfig=JSON.parse(JSON.stringify(T.defaultConfig)),t}),this.unique,!0,this.name,o)}}class aS{static[J]="PgIndexBuilder";config;constructor(o,n,T,t,S="btree"){this.config={name:t,columns:o,unique:n,only:T,method:S}}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 zk(this.config,o)}}class zk{static[J]="PgIndex";config;constructor(o,n){this.config={...o,table:n}}}function Ny(o){return new Gk(!0,o)}class hy{constructor(o){this.query=o}authToken;getQuery(){return this.query}mapResult(o,n){return o}setToken(o){return this.authToken=o,this}static[J]="PgPreparedQuery";joinsNotNullableMap}class by{constructor(o){this.dialect=o}static[J]="PgSession";execute(o,n){return Wo.startActiveSpan("drizzle.operation",()=>{return Wo.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(o),void 0,void 0,!1)}).setToken(n).execute(void 0,n)})}all(o){return this.prepareQuery(this.dialect.sqlToQuery(o),void 0,void 0,!1).all()}async count(o,n){let T=await this.execute(o,n);return Number(T[0].count)}}class cy extends qt{constructor(o,n,T,t=0){super(o,n,T);this.schema=T,this.nestedIndex=t}static[J]="PgTransaction";rollback(){throw new af}getTransactionConfigSQL(o){let 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 Hk extends hy{constructor(o,n,T,t,S,f,y){super({sql:n,params:T});this.client=o,this.queryString=n,this.params=T,this.logger=t,this.fields=S,this._isResponseInArrayMode=f,this.customResultMapper=y}static[J]="PostgresJsPreparedQuery";async execute(o={}){return Wo.startActiveSpan("drizzle.execute",async(n)=>{let T=df(this.params,o);n?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(T)}),this.logger.logQuery(this.queryString,T);let{fields:t,queryString:S,client:f,joinsNotNullableMap:y,customResultMapper:A}=this;if(!t&&!A)return Wo.startActiveSpan("drizzle.driver.execute",()=>{return f.unsafe(S,T)});let M=await Wo.startActiveSpan("drizzle.driver.execute",()=>{return n?.setAttributes({"drizzle.query.text":S,"drizzle.query.params":JSON.stringify(T)}),f.unsafe(S,T).values()});return Wo.startActiveSpan("drizzle.mapResponse",()=>{return A?A(M):M.map((F)=>jM(t,F,y))})})}all(o={}){return Wo.startActiveSpan("drizzle.execute",async(n)=>{let T=df(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 Zt extends by{constructor(o,n,T,t={}){super(n);this.client=o,this.schema=T,this.options=t,this.logger=t.logger??new oy}static[J]="PostgresJsSession";logger;prepareQuery(o,n,T,t,S){return new Hk(this.client,o.sql,o.params,this.logger,n,t,S)}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)=>{let t=new Zt(T,this.dialect,this.schema,this.options),S=new xy(this.dialect,t,this.schema);if(n)await S.setTransaction(n);return o(S)})}}class xy extends cy{constructor(o,n,T,t=0){super(o,n,T,t);this.session=n}static[J]="PostgresJsTransaction";transaction(o){return this.session.client.savepoint((n)=>{let T=new Zt(n,this.dialect,this.schema,this.session.options),t=new xy(this.dialect,T,this.schema);return o(t)})}}class mk extends qt{static[J]="PostgresJsDatabase"}function ot(o,n={}){let T=(M)=>M;for(let M of["1184","1082","1083","1114"])o.options.parsers[M]=T,o.options.serializers[M]=T;o.options.serializers["114"]=T,o.options.serializers["3802"]=T;let t=new ET({casing:n.casing}),S;if(n.logger===!0)S=new sf;else if(n.logger!==!1)S=n.logger;let f;if(n.schema){let M=j$(n.schema,h$);f={fullSchema:n.schema,schema:M.tables,tableNamesMap:M.tableNamesMap}}let y=new Zt(o,t,f,{logger:S}),A=new mk(t,y,f);return A.$client=o,A}function sS(...o){if(typeof o[0]==="string"){let n=aT(o[0]);return ot(n,o[1])}if(bM(o[0])){let{connection:n,client:T,...t}=o[0];if(T)return ot(T,t);if(typeof n==="object"&&n.url!==void 0){let{url:f,...y}=n,A=aT(f,y);return ot(A,t)}let S=aT(n);return ot(S,t)}return ot(o[0],o[1])}((o)=>{function n(T){return ot({},T)}o.mock=n})(sS||(sS={}));var vy={};BJ(vy,{users:()=>YT,userChanges:()=>Z0,untrackedUserColumnNames:()=>q0,twoFactorMethod:()=>Bk,trackedUserColumnName:()=>Vk,trackableUserColumnNames:()=>Uk,role:()=>Dk,players:()=>iy,passwordResetAttempts:()=>g0,loginHistory:()=>P0,games:()=>of,banishedIps:()=>Pt});function Qk(o){return R`lower(${o})`}var Dk=WS("role",["admin","user"]),YT=TT("users",{id:kn().primaryKey().defaultRandom(),username:xo({length:16}).notNull(),email:xo({length:254}).notNull(),hash:xo({length:64}).notNull(),salt:xo({length:36}).notNull(),createdAt:Qn({withTimezone:!0}).notNull().defaultNow(),createdIp:xo({length:45}).notNull(),isActive:Gt().notNull().default(!1),verifiedAt:Qn({withTimezone:!0}),userRole:Dk().default("user")},(o)=>[Ny("usernameUniqueIndex").on(Qk(o.username)),Ny("emailUniqueIndex").on(Qk(o.email))]),q0=["id","createdAt","createdIp","isActive","salt","verifiedAt"],Uk=["username","email","hash","userRole"],Vk=WS("trackedUserColumnName",Uk),Z0=TT("userChanges",{id:kn().primaryKey().defaultRandom(),userId:kn().notNull().references(()=>YT.id),changedAt:Qn({withTimezone:!0}).notNull().defaultNow(),changedIp:xo({length:45}).notNull(),changedColumn:Vk().notNull(),oldValue:xo({length:255}),newValue:xo({length:255})}),of=TT("games",{id:kn().primaryKey().defaultRandom()}),iy=TT("players",{userId:kn().notNull().references(()=>YT.id),gameId:kn().notNull().references(()=>of.id),score:HS().notNull()},(o)=>[B$({name:"players_userId_gameId_pk",columns:[o.userId,o.gameId]})]),P0=TT("loginHistory",{id:kn().primaryKey().defaultRandom(),userId:kn().references(()=>YT.id),loginTime:Qn({withTimezone:!0}).notNull().defaultNow(),ipAddress:xo({length:45}).notNull(),userAgent:xo({length:1024}),successful:Gt().notNull().default(!1)}),Bk=WS("twoFactorMethod",["email","phone"]),g0=TT("passwordResetAttempts",{id:kn().primaryKey().defaultRandom(),userId:kn().notNull().references(()=>YT.id),requestedIp:xo({length:45}).notNull(),requestedAt:Qn({withTimezone:!0}).notNull().defaultNow(),succeededIp:xo({length:45}),succeededAt:Qn({withTimezone:!0}),verificationMethod:Bk().notNull()}),Pt=TT("banishedIps",{ip:xo({length:45}).primaryKey(),reason:xo({length:2048}).notNull(),banishedAt:Qn({withTimezone:!0}).notNull().defaultNow(),banishedUntil:Qn({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class py{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(l0.resolve(__dirname,"notify_update.sql"));let o=[_n(YT),_n(of),_n(iy)];await this.sql`SELECT create_notify_triggers(${this.sql.array(o)})`,await this.sql.listen("table_update",(n)=>{let T=n.split(","),t=T[0],S=T[1],f=`${t}("${S}")`;if(this.observers.has(f))this.observers.get(f).next(f)})}constructor(o=!1,n={host:Cn.POSTGRES_HOST,port:Cn.POSTGRES_PORT,user:Cn.POSTGRES_USER,password:Cn.POSTGRES_PASSWORD,database:Cn.POSTGRES_DATABASE}){this.options=n,this.sql=aT(n),this.drizzle=sS(this.sql,{schema:vy,logger:o})}observe(o,n){if(!this.observers.has(o))this.observers.set(o,new s);this.observers.get(o).subscribe("SINGLETON",n)}}var nf={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"},qy=tA(nf).map(([o])=>Go.literal(Number(o))),e0=Go.union([qy[0],qy[1],...qy]),Ck=Go.tuple([e0,Go.string()]);var Py=new jf,{logger:tn}=Py;Object.assign(console,tn,{log:tn.info});tn.info(" ready");var Zy=Ik(import.meta.dir,"..","app"),s0=new py({logQuery(o,n){tn.info("\uD83D\uDCDD query",o,n)}});a0({hostname:"0.0.0.0",port:Cn.FRONTEND_PORT??3333,...s$??void 0,async fetch(o,n){try{let T=new Date,t=new URL(o.url),S=n.requestIP(o)?.address??"??";tn.info(T,S,o.method,t.pathname);let[f]=await s0.drizzle.select({banishedUntil:Pt.banishedUntil}).from(Pt).where(IT(Pt.ip,S)).limit(1),y=f?.banishedUntil===null,A=f?.banishedUntil&&f.banishedUntil>T;if(y||A)throw tn.info(`\uD83D\uDE45 request from banned ip ${S}`),[403,S];if(t.pathname==="/")return new Response(Bun.file(Ik(Zy,"index.html")));if(t.pathname==="/index.html")return Response.redirect("/");let M=d0(Zy,t.pathname),F=u0(M);if(!F.startsWith(Zy))throw[403,"Access Denied"];if(!await Lk(F).exists())return Response.redirect("/");return new Response(Lk(F))}catch(T){let t=Ck.safeParse(T);if(t.success){let[S,f]=t.data,A=`${nf[S]}. ${f}`;return tn.info(`\u274C ${S}: ${A}`),new Response(A,{status:S})}if(T instanceof Error)tn.error(T.message);else{let S=VT(T);tn.error("frontend server threw",S)}return new Response(nf[500],{status:500})}}});function Tf(){tn.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{tn.info("\u2757 received SIGINT; exiting gracefully"),Tf()});process.on("SIGTERM",()=>{tn.info("\u2757 received SIGTERM; exiting gracefully"),Tf()});process.on("exit",()=>{tn.info("\u2757 received exit; exiting gracefully"),Tf()});Py.on("timeToStop",()=>{tn.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),Tf()});tn.info(`\uD83D\uDEEB frontend server running at http://localhost:${Cn.FRONTEND_PORT}/`);Py.emit("alive");
|