tempest.games 0.1.26 → 0.1.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,25 +1,25 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var mk=Object.create;var{getPrototypeOf:Qk,defineProperty:ff,getOwnPropertyNames:Dk}=Object;var Uk=Object.prototype.hasOwnProperty;var yW=(o,n,T)=>{T=o!=null?mk(Qk(o)):{};let t=n||!o||!o.__esModule?ff(T,"default",{value:o,enumerable:!0}):T;for(let S of Dk(o))if(!Uk.call(t,S))ff(t,S,{get:()=>o[S],enumerable:!0});return t};var AW=(o,n)=>()=>(n||o((n={exports:{}}).exports,n),n.exports);var Vk=(o,n)=>{for(var T in n)ff(o,T,{get:n[T],enumerable:!0,configurable:!0,set:(t)=>n[T]=()=>t})};import{join as tW,normalize as SW,resolve as LJ}from"path";function mT(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 JW(o){return Object.fromEntries(o)}function TA(o){return Object.entries(o)}var tA=(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 SA(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 yf 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 ${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=Sn(O,D,$);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 fA(o,n){if("mutable"in n)return ft(o,n);return jn(o,n)}function cn(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)=>cn(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 cn(o,n)}class gt{_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 gt([...this._buffer]);return o._index=this._index,o}}var Bk={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function QT(o,n){let T=l(n),t=`${o.key}(${T})`,S=Bk[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 vW=Symbol("provenance");function Af(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(Ck)){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 DT(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 Ck="T$";function UT(o){return yA(to.STORE,o)}function $T(o){return fA(to.STORE,o)}function Mf(...o){if(o.length===2)return fo(to.STORE,...o);return fo(to.STORE,...o)}var Ff=(o)=>(n,T,t,S,...f)=>{console[o](`${n} ${T} "${t}" ${S}`,...f)},Lk={error:Ff("error"),info:Ff("info"),warn:Ff("warn")};class $f{logLevel;filter;logger;constructor(o,n,T=Lk){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 lt(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 MA=(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 Ik=(o)=>o[0].toUpperCase()+o.slice(1);function zn(o){return o.type.split("_").map(Ik).join(" ")}class fn 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 an(o,n,T){return(...t)=>{let S=d(o,T);if(S)return S.run(t,n);throw new fn(o,T)}}var et=(o)=>(n)=>o instanceof Function?o(n):o;var sn=(o,n)=>{if(n.valueMap.has(o.key))return n.logger.info("\uD83D\uDCD6",o.type,o.key,"reading cached value"),FA(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 $A=(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)},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)},VT=(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 RA=(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 kf=(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(kA(T,S))continue;WA(S,T),VT(T,S)}}};function jk(o,n){if(_A(n.newValue))return!1;if(o.includes("\uD83D\uDD0D"))return!1;return!0}var OA=(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(!jk(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 wA=(o,n,T)=>{let t=sn(o,T),S=t;if(o.type==="mutable_atom"&&yo(T)){let{parent:y}=T;S=Jt(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),KA(o.key,T))XA(o.key,T);VT(T,o.key),kf(o,T);let f={oldValue:t,newValue:S};if(Bo(T))RA(o,f,T);else if(T.parent){if(T.on.transactionApplying.state===null)OA(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=Jt(A,$,T)}if(M.do(f.newValue)===null)kf(A,T)}}};var dt=(o,n,T)=>{switch(o.type){case"atom":case"mutable_atom":wA(o,n,T);break;case"selector":o.set(n);break}};function ut(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=ut(o,T)??null,t)S=T.family?ro(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=$A(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);dt(A,f,o),JA(o)}function at(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 EA(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 Of{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 Of(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 Q=this.toolkit.seek(E,K);if(Q)return Q;let x=this.store.molecules.get(l(K));if(x){let h=d(E,T);return Hn(x,h,T)}if(T.config.lifespan==="immortal")throw new fn(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,Q)=>{let{set:x}=E,h=this.retrieve(f,K),w=this.retrieve(f,Q);x(h,(v)=>v.add(Q)),x(w,(v)=>v.add(K))},M=(E,K,Q)=>{let{set:x}=E,h=this.retrieve(f,K),w=this.retrieve(f,Q),v,N;x(h,(q)=>{if(q.delete(Q),q.size===0)v=`"${K}"`;return q}),x(w,(q)=>{if(q.delete(K),q.size===0)N=`"${Q}"`;return q})},F=(E,K,Q)=>{let{get:x,set:h}=E,w=this.retrieve(f,K),v=x(w);for(let N of v){if(Q.includes(N))continue;let Jo=this.retrieve(f,N);h(Jo,(Oo)=>{return Oo.delete(K),Oo})}h(w,(N)=>{return N.transaction((q)=>{q.clear();for(let Jo of Q){let Oo=y(E,Jo),tn=Oo.has(K);if(this.relations.cardinality==="1:n"){let xn=[];for(let H of Oo){if(H===K)continue;let Z=y(E,H);if(Z.delete(Jo),Z.size===0)xn.push(H)}if(!tn&&Oo.size>0)Oo.clear();for(let H of xn){let Z=[Jo,H].sort(),Fo=`"${Z[0]}:${Z[1]}"`;this.molecules.delete(Fo)}}if(!tn)Oo.add(K);q.add(Jo)}return!0}),N})},$=(E,K,Q)=>{let{set:x}=E,h=this.retrieve(f,K);x(h,(w)=>{return w.transaction((v)=>{for(let N of Q)v.add(N);return!0}),w});for(let w of Q){let v=this.retrieve(f,w);x(v,(N)=>{return N.add(K),N})}return!0},W=(E,K,Q)=>{let x=y(E,K);return Q?x.has(Q):x.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=jn(T,{key:`${o.key}/content`,default:n},["join","content"]),z=EA(T,{key:`${o.key}/content-molecules`,new:class h{key;constructor(w,v){this.key=v}}});let E=({get:h},w)=>h(this.retrieve(D,w)),K=({set:h},w,v)=>{h(this.retrieve(D,w),v)},Q=(h,w)=>{let v=T.molecules.get(`"${w}"`);if(v)this.toolkit.dispose(v),this.molecules.delete(`"${w}"`)};G=Object.assign(O,{getContent:(h)=>{return E(this.toolkit,h)},setContent:(h,w)=>{K(this.toolkit,h,w)},deleteContent:(h)=>{Q(this.toolkit,h)}})}else G=O;let Y=new Fn(o,{externalStore:G,isAType:o.isAType,isBType:o.isBType,makeContentKey:(...E)=>{let K=E.sort(),Q=`${K[0]}:${K[1]}`,[x,h]=K.map((w)=>this.molecules.get(l(w)));if(T.config.lifespan==="immortal"&&x&&h){let w=U(T),v=pn(w,[x,h],z,Q);this.molecules.set(`"${Q}"`,d(v,w))}return Q}}),B=()=>cn(T,{key:`${o.key}/singleRelatedKey`,get:(E)=>({get:K})=>{let Q=this.retrieve(f,E),x=K(Q);for(let h of x)return h;return null}},["join","keys"]),p=()=>{return cn(T,{key:`${o.key}/multipleRelatedKeys`,get:(E)=>({get:K})=>{let Q=Wf(f,T),x=this.retrieve(Q,E);return K(x).members}},["join","keys"])},c=()=>cn(T,{key:`${o.key}/singleRelatedEntry`,get:(E)=>({get:K})=>{let Q=this.retrieve(f,E),x=K(Q);for(let h of x){let w=Y.isAType?.(E)?E:void 0,v=w===void 0?E:void 0;w??=h,v??=h;let N=Y.makeContentKey(w,v),q=this.retrieve(D,N),Jo=K(q);return[h,Jo]}return null}},["join","entries"]),a=()=>cn(T,{key:`${o.key}/multipleRelatedEntries`,get:(E)=>({get:K})=>{let Q=Wf(f,T),x=this.retrieve(Q,E);return K(x).members.map((w)=>{let v=Y.isAType?.(E)?E:void 0,N=v===void 0?E:void 0;v??=w,N??=w;let q=Y.makeContentKey(v,N),Jo=this.retrieve(D,q),Oo=K(Jo);return[w,Oo]})}},["join","entries"]);switch(o.cardinality){case"1:1":{let E=B(),K=`${t}KeyOf${Ho(S)}`,Q=`${S}KeyOf${Ho(t)}`,x={[K]:E,[Q]:E},h;if(n){let w=c(),v=`${t}EntryOf${Ho(S)}`,N=`${S}EntryOf${Ho(t)}`,q={[v]:w,[N]:w};h=Object.assign(x,q)}else h=x;this.relations=Y,this.states=h;break}case"1:n":{let E=B(),K=p(),Q=`${t}KeyOf${Ho(S)}`,x=`${S}KeysOf${Ho(t)}`,h={[Q]:E,[x]:K},w;if(n){let v=c(),N=a(),q=`${t}EntryOf${Ho(S)}`,Jo=`${S}EntriesOf${Ho(t)}`,Oo={[q]:v,[Jo]:N};w=Object.assign(h,Oo)}else w=h;this.relations=Y,this.states=w;break}default:{let E=p(),K=`${t}KeysOf${Ho(S)}`,Q=`${S}KeysOf${Ho(t)}`,x={[K]:E,[Q]:E},h;if(n){let w=a(),v=`${t}EntriesOf${Ho(S)}`,N=`${S}EntriesOf${Ho(t)}`,q={[v]:w,[N]:w};h=Object.assign(x,q)}else h=x;this.relations=Y,this.states=h}}}}function st(o,n,T=to.STORE){return Rf(T).set(o.key,new Of(o,n,T)),{key:o.key,type:"join",a:o.between[0],b:o.between[1],cardinality:o.cardinality}}function Rf(o){if("joins"in o&&o.joins instanceof Map)return o.joins;let n=new Map;return o.joins=n,n}function kt(o,n){let T=Rf(n),t=T.get(o.key);if(t===void 0){if(t=Rf(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 oS(o,n,T){let t=kt(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 YA(o,n){return oS(o,n,to.STORE)}function nS(o,n,T){let t=kt(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 rk(o,n){return kt(o,n).core.findRelatedKeysState}function GA(o){return rk(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=ut(o,T)??null,t)S=T.family?ro(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)??QT(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 fn(t,f,o)}}switch(T.type){case"atom":case"mutable_atom":case"selector":case"readonly_selector":return sn(d(T,o),o);case"molecule":return d(T,o).instance}}class DT{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 zA(o){return o[0].toUpperCase()+o.slice(1)}function pn(o,n,T,t,...S){let f=SA(o),y=U(o),A=l(t);y.moleculeInProgress=A;let M=Array.isArray(n)?n:[n],F=M.map((Y)=>{if(Y instanceof DT)return Y;let B=l(Y.key),p=o.molecules.get(B);if(!p)throw new Error(`Molecule ${B} not found in store "${o.config.name}"`);return p}),$=new DT(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=mT())=>an(Y,B,U(o)),make:(Y,B,p,...c)=>pn(U(f),Y,B,p,...c),dispose:(Y)=>{so(U(f),Y)},env:()=>TS(U(f)),bond:(Y,B)=>{if(Y.type==="join"){let{as:p}=B,c=kt(Y,f);c.molecules.set(A,$),$.joins.set(Y.key,c);let a=O.subject.subscribe(`join:${Y.key}-${A}`,(w)=>{if(w.type==="molecule_disposal"){if(l(w.token.key)===A)a(),c.molecules.delete(A)}});if(p===null)return;let E=Y.a===p?Y.b:Y.a,K=YA(Y,t),Q=K[`${E}KeysOf${zA(p)}`],x=K[`${E}EntriesOf${zA(p)}`],h={relatedKeys:Q};if(x)h=Object.assign(h,{relatedEntries:x});return h}return Hn($,d(Y,f),U(f))},claim:(Y,B)=>{let{exclusive:p}=B,c=U(o).molecules.get(l(Y.key));if(c)if(p){for(let a of c.above.values())a.below.delete(c.stringKey);c.above.clear(),c.above.set($.stringKey,$),$.below.set(c.stringKey,c)}else c.above.set($.stringKey,$),$.below.set(c.stringKey,c)},spawn:(Y,B,...p)=>pn(U(o),[$],d(Y,o),B,...p)},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 _f(o,n,T){switch(n){case"newValue":{HA(o,T);break}case"oldValue":{so(T,o.token);break}}}function wf(o,n,T){switch(n){case"newValue":{so(T,o.token);break}case"oldValue":{HA(o,T),T.valueMap.set(o.token.key,o.value);break}}}function HA(o,n){let{family:T}=o.token;if(T){let t=n.families.get(T.key);if(t)Ao(n,t,ro(T.subKey))}}function Kf(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":Af(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 Xf(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":{Af(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 tS(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":at(o,S,T);break;case"state_creation":_f(S,o,T);break;case"state_disposal":wf(S,o,T);break;case"molecule_creation":Kf(S,o,T);break;case"molecule_disposal":Xf(S,o,T);break;case"transaction_update":tS(o,S,T);break}}function mA(o,n,T){if(Bo(T)&&o)T.transactionMeta.epoch.set(o,n)}function QA(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 DA=(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),tS("newValue",T.transactionMeta.update,t),Bo(t))QA(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 UA(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 VA=(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=BA(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,$=mT())=>an(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=VA(o.key,f,n,y);try{let M=U(n),{toolkit:F}=A.transactionMeta,$=o.do(F,...f);return DA($,M),$}catch(M){throw MA(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 BA(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 CA{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 gt(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 yf(null),operationClose:new s,moleculeCreationStart:new s,moleculeCreationDone:new s,moleculeDisposal:new s};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new $f("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 CA({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 fn(o,n)}function SS(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")SS(F,n);else if(F.above.delete(T.stringKey),F.above.size===0)SS(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 fn(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=QT(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)??QT(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?`
3
+ var zR=Object.create;var{getPrototypeOf:mR,defineProperty:tt,getOwnPropertyNames:QR}=Object;var DR=Object.prototype.hasOwnProperty;var MW=(o,n,T)=>{T=o!=null?zR(mR(o)):{};let S=n||!o||!o.__esModule?tt(T,"default",{value:o,enumerable:!0}):T;for(let f of QR(o))if(!DR.call(S,f))tt(S,f,{get:()=>o[f],enumerable:!0});return S};var FW=(o,n)=>()=>(n||o((n={exports:{}}).exports,n),n.exports);var UR=(o,n)=>{for(var T in n)tt(o,T,{get:n[T],enumerable:!0,configurable:!0,set:(S)=>n[T]=()=>S})};var yW=import.meta.require;import{join as fW,normalize as tW,resolve as Ck}from"path";function mT(o=Math.random){return o().toString(36).slice(2)}class fS extends Promise{fate;resolve;reject;done=!1;constructor(o){let n,T;super((S,f)=>{n=S,T=f});this.resolve=n,this.reject=T,this.use(o instanceof Promise?o:new Promise(o))}pass(o,n){if(o===this.fate)this.resolve(n),this.done=!0}fail(o,n){if(o===this.fate)this.reject(n),this.done=!0}use(o){if(o instanceof Promise){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 nM(o){return Object.entries(o)}var TM=(o,n,T=So.STORE)=>{return En(T,{key:`${o.key}:JSON`,get:({get:S})=>n.toJson(S(o)),set:({set:S},f)=>{S(o,n.fromJson(f))}})};function D(o){while(o.child!==null)o=o.child;return o}function SM(o){while(o.parent!==null)o=o.parent;return o}class s{Subscriber;subscribers=new Map;subscribe(o,n){return this.subscribers.set(o,n),()=>{this.unsubscribe(o)}}unsubscribe(o){this.subscribers.delete(o)}next(o){let n=this.subscribers.values();for(let T of n)T(o)}}class At extends s{state;constructor(o){super();this.state=o}next(o){this.state=o,super.next(o)}}function jn(o,n,T){let S={key:n.key,type:"atom_family"},f=o.families.get(n.key);if(f)o.logger.error("\u2757","atom_family",n.key,`Overwriting an existing ${Hn(f)} "${f.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let t=new s,M=Object.assign((F)=>{let y=l(F),$={key:n.key,subKey:y},W=`${n.key}(${y})`,O=D(o),E=n.default,Q={key:W,default:E instanceof Function?E(F):E};if(n.effects)Q.effects=n.effects(F);let H=tn(O,Q,$);return t.next({type:"state_creation",token:H}),H},S,{subject:t,install:(F)=>jn(F,n),internalRoles:T});return o.families.set(n.key,M),o.defaults.set(n.key,n.default),S}function fM(o,n){if("mutable"in n)return tS(o,n);return jn(o,n)}function cn(o,n,T){let S={key:n.key,type:"readonly_selector_family"},f=o.families.get(n.key);if(f)o.logger.error("\u2757","readonly_selector_family",n.key,`Overwriting an existing ${Hn(f)} "${f.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let t=new s,M=Object.assign((F)=>{let y=l(F),$={key:n.key,subKey:y},W=`${n.key}(${y})`,O=D(o),E=AS(O,{key:W,get:n.get(F)},$);return t.next({type:"state_creation",token:E}),E},S,{internalRoles:T,subject:t,install:(F)=>cn(F,n),default:(F)=>{return n.get(F)({get:(...$)=>to(o,...$),find:($,W)=>Mo(o,$,W),seek:($,W)=>Go(o,$,W),json:($)=>Bo(o,$)})}});return o.families.set(n.key,M),S}function MS(o,n){if("set"in n)return FS(o,n);return cn(o,n)}class gS{_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 gS([...this._buffer]);return o._index=this._index,o}}var VR={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function QT(o,n){let T=l(n),S=`${o.key}(${T})`,f=VR[o.type],t={key:S,type:f};if(f==="molecule")Object.assign(t,{key:n,family:o});else Object.assign(t,{family:{key:o.key,subKey:T}});return Object.assign(t,{counterfeit:!0}),t}function lo(o){let n={key:o.key,type:o.type};if("family"in o)n.family=o.family;return n}var qW=Symbol("provenance");function Mt(o,n,T){let S=l(T);try{let f=[],t;if(n==="root")f.push(o.molecules.get('"root"')),t="all";else if(typeof n==="string"&&n.startsWith(BR)){t="any";let $=l(n),W=o.molecules.get($);if(!W)throw new Error(`Molecule ${$} not found in store "${o.config.name}"`);f.push(W)}else if(T.startsWith("T$--")){t="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}"`);f.push(E)}}else{t="any";let W=l(n),O=o.molecules.get(W);if(!O)throw new Error(`Molecule ${W} not found in store "${o.config.name}"`);f.push(O)}let A=new DT(f,T);A._dependsOn=t,o.molecules.set(S,A);for(let $ of f)$.below.set(A.stringKey,A);let M={type:"molecule_creation",subType:"modern",key:A.key,provenance:n},F=D(o);if(Ao(F)&&F.transactionMeta.phase==="building")F.transactionMeta.update.updates.push(M);else F.on.moleculeCreationStart.next(M)}catch(f){if(f instanceof Error)o.logger.error("\u274C","molecule",S,"allocation failed:",f.message)}return T}function yS(o,n){let T=l(n),S=o.molecules.get(T);if(!S)throw new Error(`Molecule ${T} not found in store "${o.config.name}"`);for(let y of S.joins.values())y.relations.delete(S.key),y.molecules.delete(S.stringKey);let f;if(S.above.size===1)f=S.above.values().next().value.key;else f=[...S.above.values()].map(({key:y})=>y);let t=[];for(let y of S.tokens.values()){let $=y.family;t.push([$.key,o.valueMap.get(y.key)])}for(let y of S.tokens.values())on(o,y);for(let y of S.below.values())if(y.dependsOn==="all")yS(o,y.key);else if(y.above.delete(S.stringKey),y.above.size===0)yS(o,y.key);S.below.clear();let A={type:"molecule_disposal",subType:"modern",key:S.key,values:t,provenance:f},M=D(o);if(Ao(M)&&M.transactionMeta.phase==="building")M.transactionMeta.update.updates.push(A);else M.on.moleculeDisposal.next(A);M.molecules.delete(S.stringKey);for(let y of S.above.values())y.below.delete(S.stringKey)}var BR="T$";function UT(o){return tM(So.STORE,o)}function $T(o){return fM(So.STORE,o)}function Ft(...o){if(o.length===2)return to(So.STORE,...o);return to(So.STORE,...o)}var yt=(o)=>(n,T,S,f,...t)=>{console[o](`${n} ${T} "${S}" ${f}`,...t)},CR={error:yt("error"),info:yt("info"),warn:yt("warn")};class $t{logLevel;filter;logger;constructor(o,n,T=CR){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 lS(o){return MS(So.STORE,o)}function $S(o){return kt(o,So.STORE)}class $n{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),S=this.relations.get(n);if(T)T.add(n);else T=new Set([n]),this.relations.set(o,T);if(S)S.add(o);else S=new Set([o]),this.relations.set(n,S)}deleteRelation(o,n){let T=this.relations.get(o);if(T){if(T.delete(n),T.size===0)this.relations.delete(o);let S=this.relations.get(n);if(S){if(S.delete(o),S.size===0)this.relations.delete(n)}}}replaceRelationsUnsafely(o,n){this.relations.set(o,new Set(n));for(let T of n){let S=new Set().add(o);this.relations.set(T,S)}}replaceRelationsSafely(o,n){let T=this.relations.get(o),S=this.isAType?.(o)?o:void 0,f=S===void 0?o:void 0;if(T)for(let t of T){S??=t,f??=t;let A=this.relations.get(t);if(A){if(A.size===1)this.relations.delete(t);else A.delete(o);this.contents.delete(this.makeContentKey(S,f))}}this.relations.set(o,new Set(n));for(let t of n){let A=this.relations.get(t);if(A)A.add(o);else A=new Set().add(o),this.relations.set(t,A)}}getContentInternal(o){return this.contents.get(o)}setContent(o,n){this.contents.set(o,n)}deleteContent(o){this.contents.delete(o)}constructor(o,n){if(this.a=o.between[0],this.b=o.between[1],this.cardinality=o.cardinality,!n?.externalStore)this.relations=new Map(o.relations?.map(([T,S])=>[T,new Set(S)])),this.contents=new Map(o.contents);if(this.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=(S,f)=>T.has(S,f),this.addRelation=(S,f)=>{T.addRelation(S,f)},this.deleteRelation=(S,f)=>{T.deleteRelation(S,f)},this.replaceRelationsSafely=(S,f)=>{T.replaceRelationsSafely(S,f)},this.replaceRelationsUnsafely=(S,f)=>{T.replaceRelationsUnsafely(S,f)},this.getRelatedKeys=(S)=>T.getRelatedKeys(S),T.getContent)this.getContentInternal=(S)=>{return T.getContent(S)},this.setContent=(S,f)=>{T.setContent(S,f)},this.deleteContent=(S)=>{T.deleteContent(S)};for(let[S,f]of o.relations??[]){let t=this.isAType?.(S)?S:void 0,A=t===void 0?S:void 0;for(let M of f)t??=M,A??=M,this.addRelation(t,A)}for(let[S,f]of o.contents??[])this.setContent(S,f)}if(n?.warn)this.warn=n.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([o,n])=>[o,[...n]]),contents:[...this.contents.entries()]}}set(o,...n){let T=typeof n[0]==="string"?n[0]:o[this.b],S=n[1]??typeof n[0]==="string"?void 0:n[0];switch(o=typeof o==="string"?o:o[this.a],this.cardinality){case"1:1":{let f=this.getRelatedKey(o);if(f&&f!==T)this.delete(o,f)}case"1:n":{let f=this.getRelatedKey(T);if(f&&f!==o)this.delete(f,T)}}if(S){let f=this.makeContentKey(o,T);this.setContent(f,S)}return this.addRelation(o,T),this}delete(o,n){n=typeof n==="string"?n:o[this.b];let T=typeof o==="string"?o:o[this.a];if(T===void 0&&typeof n==="string"){let S=this.getRelatedKeys(n);if(S)for(let f of S)this.delete(f,n)}if(typeof T==="string"&&n===void 0){let S=this.getRelatedKeys(T);if(S)for(let f of S)this.delete(T,f)}if(typeof T==="string"&&typeof n==="string"){this.deleteRelation(T,n);let S=this.makeContentKey(T,n);this.deleteContent(S)}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((S)=>`"${S}"`).join(", ")}). Only one related key was expected.`);let T;for(let S of n){T=S;break}return T}}replaceRelations(o,n,T){let S=!Array.isArray(n),f=S?Object.keys(n):n;if(T?.reckless)this.replaceRelationsUnsafely(o,f);else this.replaceRelationsSafely(o,f);if(S)for(let t of f){let A=this.makeContentKey(o,t),M=n[t];this.setContent(A,M)}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 S=this.getRelatedKeys(n);if(S)return[...S].map((f)=>{return[f,this.getContent(n,f)]})}if(n===void 0&&T!==void 0){let S=this.getRelatedKeys(T);if(S)return[...S].map((f)=>{return[f,this.getContent(f,T)]})}return[]}has(o,n){if(n)return this.getRelatedKeys(o)?.has(n)??!1;return this.relations.has(o)}}function Co(o){return"epoch"in o.transactionMeta}function Ao(o){return"phase"in o.transactionMeta}var MM=(o)=>{let n=D(o);if(!Ao(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 LR=(o)=>o[0].toUpperCase()+o.slice(1);function Hn(o){return o.type.split("_").map(LR).join(" ")}class An 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 S=o[1];super(`${Hn(n)} "${n.key}" member ${l(S)} not found in store "${T.config.name}".`)}}}function an(o,n,T){return(...S)=>{let f=d(o,T);if(f)return f.run(S,n);throw new An(o,T)}}var eS=(o)=>(n)=>o instanceof Function?o(n):o;var sn=(o,n)=>{if(n.valueMap.has(o.key))return n.logger.info("\uD83D\uDCD6",o.type,o.key,"reading cached value"),FM(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 yM=(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}"${!Ao(o)?"":` ${o.transactionMeta.phase} "${o.transactionMeta.update.key}"`}`)},$M=(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)},kM=(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)},VT=(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 RM=(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 Rt=(o,n)=>{let T=D(n),S=T.selectorAtoms.getRelatedKeys(o.key);if(T.logger.info("\uD83E\uDDF9",o.type,o.key,S?`evicting ${S.size} states downstream:`:"no downstream states",S??"to evict"),S){if(T.operation.open)T.logger.info("\uD83E\uDDF9",o.type,o.key,`[ ${[...T.operation.done].join(", ")} ] already done`);for(let f of S){if(kM(T,f))continue;JM(f,T),VT(T,f)}}};function IR(o,n){if(OM(n.newValue))return!1;if(o.includes("\uD83D\uDD0D"))return!1;return!0}var WM=(o,n,T)=>{let{key:S}=o,f=D(T);if(!Ao(f)||f.transactionMeta.phase!=="building"){T.logger.error("\uD83D\uDC1E","atom",S,"stowUpdate called outside of a transaction. This is probably a bug.");return}if(!IR(S,n))return;let A={type:"atom_update",key:S,...n};if(o.family)A.family=o.family;f.transactionMeta.update.updates.push(A),T.logger.info("\uD83D\uDCC1","atom",S,"stowed (",n.oldValue,"->",n.newValue,")")};var _M=(o,n,T)=>{let S=sn(o,T),f=S;if(o.type==="mutable_atom"&&Ao(T)){let{parent:A}=T;f=kS(o,A,T)}if(f=eS(n)(f),T.logger.info("\uD83D\uDCDD","atom",o.key,"set to",f),f=On(o.key,f,o.subject,T),wM(o.key,T))KM(o.key,T);VT(T,o.key),Rt(o,T);let t={oldValue:S,newValue:f};if(Co(T))RM(o,t,T);else if(T.parent){if(T.on.transactionApplying.state===null)WM(o,t,T);else if(o.key.startsWith("*")){let A=o.key.slice(1),M=T.atoms.get(A),F=T.valueMap.get(A);if(M.type==="mutable_atom"&&Ao(T)){let{parent:$}=T;F=kS(M,$,T)}if(F.do(t.newValue)===null)Rt(M,T)}}};var dS=(o,n,T)=>{switch(o.type){case"atom":case"mutable_atom":_M(o,n,T);break;case"selector":o.set(n);break}};function uS(o,n){if(n.family){let T=o.families.get(n.family.key);if(T)return T}}function Qo(o,...n){let T,S,f,t;if(n.length===2){if(T=n[0],t=n[1],S=uS(o,T)??null,S)f=T.family?ho(T.family.subKey):null,T=Mo(o,S,f)}else S=n[0],f=n[1],t=n[2],T=Mo(o,S,f);if("counterfeit"in T){let F=o.disposalTraces.buffer.find((y)=>y?.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}".`,F?`This state was previously disposed:
4
+ ${F.trace}`:"No previous disposal trace was found.");return}let A=yM(o,T);if(A){let F=o.on.operationClose.subscribe(`waiting to set "${T.key}" at T-${A}`,()=>{F(),o.logger.info("\uD83D\uDFE2",T.type,T.key,`resuming deferred setState from T-${A}`),Qo(o,T,t)});return}let M=d(T,o);dS(M,t,o),$M(o)}function aS(o,n,T){let{key:S,newValue:f,oldValue:t}=n,A=o==="newValue"?f:t,M={key:S,type:"atom"};if(n.family)Object.assign(M,{family:n.family});Qo(T,M,A)}function XM(o,n){let T=new s,S={type:"molecule_family",key:n.key,dependsOn:n.dependsOn??"all"},f={...S,subject:T,new:n.new};return o.moleculeFamilies.set(n.key,f),S}function zn(o,n,T){let S=vn(T,n,o.key);o.tokens.set(S.key,S);let f=Ao(T)&&T.transactionMeta.phase==="building",t=T.moleculeInProgress===o.key;if(!f&&!t)o.subject.next({type:"state_creation",token:S});return S}class bo extends Set{mode="record";subject=new s;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(o,n=0){super(o);if(o instanceof bo)this.parent=o,this.cacheUpdateNumber=o.cacheUpdateNumber;if(n)this.cacheLimit=n,this.cache=new Array(n),this.subscribe("auto cache",(T)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=T})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(o){let n=new bo(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 bo(this);let n=this.child._subscribe("transaction",(T)=>{this.transactionUpdates?.push(T)});try{if(o(this.child)){for(let S of this.transactionUpdates)this.doStep(S);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(T){throw console.error("Failed to apply transaction to SetRTX:",T),T}finally{n(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(o,n){return this.subject.subscribe(o,n)}subscribe(o,n){return this.subject.subscribe(o,(T)=>{n(`${this.cacheUpdateNumber}=${T}`)})}emit(o){this.subject.next(o)}doStep(o){let n=o.indexOf(":"),T=o.substring(0,n),S=o.substring(n+1);switch(T){case"add":this.add(JSON.parse(S));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(S));break;case"tx":for(let f of S.split(";"))this.doStep(f)}}getUpdateNumber(o){let n=o.indexOf("=");return Number(o.substring(0,n))}do(o){let n=o.indexOf("="),T=Number(o.substring(0,n)),S=T-this.cacheUpdateNumber;if(S>0){if(S===1){this.mode="playback";let t=o.substring(n+1);return this.doStep(t),this.mode="record",this.cacheUpdateNumber=T,null}return this.cacheUpdateNumber+1}if(Math.abs(S)<this.cacheLimit){let t=this.cacheIdx+S;if(this.cache[t]===o)return null;this.mode="playback";let M=!1;while(!M){this.cacheIdx%=this.cacheLimit;let y=this.cache[this.cacheIdx];if(this.cacheIdx--,!y)return"OUT_OF_RANGE";this.undo(y),M=this.cacheIdx===t-1}let F=o.substring(n+1);return this.doStep(F),this.mode="record",this.cacheUpdateNumber=T,null}return"OUT_OF_RANGE"}undoStep(o){let n=o.indexOf(":"),T=o.substring(0,n),S=o.substring(n+1);switch(T){case"add":this.delete(JSON.parse(S));break;case"del":this.add(JSON.parse(S));break;case"clear":{let f=JSON.parse(S);for(let t of f)this.add(t);break}case"tx":{let f=S.split(";");for(let t=f.length-1;t>=0;t--)this.undoStep(f[t])}}}undo(o){let n=o.indexOf("=");if(Number(o.substring(0,n))===this.cacheUpdateNumber){this.mode="playback";let S=o.substring(n+1);return this.undoStep(S),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function zo(o){return o[0].toUpperCase()+o.slice(1)}class Ot{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 S=new Ot(this.options,this.defaultContent,o);return this.alternates.set(n,S),S.alternates=this.alternates,S}constructor(o,n,T=So.STORE){this.store=T,this.options=o,this.defaultContent=n,this.alternates=new Map,this.alternates.set(T.config.name,this),this.store.miscResources.set(`join:${o.key}`,this),this.retrieve=(X,G)=>{let U=this.toolkit.seek(X,G);if(U)return U;let v=this.store.molecules.get(l(G));if(v){let c=d(X,T);return zn(v,c,T)}if(T.config.lifespan==="immortal")throw new An(X,G,T);return vn(T,X,G)},this.toolkit={get:(...X)=>to(T,...X),set:(...X)=>{Qo(T,...X)},find:this.retrieve,seek:(...X)=>Go(T,...X),json:(X)=>Bo(T,X),dispose:(...X)=>{on(T,...X)}};let S=o.between[0],f=o.between[1],t=tS(T,{key:`${o.key}/relatedKeys`,default:()=>new bo,mutable:!0,fromJson:(X)=>bo.fromJSON(X),toJson:(X)=>X.toJSON()},["join","relations"]);this.core={findRelatedKeysState:t};let A=({get:X},G)=>X(this.retrieve(t,G)),M=(X,G,U)=>{let{set:v}=X,c=this.retrieve(t,G),w=this.retrieve(t,U);v(c,(q)=>q.add(U)),v(w,(q)=>q.add(G))},F=(X,G,U)=>{let{set:v}=X,c=this.retrieve(t,G),w=this.retrieve(t,U),q,r;v(c,(p)=>{if(p.delete(U),p.size===0)q=`"${G}"`;return p}),v(w,(p)=>{if(p.delete(G),p.size===0)r=`"${U}"`;return p})},y=(X,G,U)=>{let{get:v,set:c}=X,w=this.retrieve(t,G),q=v(w);for(let r of q){if(U.includes(r))continue;let ko=this.retrieve(t,r);c(ko,(Oo)=>{return Oo.delete(G),Oo})}c(w,(r)=>{return r.transaction((p)=>{p.clear();for(let ko of U){let Oo=A(X,ko),fn=Oo.has(G);if(this.relations.cardinality==="1:n"){let xn=[];for(let z of Oo){if(z===G)continue;let Z=A(X,z);if(Z.delete(ko),Z.size===0)xn.push(z)}if(!fn&&Oo.size>0)Oo.clear();for(let z of xn){let Z=[ko,z].sort(),yo=`"${Z[0]}:${Z[1]}"`;this.molecules.delete(yo)}}if(!fn)Oo.add(G);p.add(ko)}return!0}),r})},$=(X,G,U)=>{let{set:v}=X,c=this.retrieve(t,G);v(c,(w)=>{return w.transaction((q)=>{for(let r of U)q.add(r);return!0}),w});for(let w of U){let q=this.retrieve(t,w);v(q,(r)=>{return r.add(G),r})}return!0},W=(X,G,U)=>{let v=A(X,G);return U?v.has(U):v.size>0},O={getRelatedKeys:(X)=>A(this.toolkit,X),addRelation:(X,G)=>{M(this.toolkit,X,G)},deleteRelation:(X,G)=>{F(this.toolkit,X,G)},replaceRelationsSafely:(X,G)=>{y(this.toolkit,X,G)},replaceRelationsUnsafely:(X,G)=>{$(this.toolkit,X,G)},has:(X,G)=>W(this.toolkit,X,G)},E,Q,H;if(n){Q=jn(T,{key:`${o.key}/content`,default:n},["join","content"]),H=XM(T,{key:`${o.key}/content-molecules`,new:class c{key;constructor(w,q){this.key=q}}});let X=({get:c},w)=>c(this.retrieve(Q,w)),G=({set:c},w,q)=>{c(this.retrieve(Q,w),q)},U=(c,w)=>{let q=T.molecules.get(`"${w}"`);if(q)this.toolkit.dispose(q),this.molecules.delete(`"${w}"`)};E=Object.assign(O,{getContent:(c)=>{return X(this.toolkit,c)},setContent:(c,w)=>{G(this.toolkit,c,w)},deleteContent:(c)=>{U(this.toolkit,c)}})}else E=O;let Y=new $n(o,{externalStore:E,isAType:o.isAType,isBType:o.isBType,makeContentKey:(...X)=>{let G=X.sort(),U=`${G[0]}:${G[1]}`,[v,c]=G.map((w)=>this.molecules.get(l(w)));if(T.config.lifespan==="immortal"&&v&&c){let w=D(T),q=qn(w,[v,c],H,U);this.molecules.set(`"${U}"`,d(q,w))}return U}}),B=()=>cn(T,{key:`${o.key}/singleRelatedKey`,get:(X)=>({get:G})=>{let U=this.retrieve(t,X),v=G(U);for(let c of v)return c;return null}},["join","keys"]),j=()=>{return cn(T,{key:`${o.key}/multipleRelatedKeys`,get:(X)=>({get:G})=>{let U=Wt(t,T),v=this.retrieve(U,X);return G(v).members}},["join","keys"])},b=()=>cn(T,{key:`${o.key}/singleRelatedEntry`,get:(X)=>({get:G})=>{let U=this.retrieve(t,X),v=G(U);for(let c of v){let w=Y.isAType?.(X)?X:void 0,q=w===void 0?X:void 0;w??=c,q??=c;let r=Y.makeContentKey(w,q),p=this.retrieve(Q,r),ko=G(p);return[c,ko]}return null}},["join","entries"]),a=()=>cn(T,{key:`${o.key}/multipleRelatedEntries`,get:(X)=>({get:G})=>{let U=Wt(t,T),v=this.retrieve(U,X);return G(v).members.map((w)=>{let q=Y.isAType?.(X)?X:void 0,r=q===void 0?X:void 0;q??=w,r??=w;let p=Y.makeContentKey(q,r),ko=this.retrieve(Q,p),Oo=G(ko);return[w,Oo]})}},["join","entries"]);switch(o.cardinality){case"1:1":{let X=B(),G=`${S}KeyOf${zo(f)}`,U=`${f}KeyOf${zo(S)}`,v={[G]:X,[U]:X},c;if(n){let w=b(),q=`${S}EntryOf${zo(f)}`,r=`${f}EntryOf${zo(S)}`,p={[q]:w,[r]:w};c=Object.assign(v,p)}else c=v;this.relations=Y,this.states=c;break}case"1:n":{let X=B(),G=j(),U=`${S}KeyOf${zo(f)}`,v=`${f}KeysOf${zo(S)}`,c={[U]:X,[v]:G},w;if(n){let q=b(),r=a(),p=`${S}EntryOf${zo(f)}`,ko=`${f}EntriesOf${zo(S)}`,Oo={[p]:q,[ko]:r};w=Object.assign(c,Oo)}else w=c;this.relations=Y,this.states=w;break}default:{let X=j(),G=`${S}KeysOf${zo(f)}`,U=`${f}KeysOf${zo(S)}`,v={[G]:X,[U]:X},c;if(n){let w=a(),q=`${S}EntriesOf${zo(f)}`,r=`${f}EntriesOf${zo(S)}`,p={[q]:w,[r]:w};c=Object.assign(v,p)}else c=v;this.relations=Y,this.states=c}}}}function sS(o,n,T=So.STORE){return Jt(T).set(o.key,new Ot(o,n,T)),{key:o.key,type:"join",a:o.between[0],b:o.between[1],cardinality:o.cardinality}}function Jt(o){if("joins"in o&&o.joins instanceof Map)return o.joins;let n=new Map;return o.joins=n,n}function RS(o,n){let T=Jt(n),S=T.get(o.key);if(S===void 0){if(S=Jt(So.STORE).get(o.key)?.in(n),S===void 0)throw new Error(`Join "${o.key}" not found in store "${n.config.name}"`);T.set(o.key,S)}return S}function of(o,n,T){let S=RS(o,T),f;switch(o.cardinality){case"1:1":{let t=`${o.a}KeyOf${zo(o.b)}`,A=`${o.b}KeyOf${zo(o.a)}`;f={get[t](){let F=S.states[t];return S.retrieve(F,n)},get[A](){let F=S.states[A];return S.retrieve(F,n)}};let M=`${o.a}EntryOf${zo(o.b)}`;if(M in S.states){let F=`${o.b}EntryOf${zo(o.a)}`;Object.assign(f,{get[M](){let y=S.states[M];return S.retrieve(y,n)},get[F](){let y=S.states[F];return S.retrieve(y,n)}})}break}case"1:n":{let t=`${o.a}KeyOf${zo(o.b)}`,A=`${o.b}KeysOf${zo(o.a)}`;f={get[t](){let F=S.states[t];return S.retrieve(F,n)},get[A](){let F=S.states[A];return S.retrieve(F,n)}};let M=`${o.a}EntryOf${zo(o.b)}`;if(M in S.states){let F=`${o.b}EntriesOf${zo(o.a)}`;Object.assign(f,{get[M](){let y=S.states[M];return S.retrieve(y,n)},get[F](){let y=S.states[F];return S.retrieve(y,n)}})}break}case"n:n":{let t=`${o.a}KeysOf${zo(o.b)}`,A=`${o.b}KeysOf${zo(o.a)}`;f={get[t](){let F=S.states[t];return S.retrieve(F,n)},get[A](){let F=S.states[A];return S.retrieve(F,n)}};let M=`${o.a}EntriesOf${zo(o.b)}`;if(M in S.states){let F=`${o.b}EntriesOf${zo(o.a)}`;Object.assign(f,{get[M](){let y=S.states[M];return S.retrieve(y,n)},get[F](){let y=S.states[F];return S.retrieve(y,n)}})}}}return f}function YM(o,n){return of(o,n,So.STORE)}function nf(o,n,T){let S=RS(o,T),f=D(T);if(Ao(f)){let{toolkit:t}=f.transactionMeta;S.transact(t,({relations:A})=>{n(A)})}else n(S.relations)}function jR(o,n){return RS(o,n).core.findRelatedKeysState}function GM(o){return jR(o,So.STORE)}function Tf(o){return{store:o}}function to(o,...n){let T,S,f;if(n.length===1){if(T=n[0],T.type!=="molecule"){if(S=uS(o,T)??null,S)f=T.family?ho(T.family.subKey):null,T=Mo(o,S,f)}}else{S=n[0],f=n[1];let t;if(S.type==="molecule_family")t=Go(o,S,f)??QT(S,f);else t=Mo(o,S,f);T=t}if("counterfeit"in T&&"family"in T){S=T.type==="molecule"?d(T.family,o):o.families.get(T.family.key);let t=T.type==="molecule"?T.key:T.family.subKey,A=o.disposalTraces.buffer.find((M)=>M?.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}".`,A?`This state was previously disposed:
5
+ ${A.trace}`:"No previous disposal trace was found."),S.type){case"atom_family":case"mutable_atom_family":return o.defaults.get(S.key);case"selector_family":case"readonly_selector_family":{if(o.defaults.has(S.key))return o.defaults.get(T.family.key);let M=d(S,o).default(t);return o.defaults.set(S.key,M),M}case"molecule_family":throw new An(S,t,o)}}switch(T.type){case"atom":case"mutable_atom":case"selector":case"readonly_selector":return sn(d(T,o),o);case"molecule":return d(T,o).instance}}class DT{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 S of o)this.above.set(S.stringKey,S)}}function EM(o){return o[0].toUpperCase()+o.slice(1)}function qn(o,n,T,S,...f){let t=SM(o),A=D(o),M=l(S);A.moleculeInProgress=M;let F=Array.isArray(n)?n:[n],y=F.map((Y)=>{if(Y instanceof DT)return Y;let B=l(Y.key),j=o.molecules.get(B);if(!j)throw new Error(`Molecule ${B} not found in store "${o.config.name}"`);return j}),$=new DT(y,S,T);A.molecules.set(M,$);for(let Y of y)Y.below.set($.stringKey,$);let W={get:(...Y)=>to(D(t),...Y),set:(...Y)=>{Qo(D(t),...Y)},seek:(Y,B)=>Go(D(t),Y,B),json:(Y)=>Bo(D(t),Y),run:(Y,B=mT())=>an(Y,B,D(o)),make:(Y,B,j,...b)=>qn(D(t),Y,B,j,...b),dispose:(Y)=>{on(D(t),Y)},env:()=>Tf(D(t)),bond:(Y,B)=>{if(Y.type==="join"){let{as:j}=B,b=RS(Y,t);b.molecules.set(M,$),$.joins.set(Y.key,b);let a=O.subject.subscribe(`join:${Y.key}-${M}`,(w)=>{if(w.type==="molecule_disposal"){if(l(w.token.key)===M)a(),b.molecules.delete(M)}});if(j===null)return;let X=Y.a===j?Y.b:Y.a,G=YM(Y,S),U=G[`${X}KeysOf${EM(j)}`],v=G[`${X}EntriesOf${EM(j)}`],c={relatedKeys:U};if(v)c=Object.assign(c,{relatedEntries:v});return c}return zn($,d(Y,t),D(t))},claim:(Y,B)=>{let{exclusive:j}=B,b=D(o).molecules.get(l(Y.key));if(b)if(j){for(let a of b.above.values())a.below.delete(b.stringKey);b.above.clear(),b.above.set($.stringKey,$),$.below.set(b.stringKey,b)}else b.above.set($.stringKey,$),$.below.set(b.stringKey,b)},spawn:(Y,B,...j)=>qn(D(o),[$],d(Y,o),B,...j)},O=d(T,o),E=O.new;$.instance=new E(W,S,...f);let Q={type:"molecule",key:S,family:T},H={type:"molecule_creation",subType:"classic",token:Q,family:T,context:F,params:f};if(Co(A))O.subject.next(H);else if(Ao(A)&&A.on.transactionApplying.state===null)A.transactionMeta.update.updates.push(H);return A.moleculeInProgress=null,Q}function _t(o,n,T){switch(n){case"newValue":{HM(o,T);break}case"oldValue":{on(T,o.token);break}}}function wt(o,n,T){switch(n){case"newValue":{on(T,o.token);break}case"oldValue":{HM(o,T),T.valueMap.set(o.token.key,o.value);break}}}function HM(o,n){let{family:T}=o.token;if(T){let S=n.families.get(T.key);if(S)Mo(n,S,ho(T.subKey))}}function Kt(o,n,T){switch(n){case"newValue":switch(o.subType){case"classic":qn(T,o.context,o.family,o.token.key,...o.params);break;case"modern":Mt(T,o.provenance,o.key);break}break;case"oldValue":switch(o.subType){case"classic":on(T,o.token);break;case"modern":yS(T,o.key);break}break}}function Xt(o,n,T){switch(n){case"newValue":switch(o.subType){case"classic":on(T,o.token);break;case"modern":yS(T,o.key);break}break;case"oldValue":switch(o.subType){case"classic":{let S=qn(T,o.context,o.family,o.token.key);for(let[f,t]of o.values){let A=`${f}(${l(S.key)})`,M=d(S,T),F=M.tokens.has(A),y=T.families.get(f);if(y&&!F)zn(M,y,T);T.valueMap.set(A,t)}}break;case"modern":{Mt(T,o.provenance,o.key);for(let[S,f]of o.values){let t=T.families.get(S);if(t){Mo(T,t,o.key);let A=`${S}(${l(o.key)})`;T.valueMap.set(A,f)}}}}break}}function Sf(o,n,T){let S=o==="newValue"?n.updates:[...n.updates].reverse();for(let f of S)switch(f.type){case"atom_update":case"selector_update":aS(o,f,T);break;case"state_creation":_t(f,o,T);break;case"state_disposal":wt(f,o,T);break;case"molecule_creation":Kt(f,o,T);break;case"molecule_disposal":Xt(f,o,T);break;case"transaction_update":Sf(o,f,T);break}}function zM(o,n,T){if(Co(T)&&o)T.transactionMeta.epoch.set(o,n)}function mM(o,n,T){if(!Co(T))return;let f=T.transactionMeta.actionContinuities.getRelatedKey(o);if(f!==void 0)T.transactionMeta.epoch.set(f,n)}var QM=(o,n)=>{let T=D(n),{parent:S}=T;if(S===null||!Ao(T)||T.transactionMeta?.phase!=="building"){n.logger.warn("\uD83D\uDC1E","transaction","???","applyTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}T.transactionMeta.phase="applying",T.transactionMeta.update.output=o,S.child=null,S.on.transactionApplying.next(T.transactionMeta);let{updates:f}=T.transactionMeta.update;if(n.logger.info("\uD83D\uDEC4","transaction",T.transactionMeta.update.key,`Applying transaction with ${f.length} updates:`,f),Sf("newValue",T.transactionMeta.update,S),Co(S))mM(T.transactionMeta.update.key,T.transactionMeta.update.epoch,S),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(Ao(S))S.transactionMeta.update.updates.push(T.transactionMeta.update);S.on.transactionApplying.next(null)};function DM(o,n,T){if(!Co(T))return;let{epoch:f,actionContinuities:t}=T.transactionMeta;if(t.set(o,n),!f.has(o))f.set(o,-1)}class _n 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 UM=(o,n,T,S)=>{let f=D(T),t={parent:f,child:null,on:f.on,loggers:f.loggers,logger:f.logger,config:f.config,atoms:new _n(f.atoms),atomsThatAreDefault:new Set(f.atomsThatAreDefault),families:new _n(f.families),operation:{open:!1},readonlySelectors:new _n(f.readonlySelectors),timelines:new _n(f.timelines),timelineTopics:new $n(f.timelineTopics.toJSON()),trackers:new Map,transactions:new _n(f.transactions),selectorAtoms:new $n(f.selectorAtoms.toJSON()),selectorGraph:new $n(f.selectorGraph.toJSON(),{makeContentKey:(...y)=>y.sort().join(":")}),selectors:new _n(f.selectors),valueMap:new _n(f.valueMap),defaults:f.defaults,disposalTraces:T.disposalTraces.copy(),molecules:new _n(f.molecules),moleculeFamilies:new _n(f.moleculeFamilies),moleculeInProgress:f.moleculeInProgress,miscResources:new _n(f.miscResources)},A=VM(o,T),M={phase:"building",update:{type:"transaction_update",key:o,id:S,epoch:A===void 0?Number.NaN:A+1,updates:[],params:n,output:void 0},toolkit:{get:(...y)=>to(F,...y),set:(...y)=>{Qo(F,...y)},run:(y,$=mT())=>an(y,$,F),find:(y,$)=>Mo(F,y,$),seek:(y,$)=>Go(F,y,$),json:(y)=>Bo(F,y),make:(y,$,W,...O)=>qn(F,y,$,W,...O),dispose:(...y)=>{on(F,...y)},env:()=>Tf(F)}},F=Object.assign(t,{transactionMeta:M});return f.child=F,T.logger.info("\uD83D\uDEEB","transaction",o,"Building transaction with params:",n),F};function kt(o,n){let T={key:o.key,type:"transaction",run:(t,A)=>{let M=UM(o.key,t,n,A);try{let F=D(n),{toolkit:y}=M.transactionMeta,$=o.do(y,...t);return QM($,F),$}catch(F){throw MM(S),n.logger.warn("\uD83D\uDCA5","transaction",o.key,"caught:",F),F}},install:(t)=>kt(o,t),subject:new s},S=D(n);S.transactions.set(T.key,T);let f=lo(T);return n.on.transactionCreation.next(f),f}function VM(o,n){let T=Co(n),S=T?n.transactionMeta.actionContinuities.getRelatedKey(o):void 0;return T&&S!==void 0?n.transactionMeta.epoch.get(S):void 0}class BM{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;selectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new $n({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new $n({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 $n({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new $n({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new gS(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 At(null),operationClose:new s,moleculeCreationStart:new s,moleculeCreationDone:new s,moleculeDisposal:new s};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new $t("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},Co(n))this.transactionMeta={epoch:new Map(n?.transactionMeta.epoch),actionContinuities:new $n(n?.transactionMeta.actionContinuities.toJSON())};for(let[,S]of n.families){if(S.internalRoles?.includes("mutable")||S.internalRoles?.includes("join"))continue;S.install(this)}let T=new Set;for(let[,S]of n.atoms){if(T.has(S.key))continue;if(S.install(this),S.type==="mutable_atom"){let f=Bo(n,S),t=pn(S);T.add(f.key),T.add(t.key)}}for(let[,S]of n.readonlySelectors)S.install(this);for(let[,S]of n.selectors){if(T.has(S.key))continue;S.install(this)}for(let[,S]of n.transactions)S.install(this);for(let[,S]of n.timelines)S.install(this)}}}var So={get STORE(){if(!globalThis.ATOM_IO_IMPLICIT_STORE)globalThis.ATOM_IO_IMPLICIT_STORE=new BM({name:"IMPLICIT_STORE",lifespan:"ephemeral"});return globalThis.ATOM_IO_IMPLICIT_STORE}};function d(o,n){let T,S=n;while(S!==null){switch(o.type){case"atom":case"mutable_atom":T=S.atoms.get(o.key);break;case"selector":T=S.selectors.get(o.key);break;case"readonly_selector":T=S.readonlySelectors.get(o.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":T=S.families.get(o.key);break;case"timeline":T=S.timelines.get(o.key);break;case"transaction":T=S.transactions.get(o.key);break;case"molecule":T=S.molecules.get(l(o.key));break;case"molecule_family":T=S.moleculeFamilies.get(o.key);break}if(T)return T;S=S.child}throw new An(o,n)}function ff(o,n){let T;T=d(o,n);let{family:S}=o;for(let A of T.joins.values())A.relations.delete(T.key),A.molecules.delete(T.stringKey);let f=[];for(let A of T.above.values())f.push(lo(A));let t=[];for(let A of T.tokens.values()){let M=A.family;t.push([M.key,n.valueMap.get(A.key)])}if(S){let A=d(S,n),M={type:"molecule_disposal",subType:"classic",token:o,family:S,context:f,values:t};if(o.family)M.family=o.family;for(let y of T.tokens.values())on(n,y);for(let y of T.below.values())if(y.dependsOn==="all")ff(y,n);else if(y.above.delete(T.stringKey),y.above.size===0)ff(y,n);if(T.below.clear(),Ao(n)&&n.transactionMeta.phase==="building")n.transactionMeta.update.updates.push(M);else A.subject.next(M);n.molecules.delete(T.stringKey)}for(let A of T.above.values())A.below.delete(T.stringKey)}function vn(o,n,T){let S=o.families.get(n.key);if(S===void 0)throw new An(n,o);let f=S(T),t=D(o);if(f.family&&t.moleculeInProgress===null){if(Co(t))switch(f.type){case"atom":case"mutable_atom":o.on.atomCreation.next(f);break;case"selector":case"readonly_selector":o.on.selectorCreation.next(f);break}else if(Ao(t)&&t.on.transactionApplying.state===null)t.transactionMeta.update.updates.push({type:"state_creation",token:f})}return f}function Go(o,n,T){let S=l(T),f=`${n.key}(${S})`,t=D(o),A;switch(n.type){case"atom_family":case"mutable_atom_family":A=t.atoms.get(f);break;case"selector_family":A=t.selectors.get(f);break;case"readonly_selector_family":A=t.readonlySelectors.get(f);break;case"molecule_family":A=t.molecules.get(l(T))}if(A)return lo(A);return A}function Mo(o,n,T){let S=Go(o,n,T);if(S)return S;let f=o.molecules.get(l(T));if(f)return zn(f,n,o);if(o.config.lifespan==="immortal"){let t=QT(n,T);return o.logger.error("\u274C",t.type,t.key,`was not found in store "${o.config.name}"; returned a counterfeit token.`),t}return S=vn(o,n,T),S}function on(o,...n){let T,S;if(n.length===1)T=n[0],S=T.key;else{let t=n[0],A=n[1];T=t.type==="molecule_family"?Go(o,t,A)??QT(t,A):Mo(o,t,A)}try{d(T,o)}catch(t){let A=o.disposalTraces.buffer.find((M)=>M?.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}".`,A?`
6
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":Ef(T,o);break;case"selector":case"readonly_selector":LA(T,o);break;case"molecule":SS(T,o);break}let{stack:S}=new Error;if(S){let f=S?.split(`
7
+ ${A.trace}`:"No previous disposal trace was found.");return}switch(T.type){case"atom":case"mutable_atom":Yt(T,o);break;case"selector":case"readonly_selector":CM(T,o);break;case"molecule":ff(T,o);break}let{stack:f}=new Error;if(f){let t=f?.split(`
8
8
  `)?.slice(3)?.join(`
9
- `);o.disposalTraces.add({key:T.key,trace:f})}}var fS=(o,n)=>U(n).atoms.has(o),Nk=(o,n)=>U(n).selectors.has(o),bk=(o,n)=>U(n).readonlySelectors.has(o),IA=(o,n)=>fS(o,n)||Nk(o,n)||bk(o,n);var yS=(o,n)=>{return U(n).selectorGraph.getRelationEntries({downstreamSelectorKey:o}).filter(([t,{source:S}])=>S!==o).map(([t,{source:S}])=>S).filter((t)=>IA(t,n))};var Yf=(o,n,T)=>{let t=[],S=yS(o,T);while(S.length>0){let f=S.shift();if(n.has(f))continue;if(n.add(f),!fS(f,T))S.push(...yS(f,T));else if(!t.includes(f))t.push(f)}return t},jA=(o,n)=>{let T=o.key,t=yS(T,n),S=new Set;return t.flatMap((f)=>fS(f,n)?f:Yf(f,S,n))};var rA=(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=Yf(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 AS=(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 fn(M,F,T)}}}else[f]=t;if(f.type==="molecule")return fo(T,f);let y=d(f,T),A=sn(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}),rA(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 fn(M,F,T);S=$}let y=U(T),A=d(S,y);dt(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}=AS(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=AS(n.key,f,t),{find:A,get:M,seek:F,json:$}=y,W={find:A,get:M,seek:F,json:$},O=(B=n.get,p=U(o))=>{let c=B(W);return Wn(n.key,c,S,p),f.clear(),c},D={...n,subject:S,install:(B)=>Rt(B,n,T),get:O,set:(B)=>{let p=U(o),c=O(n.get,p),a=et(B)(c);if(o.logger.info("\uD83D\uDCDD","selector",n.key,"set (",c,"->",a,")"),Wn(n.key,a,S,p),VT(p,n.key),Bo(p))S.next({newValue:a,oldValue:c});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 LA(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 NA(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,ro(f.token.family.subKey))}),t}var ro=(o)=>JSON.parse(o),l=(o)=>JSON.stringify(o),M4=[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 Hf=(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=sn(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=Hf(f,t),M=(W)=>{if(A)A.length=0,A.push(...Hf(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 Gf=(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 zf=(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 oT{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=Sn(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=Gf({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),MS(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 oT(M,o),!T)tA(M,n,o);return M}class mf{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=ro(t.token.family.subKey);Eo(n,this.latestUpdateAtoms,S),new oT(t.token,n)}}),this.latestUpdateAtoms.subject.subscribe(`store=${n.config.name}::tracker-atom-family`,(t)=>{if(t.token.family){let S=ro(t.token.family.subKey),f=Eo(n,this.mutableAtoms,S);if(f)new oT(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),NA(A,n,o),new mf(A,o),t}var Wf=(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 _A(o){return typeof o==="object"&&o!==null&&"do"in o&&"undo"in o&&"subscribe"in o}function Jt(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 oT(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 FA=(o,n)=>{let T=n.valueMap.get(o.key);if(o.type==="mutable_atom"&&yo(n)){let{parent:t}=n;T=Jt(o,t,n)}return T},WA=(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 KA=(o,n)=>{return U(n).atomsThatAreDefault.has(o)},MS=(o,n)=>{let T=U(n);T.atomsThatAreDefault=new Set(T.atomsThatAreDefault).add(o)},XA=(o,n)=>{let T=U(n);T.atomsThatAreDefault=new Set(U(n).atomsThatAreDefault),T.atomsThatAreDefault.delete(o)};function Sn(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}"`),Sn(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),MS(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 yA(o,n){if("mutable"in n){let S=Wt(o,n,void 0);return o.on.atomCreation.next(S),S}let t=Sn(o,n,void 0);return o.on.atomCreation.next(t),t}function Ef(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);Ef(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 Qf=(o)=>{let n=Sn(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 Df=(o)=>{let n=Sn(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 FS{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 Uf=new FS({number:(o)=>typeof o==="number",string:(o)=>typeof o==="string",boolean:(o)=>typeof o==="boolean",null:(o)=>o===null});function Vf(o){if(!o)return!1;return Object.getPrototypeOf(o)===Object.prototype}var Bf=new FS({object:Vf,array:(o)=>Array.isArray(o)}),hk=new FS({...Uf.supported,...Bf.supported}),BT=(o)=>{if(o===void 0)return"undefined";let n=hk.refine(o);if(n)return n.type;return Object.getPrototypeOf(o).constructor.name};class hA{store;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(o=to.STORE){this.store=o;this.atomIndex=Qf(this.store),this.selectorIndex=Df(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=hA.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");let n=Mf(this.atomIndex),T=Mf(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 Cf=(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]):Vf(S)?Object.entries(S):[];for(let[M,F]of A){let $=T([...t,M],F);if($?.jobComplete)return $}return{}};T([],o)};function xk(o,n){return{summary:`${o<n?"+":"-"}${Math.abs(o-n)} (${o} \u2192 ${n})`}}function ck(o,n){return{summary:`${o.length<n.length?"+":"-"}${Math.abs(o.length-n.length)} ("${o}" \u2192 "${n}")`}}function vk(o,n){return{summary:`${o} \u2192 ${n}`}}function xA(o,n,T){let t="",S=[],f=[],y=[];return Cf(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])}}}),Cf(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 ik(o,n,T){return xA(o,n,T)}class cA{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=BT(o),f=BT(n);if(S===f)return{summary:`${S} \u2192 ${f}`};return{summary:`Type change: ${S} \u2192 ${f}`}}}var X8=new cA(Uf,Bf,{number:xk,string:ck,boolean:vk,null:()=>({summary:"No Change"}),object:xA,array:ik});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 $S{key;type="continuity";globals=[];actions=[];perspectives=[];constructor(o){this.key=o}static existing=new vA;static create(o,n){let T=new $S(o),{type:t,globals:S,actions:f,perspectives:y}=n(T),A={type:t,key:o,globals:S,actions:f,perspectives:y};return $S.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 U8(o){let{key:n,config:T}=o,t=$S.create(n,T),{actions:S}=t;for(let f of S)UA(n,f.key,to.STORE);return mA(n,-1,to.STORE),t}var I8=UT({key:"usersInRoomIndex",mutable:!0,default:()=>new No,toJson:(o)=>o.toJSON(),fromJson:(o)=>No.fromJSON(o)}),Lf=UT({key:"roomIndex",default:()=>new No,mutable:!0,toJson:(o)=>o.toJSON(),fromJson:(o)=>No.fromJSON(o)}),pk={enteredAtEpoch:0},Ot=st({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(o)=>typeof o==="string",isBType:(o)=>typeof o==="string"},pk),j8=lt({key:"usersInMyRoomView",get:(o)=>({find:n})=>{let T=GA(Ot);return[n(T,o)]}});import{spawn as qk}from"child_process";class CT{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 If extends CT{incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";process;key;logger;handleLog(o){if(Array.isArray(o)){let[n,...T]=o;switch(n){case"i":this.logger.info(...T);break;case"w":this.logger.warn(...T);break;case"e":this.logger.error(...T);break}}}constructor(o,n,T){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});if(this.process=o,this.key=n,this.logger=T??{info:(...t)=>{console.info(this.id,this.key,...t)},warn:(...t)=>{console.warn(this.id,this.key,...t)},error:(...t)=>{console.error(this.id,this.key,...t)}},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=ro(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=ro(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=ro(this.incompleteLog);this.handleLog(y);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)y=ro(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 iA extends CT{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 CT{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=ro(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=ro(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 iA(`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 rf=$T({key:"roomArguments",default:["echo",["Hello World!"]]}),pA=lt({key:"room",get:(o)=>async({get:n,find:T})=>{let t=T(rf,o),S=n(t),[f,y]=S,A=await new Promise((M)=>{let F=qk(f,y,{env:process.env}),$=(W)=>{if(W.toString()==="ALIVE")F.stdout.off("data",$),M(F)};F.stdout.on("data",$)});return new If(A,o)}});var ME=$t({key:"createRoom",do:({get:o,set:n,find:T},t,S,f)=>{let y=f?[S,f]:[S],A=T(rf,t);n(A,y),n(Lf,($)=>$.add(t));let M=T(pA,t);return o(M)}}),FE=$t({key:"joinRoom",do:(o,n,T,t)=>{let S={enteredAtEpoch:t};return nS(Ot,(f)=>{f.set({room:n,user:T},S)},o.env().store),S}}),$E=$t({key:"leaveRoom",do:(o,n,T)=>{nS(Ot,(t)=>{t.delete({room:n,user:T})},o.env().store)}}),JE=$t({key:"destroyRoom",do:(o,n)=>{nS(Ot,(T)=>{T.delete({room:n})},o.env().store),o.set(Lf,(T)=>(T.delete(n),T))}});function Nf(o,n){return n.map((T)=>{switch(T.type){case"transaction_update":{let t=Nf(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 WE=$T({key:"redactor",default:{occlude:(o)=>o}}),LT=$T({key:"unacknowledgedUpdates",default:()=>[]});var qA=$T({key:"sockets",default:null}),XE=UT({key:"socketsIndex",mutable:!0,default:()=>new No,toJson:(o)=>o.toJSON(),fromJson:(o)=>No.fromJSON(o)}),EE=UT({key:"usersIndex",mutable:!0,default:()=>new No,toJson:(o)=>o.toJSON(),fromJson:(o)=>No.fromJSON(o)}),bf=st({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(o)=>o.startsWith("user::"),isBType:(o)=>o.startsWith("socket::")});function ZA(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 PA(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{an({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 gA(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,LT,T,(M)=>{return M.shift(),o.logger.info("\uD83D\uDC4D","continuity",S,`${T} unacknowledged update queue now has`,M.length,"items"),M})}}function lA(o,n,T,t){let S=n.key,f=[];for(let y of n.actions){let A=zf(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})})),$=Nf(F,M.updates),W={...M,updates:$};Qo(o,LT,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 eA(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,p=fo(o,B);return[B,p]});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 dE({socket:o,store:n=to.STORE}){return function T(t){let S=o,f=t.key,y=oS(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=oS(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 p=Ao(n,qA,B);S=fo(n,p);for(let a of $)S?.emit(`tx-new:${f}`,a)},`sync-continuity:${f}:${A}`,n),$=fo(n,LT,A),W=[],O=eA(n,t,A,S),G=lA(n,t,A,S);W.push(...O,...G);let D=ZA(n,t,A,o);S.off(`get:${f}`,D),S.on(`get:${f}`,D);let z=PA(n,t,A);S.off(`tx-run:${f}`,z),S.on(`tx-run:${f}`,z);let Y=gA(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:CJ,serve:fW}=globalThis.Bun;import{readFileSync as FM}from"fs";import{resolve as qf}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 xf;(function(o){o.mergeShapes=(n,T)=>{return{...n,...T}}})(xf||(xf={}));var r=Mo.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Pn=(o)=>{switch(typeof o){case"undefined":return r.undefined;case"string":return r.string;case"number":return isNaN(o)?r.nan:r.number;case"boolean":return r.boolean;case"function":return r.function;case"bigint":return r.bigint;case"symbol":return r.symbol;case"object":if(Array.isArray(o))return r.array;if(o===null)return r.null;if(o.then&&typeof o.then==="function"&&o.catch&&typeof o.catch==="function")return r.promise;if(typeof Map!=="undefined"&&o instanceof Map)return r.map;if(typeof Set!=="undefined"&&o instanceof Set)return r.set;if(typeof Date!=="undefined"&&o instanceof Date)return r.date;return r.object;default:return r.unknown}},m=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"]),Zk=(o)=>{return JSON.stringify(o,null,2).replace(/"([^"]+)":/g,"$1:")};class $n extends Error{get errors(){return this.issues}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}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 $n))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()}}$n.create=(o)=>{return new $n(o)};var NT=(o,n)=>{let T;switch(o.code){case m.invalid_type:if(o.received===r.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,Mo.jsonStringifyReplacer)}`;break;case m.unrecognized_keys:T=`Unrecognized key(s) in object: ${Mo.joinValues(o.keys,", ")}`;break;case m.invalid_union:T="Invalid input";break;case m.invalid_union_discriminator:T=`Invalid discriminator value. Expected ${Mo.joinValues(o.options)}`;break;case m.invalid_enum_value:T=`Invalid enum value. Expected ${Mo.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 Mo.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,Mo.assertNever(o)}return{message:T}},aA=NT;function Pk(o){aA=o}function JS(){return aA}var kS=(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}},gk=[];function L(o,n){let T=JS(),t=kS({issueData:n,data:o.data,path:o.path,errorMaps:[o.common.contextualErrorMap,o.schemaErrorMap,T,T===NT?void 0:NT].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}),on=(o)=>({status:"valid",value:o}),cf=(o)=>o.status==="aborted",vf=(o)=>o.status==="dirty",JT=(o)=>o.status==="valid",Kt=(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 sA(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 i;(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})(i||(i={}));var _t,wt;class Un{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 dA=(o,n)=>{if(JT(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 $n(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{get description(){return this._def.description}_getType(o){return Pn(o.data)}_getOrReturnCtx(o,n){return n||{common:o.parent.common,data:o.data,parsedType:Pn(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:Pn(o.data),schemaErrorMap:this._def.errorMap,path:o.path,parent:o.parent}}}_parseSync(o){let n=this._parse(o);if(Kt(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:Pn(o)},S=this._parseSync({data:o,path:t.path,parent:t});return dA(t,S)}"~validate"(o){var n,T;let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:o,parsedType:Pn(o)};if(!this["~standard"].async)try{let S=this._parseSync({data:o,path:[],parent:t});return JT(S)?{value:S.value}:{issues:t.common.issues}}catch(S){if((T=(n=S===null||S===void 0?void 0:S.message)===null||n===void 0?void 0:n.toLowerCase())===null||T===void 0?void 0:T.includes("encountered"))this["~standard"].async=!0;t.common={issues:[],async:!0}}return this._parseAsync({data:o,path:[],parent:t}).then((S)=>JT(S)?{value:S.value}:{issues:t.common.issues})}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:Pn(o)},t=this._parse({data:o,path:T.path,parent:T}),S=await(Kt(t)?t:Promise.resolve(t));return dA(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 _n({schema:this,typeName:e.ZodEffects,effect:{type:"refinement",refinement:o}})}superRefine(o){return this._refinement(o)}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),this["~standard"]={version:1,vendor:"zod",validate:(n)=>this["~validate"](n)}}optional(){return Dn.create(this,this._def)}nullable(){return gn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Qn.create(this)}promise(){return OT.create(this,this._def)}or(o){return cT.create([this,o],this._def)}and(o){return vT.create(this,o,this._def)}transform(o){return new _n({...oo(this._def),schema:this,typeName:e.ZodEffects,effect:{type:"transform",transform:o}})}default(o){let n=typeof o==="function"?o:()=>o;return new ZT({...oo(this._def),innerType:this,defaultValue:n,typeName:e.ZodDefault})}brand(){return new OS({typeName:e.ZodBranded,type:this,...oo(this._def)})}catch(o){let n=typeof o==="function"?o:()=>o;return new PT({...oo(this._def),innerType:this,catchValue:n,typeName:e.ZodCatch})}describe(o){return new this.constructor({...this._def,description:o})}pipe(o){return Ht.create(this,o)}readonly(){return gT.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var lk=/^c[^\s-]{8,}$/i,ek=/^[0-9a-z]+$/,dk=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uk=/^[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,ak=/^[a-z0-9_-]{21}$/i,sk=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,oR=/^[-+]?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)?)??$/,nR=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,TR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",hf,tR=/^(?:(?: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])$/,SR=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,fR=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,yR=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,AR=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,MR=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,oM="((\\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])))",FR=new RegExp(`^${oM}$`);function nM(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 $R(o){return new RegExp(`^${nM(o)}$`)}function TM(o){let n=`${oM}T${nM(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 JR(o,n){if((n==="v4"||!n)&&tR.test(o))return!0;if((n==="v6"||!n)&&fR.test(o))return!0;return!1}function kR(o,n){if(!sk.test(o))return!1;try{let[T]=o.split("."),t=T.replace(/-/g,"+").replace(/_/g,"/").padEnd(T.length+(4-T.length%4)%4,"="),S=JSON.parse(atob(t));if(typeof S!=="object"||S===null)return!1;if(!S.typ||!S.alg)return!1;if(n&&S.alg!==n)return!1;return!0}catch(T){return!1}}function RR(o,n){if((n==="v4"||!n)&&SR.test(o))return!0;if((n==="v6"||!n)&&yR.test(o))return!0;return!1}class mn extends no{_parse(o){if(this._def.coerce)o.data=String(o.data);if(this._getType(o)!==r.string){let S=this._getOrReturnCtx(o);return L(S,{code:m.invalid_type,expected:r.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),L(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),L(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)L(t,{code:m.too_big,maximum:S.value,type:"string",inclusive:!0,exact:!0,message:S.message});else if(y)L(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(!nR.test(o.data))t=this._getOrReturnCtx(o,t),L(t,{validation:"email",code:m.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="emoji"){if(!hf)hf=new RegExp(TR,"u");if(!hf.test(o.data))t=this._getOrReturnCtx(o,t),L(t,{validation:"emoji",code:m.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="uuid"){if(!uk.test(o.data))t=this._getOrReturnCtx(o,t),L(t,{validation:"uuid",code:m.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="nanoid"){if(!ak.test(o.data))t=this._getOrReturnCtx(o,t),L(t,{validation:"nanoid",code:m.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="cuid"){if(!lk.test(o.data))t=this._getOrReturnCtx(o,t),L(t,{validation:"cuid",code:m.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="cuid2"){if(!ek.test(o.data))t=this._getOrReturnCtx(o,t),L(t,{validation:"cuid2",code:m.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="ulid"){if(!dk.test(o.data))t=this._getOrReturnCtx(o,t),L(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),L(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),L(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),L(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),L(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),L(t,{code:m.invalid_string,validation:{endsWith:S.value},message:S.message}),T.dirty()}else if(S.kind==="datetime"){if(!TM(S).test(o.data))t=this._getOrReturnCtx(o,t),L(t,{code:m.invalid_string,validation:"datetime",message:S.message}),T.dirty()}else if(S.kind==="date"){if(!FR.test(o.data))t=this._getOrReturnCtx(o,t),L(t,{code:m.invalid_string,validation:"date",message:S.message}),T.dirty()}else if(S.kind==="time"){if(!$R(S).test(o.data))t=this._getOrReturnCtx(o,t),L(t,{code:m.invalid_string,validation:"time",message:S.message}),T.dirty()}else if(S.kind==="duration"){if(!oR.test(o.data))t=this._getOrReturnCtx(o,t),L(t,{validation:"duration",code:m.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="ip"){if(!JR(o.data,S.version))t=this._getOrReturnCtx(o,t),L(t,{validation:"ip",code:m.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="jwt"){if(!kR(o.data,S.alg))t=this._getOrReturnCtx(o,t),L(t,{validation:"jwt",code:m.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="cidr"){if(!RR(o.data,S.version))t=this._getOrReturnCtx(o,t),L(t,{validation:"cidr",code:m.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="base64"){if(!AR.test(o.data))t=this._getOrReturnCtx(o,t),L(t,{validation:"base64",code:m.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="base64url"){if(!MR.test(o.data))t=this._getOrReturnCtx(o,t),L(t,{validation:"base64url",code:m.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:m.invalid_string,...i.errToObj(T)})}_addCheck(o){return new mn({...this._def,checks:[...this._def.checks,o]})}email(o){return this._addCheck({kind:"email",...i.errToObj(o)})}url(o){return this._addCheck({kind:"url",...i.errToObj(o)})}emoji(o){return this._addCheck({kind:"emoji",...i.errToObj(o)})}uuid(o){return this._addCheck({kind:"uuid",...i.errToObj(o)})}nanoid(o){return this._addCheck({kind:"nanoid",...i.errToObj(o)})}cuid(o){return this._addCheck({kind:"cuid",...i.errToObj(o)})}cuid2(o){return this._addCheck({kind:"cuid2",...i.errToObj(o)})}ulid(o){return this._addCheck({kind:"ulid",...i.errToObj(o)})}base64(o){return this._addCheck({kind:"base64",...i.errToObj(o)})}base64url(o){return this._addCheck({kind:"base64url",...i.errToObj(o)})}jwt(o){return this._addCheck({kind:"jwt",...i.errToObj(o)})}ip(o){return this._addCheck({kind:"ip",...i.errToObj(o)})}cidr(o){return this._addCheck({kind:"cidr",...i.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,...i.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,...i.errToObj(o===null||o===void 0?void 0:o.message)})}duration(o){return this._addCheck({kind:"duration",...i.errToObj(o)})}regex(o,n){return this._addCheck({kind:"regex",regex:o,...i.errToObj(n)})}includes(o,n){return this._addCheck({kind:"includes",value:o,position:n===null||n===void 0?void 0:n.position,...i.errToObj(n===null||n===void 0?void 0:n.message)})}startsWith(o,n){return this._addCheck({kind:"startsWith",value:o,...i.errToObj(n)})}endsWith(o,n){return this._addCheck({kind:"endsWith",value:o,...i.errToObj(n)})}min(o,n){return this._addCheck({kind:"min",value:o,...i.errToObj(n)})}max(o,n){return this._addCheck({kind:"max",value:o,...i.errToObj(n)})}length(o,n){return this._addCheck({kind:"length",value:o,...i.errToObj(n)})}nonempty(o){return this.min(1,i.errToObj(o))}trim(){return new mn({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new mn({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new mn({...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 isCIDR(){return!!this._def.checks.find((o)=>o.kind==="cidr")}get isBase64(){return!!this._def.checks.find((o)=>o.kind==="base64")}get isBase64url(){return!!this._def.checks.find((o)=>o.kind==="base64url")}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}}mn.create=(o)=>{var n;return new mn({checks:[],typeName:e.ZodString,coerce:(n=o===null||o===void 0?void 0:o.coerce)!==null&&n!==void 0?n:!1,...oo(o)})};function WR(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 TT extends no{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(o){if(this._def.coerce)o.data=Number(o.data);if(this._getType(o)!==r.number){let S=this._getOrReturnCtx(o);return L(S,{code:m.invalid_type,expected:r.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),L(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),L(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),L(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(WR(o.data,S.value)!==0)T=this._getOrReturnCtx(o,T),L(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),L(T,{code:m.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,i.toString(n))}gt(o,n){return this.setLimit("min",o,!1,i.toString(n))}lte(o,n){return this.setLimit("max",o,!0,i.toString(n))}lt(o,n){return this.setLimit("max",o,!1,i.toString(n))}setLimit(o,n,T,t){return new TT({...this._def,checks:[...this._def.checks,{kind:o,value:n,inclusive:T,message:i.toString(t)}]})}_addCheck(o){return new TT({...this._def,checks:[...this._def.checks,o]})}int(o){return this._addCheck({kind:"int",message:i.toString(o)})}positive(o){return this._addCheck({kind:"min",value:0,inclusive:!1,message:i.toString(o)})}negative(o){return this._addCheck({kind:"max",value:0,inclusive:!1,message:i.toString(o)})}nonpositive(o){return this._addCheck({kind:"max",value:0,inclusive:!0,message:i.toString(o)})}nonnegative(o){return this._addCheck({kind:"min",value:0,inclusive:!0,message:i.toString(o)})}multipleOf(o,n){return this._addCheck({kind:"multipleOf",value:o,message:i.toString(n)})}finite(o){return this._addCheck({kind:"finite",message:i.toString(o)})}safe(o){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:i.toString(o)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:i.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)}}TT.create=(o)=>{return new TT({checks:[],typeName:e.ZodNumber,coerce:(o===null||o===void 0?void 0:o.coerce)||!1,...oo(o)})};class tT extends no{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(o){if(this._def.coerce)try{o.data=BigInt(o.data)}catch(S){return this._getInvalidInput(o)}if(this._getType(o)!==r.bigint)return this._getInvalidInput(o);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),L(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),L(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),L(T,{code:m.not_multiple_of,multipleOf:S.value,message:S.message}),t.dirty()}else Mo.assertNever(S);return{status:t.value,value:o.data}}_getInvalidInput(o){let n=this._getOrReturnCtx(o);return L(n,{code:m.invalid_type,expected:r.bigint,received:n.parsedType}),u}gte(o,n){return this.setLimit("min",o,!0,i.toString(n))}gt(o,n){return this.setLimit("min",o,!1,i.toString(n))}lte(o,n){return this.setLimit("max",o,!0,i.toString(n))}lt(o,n){return this.setLimit("max",o,!1,i.toString(n))}setLimit(o,n,T,t){return new tT({...this._def,checks:[...this._def.checks,{kind:o,value:n,inclusive:T,message:i.toString(t)}]})}_addCheck(o){return new tT({...this._def,checks:[...this._def.checks,o]})}positive(o){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:i.toString(o)})}negative(o){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:i.toString(o)})}nonpositive(o){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:i.toString(o)})}nonnegative(o){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:i.toString(o)})}multipleOf(o,n){return this._addCheck({kind:"multipleOf",value:o,message:i.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}}tT.create=(o)=>{var n;return new tT({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)!==r.boolean){let T=this._getOrReturnCtx(o);return L(T,{code:m.invalid_type,expected:r.boolean,received:T.parsedType}),u}return on(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 kT extends no{_parse(o){if(this._def.coerce)o.data=new Date(o.data);if(this._getType(o)!==r.date){let S=this._getOrReturnCtx(o);return L(S,{code:m.invalid_type,expected:r.date,received:S.parsedType}),u}if(isNaN(o.data.getTime())){let S=this._getOrReturnCtx(o);return L(S,{code:m.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),L(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),L(t,{code:m.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 kT({...this._def,checks:[...this._def.checks,o]})}min(o,n){return this._addCheck({kind:"min",value:o.getTime(),message:i.toString(n)})}max(o,n){return this._addCheck({kind:"max",value:o.getTime(),message:i.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}}kT.create=(o)=>{return new kT({checks:[],coerce:(o===null||o===void 0?void 0:o.coerce)||!1,typeName:e.ZodDate,...oo(o)})};class Xt extends no{_parse(o){if(this._getType(o)!==r.symbol){let T=this._getOrReturnCtx(o);return L(T,{code:m.invalid_type,expected:r.symbol,received:T.parsedType}),u}return on(o.data)}}Xt.create=(o)=>{return new Xt({typeName:e.ZodSymbol,...oo(o)})};class hT extends no{_parse(o){if(this._getType(o)!==r.undefined){let T=this._getOrReturnCtx(o);return L(T,{code:m.invalid_type,expected:r.undefined,received:T.parsedType}),u}return on(o.data)}}hT.create=(o)=>{return new hT({typeName:e.ZodUndefined,...oo(o)})};class xT extends no{_parse(o){if(this._getType(o)!==r.null){let T=this._getOrReturnCtx(o);return L(T,{code:m.invalid_type,expected:r.null,received:T.parsedType}),u}return on(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 on(o.data)}}RT.create=(o)=>{return new RT({typeName:e.ZodAny,...oo(o)})};class nT extends no{constructor(){super(...arguments);this._unknown=!0}_parse(o){return on(o.data)}}nT.create=(o)=>{return new nT({typeName:e.ZodUnknown,...oo(o)})};class rn extends no{_parse(o){let n=this._getOrReturnCtx(o);return L(n,{code:m.invalid_type,expected:r.never,received:n.parsedType}),u}}rn.create=(o)=>{return new rn({typeName:e.ZodNever,...oo(o)})};class Et extends no{_parse(o){if(this._getType(o)!==r.undefined){let T=this._getOrReturnCtx(o);return L(T,{code:m.invalid_type,expected:r.void,received:T.parsedType}),u}return on(o.data)}}Et.create=(o)=>{return new Et({typeName:e.ZodVoid,...oo(o)})};class Qn extends no{_parse(o){let{ctx:n,status:T}=this._processInputParams(o),t=this._def;if(n.parsedType!==r.array)return L(n,{code:m.invalid_type,expected:r.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)L(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)L(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)L(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 Un(n,f,n.path,y))})).then((f)=>{return eo.mergeArray(T,f)});let S=[...n.data].map((f,y)=>{return t.type._parseSync(new Un(n,f,n.path,y))});return eo.mergeArray(T,S)}get element(){return this._def.type}min(o,n){return new Qn({...this._def,minLength:{value:o,message:i.toString(n)}})}max(o,n){return new Qn({...this._def,maxLength:{value:o,message:i.toString(n)}})}length(o,n){return new Qn({...this._def,exactLength:{value:o,message:i.toString(n)}})}nonempty(o){return this.min(1,o)}}Qn.create=(o,n)=>{return new Qn({type:o,minLength:null,maxLength:null,exactLength:null,typeName:e.ZodArray,...oo(n)})};function IT(o){if(o instanceof Do){let n={};for(let T in o.shape){let t=o.shape[T];n[T]=Dn.create(IT(t))}return new Do({...o._def,shape:()=>n})}else if(o instanceof Qn)return new Qn({...o._def,type:IT(o.element)});else if(o instanceof Dn)return Dn.create(IT(o.unwrap()));else if(o instanceof gn)return gn.create(IT(o.unwrap()));else if(o instanceof Nn)return Nn.create(o.items.map((n)=>IT(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)!==r.object){let M=this._getOrReturnCtx(o);return L(M,{code:m.invalid_type,expected:r.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 rn&&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 Un(t,$,t.path,M)),alwaysSet:M in t.data})}if(this._def.catchall instanceof rn){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)L(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 $=t.data[F];A.push({key:{status:"valid",value:F},value:M._parse(new Un(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 i.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=i.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 IT(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 Dn)S=S._def.innerType;n[T]=S}}),new Do({...this._def,shape:()=>n})}keyof(){return tM(Mo.objectKeys(this.shape))}}Do.create=(o,n)=>{return new Do({shape:()=>o,unknownKeys:"strip",catchall:rn.create(),typeName:e.ZodObject,...oo(n)})};Do.strictCreate=(o,n)=>{return new Do({shape:()=>o,unknownKeys:"strict",catchall:rn.create(),typeName:e.ZodObject,...oo(n)})};Do.lazycreate=(o,n)=>{return new Do({shape:o,unknownKeys:"strip",catchall:rn.create(),typeName:e.ZodObject,...oo(n)})};class cT 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 $n(y.ctx.common.issues));return L(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 $n(A));return L(n,{code:m.invalid_union,unionErrors:y}),u}}get options(){return this._def.options}}cT.create=(o,n)=>{return new cT({options:o,typeName:e.ZodUnion,...oo(n)})};var Zn=(o)=>{if(o instanceof iT)return Zn(o.schema);else if(o instanceof _n)return Zn(o.innerType());else if(o instanceof pT)return[o.value];else if(o instanceof ST)return o.options;else if(o instanceof qT)return Mo.objectValues(o.enum);else if(o instanceof ZT)return Zn(o._def.innerType);else if(o instanceof hT)return[void 0];else if(o instanceof xT)return[null];else if(o instanceof Dn)return[void 0,...Zn(o.unwrap())];else if(o instanceof gn)return[null,...Zn(o.unwrap())];else if(o instanceof OS)return Zn(o.unwrap());else if(o instanceof gT)return Zn(o.unwrap());else if(o instanceof PT)return Zn(o._def.innerType);else return[]};class WS extends no{_parse(o){let{ctx:n}=this._processInputParams(o);if(n.parsedType!==r.object)return L(n,{code:m.invalid_type,expected:r.object,received:n.parsedType}),u;let T=this.discriminator,t=n.data[T],S=this.optionsMap.get(t);if(!S)return L(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=Zn(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 WS({typeName:e.ZodDiscriminatedUnion,discriminator:o,options:n,optionsMap:t,...oo(T)})}}function pf(o,n){let T=Pn(o),t=Pn(n);if(o===n)return{valid:!0,data:o};else if(T===r.object&&t===r.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=pf(o[A],n[A]);if(!M.valid)return{valid:!1};y[A]=M.data}return{valid:!0,data:y}}else if(T===r.array&&t===r.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=pf(y,A);if(!M.valid)return{valid:!1};S.push(M.data)}return{valid:!0,data:S}}else if(T===r.date&&t===r.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(cf(S)||cf(f))return u;let y=pf(S.value,f.value);if(!y.valid)return L(T,{code:m.invalid_intersection_types}),u;if(vf(S)||vf(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 Nn extends no{_parse(o){let{status:n,ctx:T}=this._processInputParams(o);if(T.parsedType!==r.array)return L(T,{code:m.invalid_type,expected:r.array,received:T.parsedType}),u;if(T.data.length<this._def.items.length)return L(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)L(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 Un(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 Nn({...this._def,rest:o})}}Nn.create=(o,n)=>{if(!Array.isArray(o))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Nn({items:o,typeName:e.ZodTuple,rest:null,...oo(n)})};class Yt 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!==r.object)return L(T,{code:m.invalid_type,expected:r.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 Un(T,y,T.path,y)),value:f._parse(new Un(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 Yt({keyType:o,valueType:n,typeName:e.ZodRecord,...oo(T)});return new Yt({keyType:mn.create(),valueType:o,typeName:e.ZodRecord,...oo(n)})}}class Gt 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!==r.map)return L(T,{code:m.invalid_type,expected:r.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 Un(T,y,T.path,[M,"key"])),value:S._parse(new Un(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}}}}Gt.create=(o,n,T)=>{return new Gt({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!==r.set)return L(T,{code:m.invalid_type,expected:r.set,received:T.parsedType}),u;let t=this._def;if(t.minSize!==null){if(T.data.size<t.minSize.value)L(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)L(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 Un(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:i.toString(n)}})}max(o,n){return new WT({...this._def,maxSize:{value:o,message:i.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 rT extends no{constructor(){super(...arguments);this.validate=this.implement}_parse(o){let{ctx:n}=this._processInputParams(o);if(n.parsedType!==r.function)return L(n,{code:m.invalid_type,expected:r.function,received:n.parsedType}),u;function T(y,A){return kS({data:y,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,JS(),NT].filter((M)=>!!M),issueData:{code:m.invalid_arguments,argumentsError:A}})}function t(y,A){return kS({data:y,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,JS(),NT].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 OT){let y=this;return on(async function(...A){let M=new $n([]),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 on(function(...A){let M=y._def.args.safeParse(A,S);if(!M.success)throw new $n([T(A,M.error)]);let F=Reflect.apply(f,this,M.data),$=y._def.returns.safeParse(F,S);if(!$.success)throw new $n([t(F,$.error)]);return $.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...o){return new rT({...this._def,args:Nn.create(o).rest(nT.create())})}returns(o){return new rT({...this._def,returns:o})}implement(o){return this.parse(o)}strictImplement(o){return this.parse(o)}static create(o,n,T){return new rT({args:o?o:Nn.create([]).rest(nT.create()),returns:n||nT.create(),typeName:e.ZodFunction,...oo(T)})}}class iT 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})}}iT.create=(o,n)=>{return new iT({getter:o,typeName:e.ZodLazy,...oo(n)})};class pT extends no{_parse(o){if(o.data!==this._def.value){let n=this._getOrReturnCtx(o);return L(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:e.ZodLiteral,...oo(n)})};function tM(o,n){return new ST({values:o,typeName:e.ZodEnum,...oo(n)})}class ST extends no{constructor(){super(...arguments);_t.set(this,void 0)}_parse(o){if(typeof o.data!=="string"){let n=this._getOrReturnCtx(o),T=this._def.values;return L(n,{expected:Mo.joinValues(T),received:n.parsedType,code:m.invalid_type}),u}if(!RS(this,_t,"f"))sA(this,_t,new Set(this._def.values),"f");if(!RS(this,_t,"f").has(o.data)){let n=this._getOrReturnCtx(o),T=this._def.values;return L(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 ST.create(o,{...this._def,...n})}exclude(o,n=this._def){return ST.create(this.options.filter((T)=>!o.includes(T)),{...this._def,...n})}}_t=new WeakMap;ST.create=tM;class qT extends no{constructor(){super(...arguments);wt.set(this,void 0)}_parse(o){let n=Mo.getValidEnumValues(this._def.values),T=this._getOrReturnCtx(o);if(T.parsedType!==r.string&&T.parsedType!==r.number){let t=Mo.objectValues(n);return L(T,{expected:Mo.joinValues(t),received:T.parsedType,code:m.invalid_type}),u}if(!RS(this,wt,"f"))sA(this,wt,new Set(Mo.getValidEnumValues(this._def.values)),"f");if(!RS(this,wt,"f").has(o.data)){let t=Mo.objectValues(n);return L(T,{received:T.data,code:m.invalid_enum_value,options:t}),u}return on(o.data)}get enum(){return this._def.values}}wt=new WeakMap;qT.create=(o,n)=>{return new qT({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!==r.promise&&n.common.async===!1)return L(n,{code:m.invalid_type,expected:r.promise,received:n.parsedType}),u;let T=n.parsedType===r.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})}))}}OT.create=(o,n)=>{return new OT({type:o,typeName:e.ZodPromise,...oo(n)})};class _n 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(L(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(!JT(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(!JT(f))return f;return Promise.resolve(t.transform(f.value,S)).then((y)=>({status:n.value,value:y}))});Mo.assertNever(t)}}_n.create=(o,n,T)=>{return new _n({schema:o,typeName:e.ZodEffects,effect:n,...oo(T)})};_n.createWithPreprocess=(o,n,T)=>{return new _n({schema:n,effect:{type:"preprocess",transform:o},typeName:e.ZodEffects,...oo(T)})};class Dn extends no{_parse(o){if(this._getType(o)===r.undefined)return on(void 0);return this._def.innerType._parse(o)}unwrap(){return this._def.innerType}}Dn.create=(o,n)=>{return new Dn({innerType:o,typeName:e.ZodOptional,...oo(n)})};class gn extends no{_parse(o){if(this._getType(o)===r.null)return on(null);return this._def.innerType._parse(o)}unwrap(){return this._def.innerType}}gn.create=(o,n)=>{return new gn({innerType:o,typeName:e.ZodNullable,...oo(n)})};class ZT extends no{_parse(o){let{ctx:n}=this._processInputParams(o),T=n.data;if(n.parsedType===r.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:e.ZodDefault,defaultValue:typeof n.default==="function"?n.default:()=>n.default,...oo(n)})};class PT 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(Kt(t))return t.then((S)=>{return{status:"valid",value:S.status==="valid"?S.value:this._def.catchValue({get error(){return new $n(T.common.issues)},input:T.data})}});else return{status:"valid",value:t.status==="valid"?t.value:this._def.catchValue({get error(){return new $n(T.common.issues)},input:T.data})}}removeCatch(){return this._def.innerType}}PT.create=(o,n)=>{return new PT({innerType:o,typeName:e.ZodCatch,catchValue:typeof n.catch==="function"?n.catch:()=>n.catch,...oo(n)})};class zt extends no{_parse(o){if(this._getType(o)!==r.nan){let T=this._getOrReturnCtx(o);return L(T,{code:m.invalid_type,expected:r.nan,received:T.parsedType}),u}return{status:"valid",value:o.data}}}zt.create=(o)=>{return new zt({typeName:e.ZodNaN,...oo(o)})};var OR=Symbol("zod_brand");class OS 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 Ht 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 Ht({in:o,out:n,typeName:e.ZodPipeline})}}class gT extends no{_parse(o){let n=this._def.innerType._parse(o),T=(t)=>{if(JT(t))t.value=Object.freeze(t.value);return t};return Kt(n)?n.then((t)=>T(t)):T(n)}unwrap(){return this._def.innerType}}gT.create=(o,n)=>{return new gT({innerType:o,typeName:e.ZodReadonly,...oo(n)})};function SM(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 _R={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 wR=(o,n={message:`Input not instance of ${o.name}`})=>SM((T)=>T instanceof o,n),fM=mn.create,yM=TT.create,KR=zt.create,XR=tT.create,AM=bT.create,ER=kT.create,YR=Xt.create,GR=hT.create,zR=xT.create,HR=RT.create,mR=nT.create,QR=rn.create,DR=Et.create,UR=Qn.create,mt=Do.create,VR=Do.strictCreate,BR=cT.create,CR=WS.create,LR=vT.create,IR=Nn.create,jR=Yt.create,rR=Gt.create,NR=WT.create,bR=rT.create,hR=iT.create,xR=pT.create,cR=ST.create,vR=qT.create,iR=OT.create,uA=_n.create,pR=Dn.create,qR=gn.create,ZR=_n.createWithPreprocess,PR=Ht.create,gR=()=>fM().optional(),lR=()=>yM().optional(),eR=()=>AM().optional(),dR={string:(o)=>mn.create({...o,coerce:!0}),number:(o)=>TT.create({...o,coerce:!0}),boolean:(o)=>bT.create({...o,coerce:!0}),bigint:(o)=>tT.create({...o,coerce:!0}),date:(o)=>kT.create({...o,coerce:!0})},uR=u,Yo=Object.freeze({__proto__:null,defaultErrorMap:NT,setErrorMap:Pk,getErrorMap:JS,makeIssue:kS,EMPTY_PATH:gk,addIssueToContext:L,ParseStatus:eo,INVALID:u,DIRTY:jT,OK:on,isAborted:cf,isDirty:vf,isValid:JT,isAsync:Kt,get util(){return Mo},get objectUtil(){return xf},ZodParsedType:r,getParsedType:Pn,ZodType:no,datetimeRegex:TM,ZodString:mn,ZodNumber:TT,ZodBigInt:tT,ZodBoolean:bT,ZodDate:kT,ZodSymbol:Xt,ZodUndefined:hT,ZodNull:xT,ZodAny:RT,ZodUnknown:nT,ZodNever:rn,ZodVoid:Et,ZodArray:Qn,ZodObject:Do,ZodUnion:cT,ZodDiscriminatedUnion:WS,ZodIntersection:vT,ZodTuple:Nn,ZodRecord:Yt,ZodMap:Gt,ZodSet:WT,ZodFunction:rT,ZodLazy:iT,ZodLiteral:pT,ZodEnum:ST,ZodNativeEnum:qT,ZodPromise:OT,ZodEffects:_n,ZodTransformer:_n,ZodOptional:Dn,ZodNullable:gn,ZodDefault:ZT,ZodCatch:PT,ZodNaN:zt,BRAND:OR,ZodBranded:OS,ZodPipeline:Ht,ZodReadonly:gT,custom:SM,Schema:no,ZodSchema:no,late:_R,get ZodFirstPartyTypeKind(){return e},coerce:dR,any:HR,array:UR,bigint:XR,boolean:AM,date:ER,discriminatedUnion:CR,effect:uA,enum:cR,function:bR,instanceof:wR,intersection:LR,lazy:hR,literal:xR,map:rR,nan:KR,nativeEnum:vR,never:QR,null:zR,nullable:qR,number:yM,object:mt,oboolean:eR,onumber:lR,optional:pR,ostring:gR,pipeline:PR,preprocess:ZR,promise:iR,record:jR,set:NR,strictObject:VR,string:fM,symbol:YR,transformer:uA,tuple:IR,undefined:GR,union:BR,unknown:mR,void:DR,NEVER:uR,ZodIssueCode:m,quotelessJson:Zk,ZodError:$n});function MM(o){let n=o.runtimeEnvStrict??o.runtimeEnv??process.env;if(o.emptyStringAsUndefined??!1){for(let[K,Q]of Object.entries(n))if(Q==="")delete n[K]}if(!!o.skipValidation)return n;let S=typeof o.client==="object"?o.client:{},f=typeof o.server==="object"?o.server:{},y=typeof o.shared==="object"?o.shared:{},A=mt(S),M=mt(f),F=mt(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)},p=(K)=>{return K==="__esModule"||K==="$$typeof"},c=(o.extends??[]).reduce((K,Q)=>{return Object.assign(K,Q)},{}),a=Object.assign(G.data,c);return new Proxy(a,{get(K,Q){if(typeof Q!=="string")return;if(p(Q))return;if(!B(Q))return z(Q);return Reflect.get(K,Q)}})}var aR="__vite_start_time"in globalThis,sR=typeof window!=="undefined",D5="vitest"in globalThis,Vn=MM({isServer:!aR&&!sR,server:{CI:Yo.string().transform((o)=>!0).optional(),POSTGRES_USER:Yo.string(),POSTGRES_PASSWORD:Yo.string(),POSTGRES_DATABASE:Yo.string(),POSTGRES_HOST:Yo.string(),POSTGRES_PORT:Yo.string().transform((o)=>Number.parseInt(o,10)),BACKEND_PORT:Yo.string().transform((o)=>Number.parseInt(o,10)),RUN_WORKERS_FROM_SOURCE:Yo.union([Yo.literal("true"),Yo.literal("false")]).optional().transform((o)=>o==="true"),FRONTEND_PORT:Yo.string().transform((o)=>Number.parseInt(o,10)),FRONTEND_ORIGINS:Yo.string().transform((o)=>JSON.parse(o)).pipe(Yo.array(Yo.string())),OPENAI_API_KEY:Yo.string().optional()},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:Yo.string(),VITE_USE_SELF_SIGNED_CERTIFICATE:Yo.union([Yo.literal("true"),Yo.literal("false")]).optional().transform((o)=>o==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var $M=qf(import.meta.dirname,"../dev"),JM=Vn.VITE_USE_SELF_SIGNED_CERTIFICATE?{cert:FM(qf($M,"./cert.pem"),"utf-8"),key:FM(qf($M,"./key.pem"),"utf-8")}:void 0;import nW from"path";var k=Symbol.for("drizzle:entityKind"),I5=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,k))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(k in T&&T[k]===n[k])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[k]="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 Zf{static[k]="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 Bn=Symbol.for("drizzle:Name");class Pf{static[k]="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 kM(o,this)}}class kM{constructor(o,n){this.table=o,this.reference=n.reference,this.onUpdate=n._onUpdate,this.onDelete=n._onDelete}static[k]="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[Bn],...t,T[0].table[Bn],...S];return o??`${f.join("_")}_fk`}}function _S(o,...n){return o(...n)}function RM(o,n){return`${o[Bn]}_${n.join("_")}_unique`}function WM(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]=WM(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]=WM(o,t,!1);T.push(y),t=A}return[T,t]}function _M(o){let[n]=OM(o,1);return n}function gf(o){return`{${o.map((n)=>{if(Array.isArray(n))return gf(n);if(typeof n==="string")return`"${n.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${n}`}).join(",")}}`}class b extends Zf{foreignKeyConfigs=[];static[k]="PgColumnBuilder";array(o){return new KM(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 _S((S,f)=>{let y=new Pf(()=>{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 wM(o,this.config)}}class V extends Ro{constructor(o,n){if(!n.uniqueName)n.uniqueName=RM(o,[n.name]);super(o,n);this.table=o}static[k]="PgColumn"}class wM extends V{static[k]="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 Qt{static[k]="IndexedColumn";constructor(o,n,T,t){this.name=o,this.keyAsName=n,this.type=T,this.indexConfig=t}name;keyAsName;type;indexConfig}class KM extends b{static[k]="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 lf(o,this.config,n)}}class lf extends V{constructor(o,n,T,t){super(o,n);this.baseColumn=T,this.range=t,this.size=n.size}size;static[k]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(o){if(typeof o==="string")o=_M(o);return o.map((n)=>this.baseColumn.mapFromDriverValue(n))}mapToDriverValue(o,n=!1){let T=o.map((t)=>t===null?null:X(this.baseColumn,lf)?this.baseColumn.mapToDriverValue(t,!0):this.baseColumn.mapToDriverValue(t));if(n)return T;return gf(T)}}var ef=Symbol.for("drizzle:isPgEnum");function XM(o){return!!o&&typeof o==="function"&&ef in o&&o[ef]===!0}class EM extends b{static[k]="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[k]="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 o0(o,n,void 0)}function o0(o,n,T){let t=Object.assign((S)=>new EM(S??"",t),{enumName:o,enumValues:n,schema:T,[ef]:!0});return t}class bo{static[k]="Subquery";constructor(o,n,T,t=!1){this._={brand:"Subquery",sql:o,selectedFields:n,alias:T,isWith:t}}}class Dt extends bo{static[k]="WithSubquery"}var GM="0.38.3";var df,uf,Wo={startActiveSpan(o,n){if(!df)return n();if(!uf)uf=df.trace.getTracer("drizzle-orm",GM);return _S((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()}}),df,uf)}};var Go=Symbol.for("drizzle:ViewBaseConfig");var KS=Symbol.for("drizzle:Schema"),XS=Symbol.for("drizzle:Columns"),zM=Symbol.for("drizzle:ExtraConfigColumns"),af=Symbol.for("drizzle:OriginalName"),sf=Symbol.for("drizzle:BaseName"),ES=Symbol.for("drizzle:IsAlias"),HM=Symbol.for("drizzle:ExtraConfigBuilder"),n0=Symbol.for("drizzle:IsDrizzleTable");class I{static[k]="Table";static Symbol={Name:Bn,Schema:KS,OriginalName:af,Columns:XS,ExtraConfigColumns:zM,BaseName:sf,IsAlias:ES,ExtraConfigBuilder:HM};[Bn];[af];[KS];[XS];[zM];[sf];[ES]=!1;[n0]=!0;[HM]=void 0;constructor(o,n,T){this[Bn]=this[af]=o,this[KS]=n,this[sf]=T}}function wn(o){return o[Bn]}function _T(o){return`${o[KS]??"public"}.${o[Bn]}`}function oy(o){return o!==null&&o!==void 0&&typeof o.getSQL==="function"}function T0(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[k]="StringChunk";value;constructor(o){this.value=Array.isArray(o)?o:[o]}getSQL(){return new j([this])}}class j{constructor(o){this.queryChunks=o}static[k]="SQL";decoder=QM;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 T0(o.map((F)=>{if(X(F,ho))return{sql:F.value.join(""),params:[]};if(X(F,YS))return{sql:S(F.value),params:[]};if(F===void 0)return{sql:"",params:[]};if(Array.isArray(F)){let $=[new ho("(")];for(let[W,O]of F.entries())if($.push(O),W<F.length-1)$.push(new ho(", "));return $.push(new ho(")")),this.buildQueryFromSourceParams($,T)}if(X(F,j))return this.buildQueryFromSourceParams(F.queryChunks,{...T,inlineParams:A||F.shouldInlineParams});if(X(F,I)){let $=F[I.Symbol.Schema],W=F[I.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[I.Symbol.Schema];return{sql:F.table[ES]||W===void 0?S(F.table[I.Symbol.Name])+"."+S($):S(W)+"."+S(F.table[I.Symbol.Name])+"."+S($),params:[]}}if(X(F,yn)){let $=F[Go].schema,W=F[Go].name;return{sql:$===void 0?S(W):S($)+"."+S(W),params:[]}}if(X(F,Jn)){if(X(F.value,fT))return{sql:f(M.value++,F),params:[F],typings:["none"]};let $=F.value===null?null:F.encoder.mapToDriverValue(F.value);if(X($,j))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,fT))return{sql:f(M.value++,F),params:[F],typings:["none"]};if(X(F,j.Aliased)&&F.fieldAlias!==void 0)return{sql:S(F.fieldAlias),params:[]};if(X(F,bo)){if(F._.isWith)return{sql:S(F._.alias),params:[]};return this.buildQueryFromSourceParams([new ho("("),F._.sql,new ho(") "),new YS(F._.alias)],T)}if(XM(F)){if(F.schema)return{sql:S(F.schema)+"."+S(F.enumName),params:[]};return{sql:S(F.enumName),params:[]}}if(oy(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 j.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 YS{constructor(o){this.value=o}static[k]="Name";brand;getSQL(){return new j([this])}}function mM(o){return typeof o==="object"&&o!==null&&"mapToDriverValue"in o&&typeof o.mapToDriverValue==="function"}var QM={mapFromDriverValue:(o)=>o},DM={mapToDriverValue:(o)=>o},YY={...QM,...DM};class Jn{constructor(o,n=DM){this.value=o,this.encoder=n}static[k]="Param";brand;getSQL(){return new j([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 j(T)}((o)=>{function n(){return new j([])}o.empty=n;function T(M){return new j(M)}o.fromList=T;function t(M){return new j([new ho(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 j($)}o.join=S;function f(M){return new YS(M)}o.identifier=f;function y(M){return new fT(M)}o.placeholder=y;function A(M,F){return new Jn(M,F)}o.param=A})(R||(R={}));((o)=>{class n{constructor(T,t){this.sql=T,this.fieldAlias=t}static[k]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new n(this.sql,this.fieldAlias)}}o.Aliased=n})(j||(j={}));class fT{constructor(o){this.name=o}static[k]="Placeholder";getSQL(){return new j([this])}}function ny(o,n){return o.map((T)=>{if(X(T,fT)){if(!(T.name in n))throw new Error(`No value for placeholder "${T.name}" was provided`);return n[T.name]}if(X(T,Jn)&&X(T.value,fT)){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})}var t0=Symbol.for("drizzle:IsDrizzleView");class yn{static[k]="View";[Go];[t0]=!0;constructor({name:o,schema:n,selectedFields:T,query:t}){this[Go]={name:o,originalName:o,schema:n,selectedFields:T,query:t,isExisting:!t,isAlias:!1}}getSQL(){return new j([this])}}Ro.prototype.getSQL=function(){return new j([this])};I.prototype.getSQL=function(){return new j([this])};bo.prototype.getSQL=function(){return new j([this])};class lT{constructor(o){this.table=o}static[k]="ColumnAliasProxyHandler";get(o,n){if(n==="table")return this.table;return o[n]}}class Ut{constructor(o,n){this.alias=o,this.replaceOriginalName=n}static[k]="TableAliasProxyHandler";get(o,n){if(n===I.Symbol.IsAlias)return!0;if(n===I.Symbol.Name)return this.alias;if(this.replaceOriginalName&&n===I.Symbol.OriginalName)return this.alias;if(n===Go)return{...o[Go],name:this.alias,isAlias:!0};if(n===I.Symbol.Columns){let t=o[I.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 GS(o,n){return new Proxy(o,new Ut(n,!1))}function bn(o,n){return new Proxy(o,new lT(new Proxy(o.table,new Ut(n,!1))))}function Ty(o,n){return new j.Aliased(Vt(o.sql,n),o.fieldAlias)}function Vt(o,n){return R.join(o.queryChunks.map((T)=>{if(X(T,Ro))return bn(T,n);if(X(T,j))return Vt(T,n);if(X(T,j.Aliased))return Ty(T,n);return T}))}class zS extends Error{static[k]="DrizzleError";constructor({message:o,cause:n}){super(o);this.name="DrizzleError",this.cause=n}}class ty extends zS{static[k]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}function An(o,n){if(mM(n)&&!oy(o)&&!X(o,Jn)&&!X(o,fT)&&!X(o,Ro)&&!X(o,I)&&!X(o,yn))return new Jn(o,n);return o}var HS=(o,n)=>{return R`${o} = ${An(n,o)}`},UM=(o,n)=>{return R`${o} <> ${An(n,o)}`};function Bt(...o){let n=o.filter((T)=>T!==void 0);if(n.length===0)return;if(n.length===1)return new j(n);return new j([new ho("("),R.join(n,new ho(" and ")),new ho(")")])}function VM(...o){let n=o.filter((T)=>T!==void 0);if(n.length===0)return;if(n.length===1)return new j(n);return new j([new ho("("),R.join(n,new ho(" or ")),new ho(")")])}function BM(o){return R`not ${o}`}var CM=(o,n)=>{return R`${o} > ${An(n,o)}`},LM=(o,n)=>{return R`${o} >= ${An(n,o)}`},IM=(o,n)=>{return R`${o} < ${An(n,o)}`},jM=(o,n)=>{return R`${o} <= ${An(n,o)}`};function rM(o,n){if(Array.isArray(n)){if(n.length===0)return R`false`;return R`${o} in ${n.map((T)=>An(T,o))}`}return R`${o} in ${An(n,o)}`}function NM(o,n){if(Array.isArray(n)){if(n.length===0)return R`true`;return R`${o} not in ${n.map((T)=>An(T,o))}`}return R`${o} not in ${An(n,o)}`}function bM(o){return R`${o} is null`}function hM(o){return R`${o} is not null`}function xM(o){return R`exists ${o}`}function cM(o){return R`not exists ${o}`}function vM(o,n,T){return R`${o} between ${An(n,o)} and ${An(T,o)}`}function iM(o,n,T){return R`${o} not between ${An(n,o)} and ${An(T,o)}`}function pM(o,n){return R`${o} like ${n}`}function qM(o,n){return R`${o} not like ${n}`}function ZM(o,n){return R`${o} ilike ${n}`}function PM(o,n){return R`${o} not ilike ${n}`}function gM(o){return R`${o} asc`}function lM(o){return R`${o} desc`}class eM{static[k]="ConsoleLogWriter";write(o){console.log(o)}}class Sy{static[k]="DefaultLogger";writer;constructor(o){this.writer=o?.writer??new eM}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 fy{static[k]="NoopLogger";logQuery(){}}class nn{static[k]="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 dM(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,j))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?wn(A.table):!1;else if(typeof t[z]==="string"&&t[z]!==wn(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 Kn(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,j)||X(S,j.Aliased))T.push({path:f,field:S});else if(X(S,I))T.push(...Kn(S[I.Symbol.Columns],f));else T.push(...Kn(S,f));return T},[])}function Ct(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 mS(o,n){let T=Object.entries(n).filter(([,t])=>t!==void 0).map(([t,S])=>{if(X(S,j)||X(S,Ro))return[t,S];else return[t,new Jn(S,o[I.Symbol.Columns][t])]});if(T.length===0)throw new Error("No values to set");return Object.fromEntries(T)}function uM(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 aM(o){return o[I.Symbol.Columns]}function ln(o){return X(o,bo)?o._.alias:X(o,yn)?o[Go].name:X(o,j)?void 0:o[I.Symbol.IsAlias]?o[I.Symbol.Name]:o[I.Symbol.BaseName]}function So(o,n){return{name:typeof o==="string"&&o.length>0?o:"",config:typeof o==="object"?o:n}}function sM(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 yT extends b{static[k]="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 oF extends yT{static[k]="PgBigInt53Builder";constructor(o){super(o,"number","PgBigInt53")}build(o){return new nF(o,this.config)}}class nF extends V{static[k]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}}class TF extends yT{static[k]="PgBigInt64Builder";constructor(o){super(o,"bigint","PgBigInt64")}build(o){return new tF(o,this.config)}}class tF extends V{static[k]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(o){return BigInt(o)}}function SF(o,n){let{name:T,config:t}=So(o,n);if(t.mode==="number")return new oF(T);return new TF(T)}class fF extends b{static[k]="PgBigSerial53Builder";constructor(o){super(o,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new yF(o,this.config)}}class yF extends V{static[k]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}}class AF extends b{static[k]="PgBigSerial64Builder";constructor(o){super(o,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(o){return new MF(o,this.config)}}class MF extends V{static[k]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(o){return BigInt(o)}}function FF(o,n){let{name:T,config:t}=So(o,n);if(t.mode==="number")return new fF(T);return new AF(T)}class $F extends b{static[k]="PgBooleanBuilder";constructor(o){super(o,"boolean","PgBoolean")}build(o){return new JF(o,this.config)}}class JF extends V{static[k]="PgBoolean";getSQLType(){return"boolean"}}function Lt(o){return new $F(o??"")}class kF extends b{static[k]="PgCharBuilder";constructor(o,n){super(o,"string","PgChar");this.config.length=n.length,this.config.enumValues=n.enum}build(o){return new RF(o,this.config)}}class RF extends V{static[k]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function WF(o,n={}){let{name:T,config:t}=So(o,n);return new kF(T,t)}class OF extends b{static[k]="PgCidrBuilder";constructor(o){super(o,"string","PgCidr")}build(o){return new _F(o,this.config)}}class _F extends V{static[k]="PgCidr";getSQLType(){return"cidr"}}function wF(o){return new OF(o??"")}class KF extends b{static[k]="PgCustomColumnBuilder";constructor(o,n,T){super(o,"custom","PgCustomColumn");this.config.fieldConfig=n,this.config.customTypeParams=T}build(o){return new XF(o,this.config)}}class XF extends V{static[k]="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 EF(o){return(n,T)=>{let{name:t,config:S}=So(n,T);return new KF(t,S,o)}}class en extends b{static[k]="PgDateColumnBaseBuilder";defaultNow(){return this.default(R`now()`)}}class YF extends en{static[k]="PgDateBuilder";constructor(o){super(o,"date","PgDate")}build(o){return new QS(o,this.config)}}class QS extends V{static[k]="PgDate";getSQLType(){return"date"}mapFromDriverValue(o){return new Date(o)}mapToDriverValue(o){return o.toISOString()}}class GF extends en{static[k]="PgDateStringBuilder";constructor(o){super(o,"string","PgDateString")}build(o){return new DS(o,this.config)}}class DS extends V{static[k]="PgDateString";getSQLType(){return"date"}}function zF(o,n){let{name:T,config:t}=So(o,n);if(t?.mode==="date")return new YF(T);return new GF(T)}class HF extends b{static[k]="PgDoublePrecisionBuilder";constructor(o){super(o,"number","PgDoublePrecision")}build(o){return new mF(o,this.config)}}class mF extends V{static[k]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseFloat(o);return o}}function QF(o){return new HF(o??"")}class DF extends b{static[k]="PgInetBuilder";constructor(o){super(o,"string","PgInet")}build(o){return new UF(o,this.config)}}class UF extends V{static[k]="PgInet";getSQLType(){return"inet"}}function VF(o){return new DF(o??"")}class BF extends yT{static[k]="PgIntegerBuilder";constructor(o){super(o,"number","PgInteger")}build(o){return new CF(o,this.config)}}class CF extends V{static[k]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseInt(o);return o}}function US(o){return new BF(o??"")}class LF extends b{static[k]="PgIntervalBuilder";constructor(o,n){super(o,"string","PgInterval");this.config.intervalConfig=n}build(o){return new IF(o,this.config)}}class IF extends V{static[k]="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 jF(o,n={}){let{name:T,config:t}=So(o,n);return new LF(T,t)}class rF extends b{static[k]="PgJsonBuilder";constructor(o){super(o,"json","PgJson")}build(o){return new VS(o,this.config)}}class VS extends V{static[k]="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 NF(o){return new rF(o??"")}class bF extends b{static[k]="PgJsonbBuilder";constructor(o){super(o,"json","PgJsonb")}build(o){return new BS(o,this.config)}}class BS extends V{static[k]="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 hF(o){return new bF(o??"")}class xF extends b{static[k]="PgLineBuilder";constructor(o){super(o,"array","PgLine")}build(o){return new cF(o,this.config)}}class cF extends V{static[k]="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 vF extends b{static[k]="PgLineABCBuilder";constructor(o){super(o,"json","PgLineABC")}build(o){return new iF(o,this.config)}}class iF extends V{static[k]="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 pF(o,n){let{name:T,config:t}=So(o,n);if(!t?.mode||t.mode==="tuple")return new xF(T);return new vF(T)}class qF extends b{static[k]="PgMacaddrBuilder";constructor(o){super(o,"string","PgMacaddr")}build(o){return new ZF(o,this.config)}}class ZF extends V{static[k]="PgMacaddr";getSQLType(){return"macaddr"}}function PF(o){return new qF(o??"")}class gF extends b{static[k]="PgMacaddr8Builder";constructor(o){super(o,"string","PgMacaddr8")}build(o){return new lF(o,this.config)}}class lF extends V{static[k]="PgMacaddr8";getSQLType(){return"macaddr8"}}function eF(o){return new gF(o??"")}class dF extends b{static[k]="PgNumericBuilder";constructor(o,n,T){super(o,"string","PgNumeric");this.config.precision=n,this.config.scale=T}build(o){return new CS(o,this.config)}}class CS extends V{static[k]="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 uF(o,n){let{name:T,config:t}=So(o,n);return new dF(T,t?.precision,t?.scale)}class aF extends b{static[k]="PgPointTupleBuilder";constructor(o){super(o,"array","PgPointTuple")}build(o){return new sF(o,this.config)}}class sF extends V{static[k]="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 o$ extends b{static[k]="PgPointObjectBuilder";constructor(o){super(o,"json","PgPointObject")}build(o){return new n$(o,this.config)}}class n$ extends V{static[k]="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 T$(o,n){let{name:T,config:t}=So(o,n);if(!t?.mode||t.mode==="tuple")return new aF(T);return new o$(T)}function S0(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 t$(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 yy(o){let n=S0(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=t$(n,T);T+=8;let M=t$(n,T);return T+=8,[A,M]}throw new Error("Unsupported geometry type")}class S$ extends b{static[k]="PgGeometryBuilder";constructor(o){super(o,"array","PgGeometry")}build(o){return new f$(o,this.config)}}class f$ extends V{static[k]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(o){return yy(o)}mapToDriverValue(o){return`point(${o[0]} ${o[1]})`}}class y$ extends b{static[k]="PgGeometryObjectBuilder";constructor(o){super(o,"json","PgGeometryObject")}build(o){return new A$(o,this.config)}}class A$ extends V{static[k]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(o){let n=yy(o);return{x:n[0],y:n[1]}}mapToDriverValue(o){return`point(${o.x} ${o.y})`}}function M$(o,n){let{name:T,config:t}=So(o,n);if(!t?.mode||t.mode==="tuple")return new S$(T);return new y$(T)}class F$ extends b{static[k]="PgRealBuilder";constructor(o,n){super(o,"number","PgReal");this.config.length=n}build(o){return new $$(o,this.config)}}class $$ extends V{static[k]="PgReal";constructor(o,n){super(o,n)}getSQLType(){return"real"}mapFromDriverValue=(o)=>{if(typeof o==="string")return Number.parseFloat(o);return o}}function J$(o){return new F$(o??"")}class k$ extends b{static[k]="PgSerialBuilder";constructor(o){super(o,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new R$(o,this.config)}}class R$ extends V{static[k]="PgSerial";getSQLType(){return"serial"}}function W$(o){return new k$(o??"")}class O$ extends yT{static[k]="PgSmallIntBuilder";constructor(o){super(o,"number","PgSmallInt")}build(o){return new _$(o,this.config)}}class _$ extends V{static[k]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(o)=>{if(typeof o==="string")return Number(o);return o}}function w$(o){return new O$(o??"")}class K$ extends b{static[k]="PgSmallSerialBuilder";constructor(o){super(o,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new X$(o,this.config)}}class X$ extends V{static[k]="PgSmallSerial";getSQLType(){return"smallserial"}}function E$(o){return new K$(o??"")}class Y$ extends b{static[k]="PgTextBuilder";constructor(o,n){super(o,"string","PgText");this.config.enumValues=n.enum}build(o){return new G$(o,this.config)}}class G$ extends V{static[k]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function z$(o,n={}){let{name:T,config:t}=So(o,n);return new Y$(T,t)}class H$ extends en{constructor(o,n,T){super(o,"string","PgTime");this.withTimezone=n,this.precision=T,this.config.withTimezone=n,this.config.precision=T}static[k]="PgTimeBuilder";build(o){return new LS(o,this.config)}}class LS extends V{static[k]="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 m$(o,n={}){let{name:T,config:t}=So(o,n);return new H$(T,t.withTimezone??!1,t.precision)}class Q$ extends en{static[k]="PgTimestampBuilder";constructor(o,n,T){super(o,"date","PgTimestamp");this.config.withTimezone=n,this.config.precision=T}build(o){return new IS(o,this.config)}}class IS extends V{static[k]="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 D$ extends en{static[k]="PgTimestampStringBuilder";constructor(o,n,T){super(o,"string","PgTimestampString");this.config.withTimezone=n,this.config.precision=T}build(o){return new jS(o,this.config)}}class jS extends V{static[k]="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 Cn(o,n={}){let{name:T,config:t}=So(o,n);if(t?.mode==="string")return new D$(T,t.withTimezone??!1,t.precision);return new Q$(T,t?.withTimezone??!1,t?.precision)}class U$ extends b{static[k]="PgUUIDBuilder";constructor(o){super(o,"string","PgUUID")}defaultRandom(){return this.default(R`gen_random_uuid()`)}build(o){return new rS(o,this.config)}}class rS extends V{static[k]="PgUUID";getSQLType(){return"uuid"}}function kn(o){return new U$(o??"")}class V$ extends b{static[k]="PgVarcharBuilder";constructor(o,n){super(o,"string","PgVarchar");this.config.length=n.length,this.config.enumValues=n.enum}build(o){return new B$(o,this.config)}}class B$ extends V{static[k]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function co(o,n={}){let{name:T,config:t}=So(o,n);return new V$(T,t)}class C$ extends b{static[k]="PgBinaryVectorBuilder";constructor(o,n){super(o,"string","PgBinaryVector");this.config.dimensions=n.dimensions}build(o){return new L$(o,this.config)}}class L$ extends V{static[k]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function I$(o,n){let{name:T,config:t}=So(o,n);return new C$(T,t)}class j$ extends b{static[k]="PgHalfVectorBuilder";constructor(o,n){super(o,"array","PgHalfVector");this.config.dimensions=n.dimensions}build(o){return new r$(o,this.config)}}class r$ extends V{static[k]="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 N$(o,n){let{name:T,config:t}=So(o,n);return new j$(T,t)}class b$ extends b{static[k]="PgSparseVectorBuilder";constructor(o,n){super(o,"string","PgSparseVector");this.config.dimensions=n.dimensions}build(o){return new h$(o,this.config)}}class h$ extends V{static[k]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function x$(o,n){let{name:T,config:t}=So(o,n);return new b$(T,t)}class c$ extends b{static[k]="PgVectorBuilder";constructor(o,n){super(o,"array","PgVector");this.config.dimensions=n.dimensions}build(o){return new v$(o,this.config)}}class v$ extends V{static[k]="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 i$(o,n){let{name:T,config:t}=So(o,n);return new c$(T,t)}function p$(){return{bigint:SF,bigserial:FF,boolean:Lt,char:WF,cidr:wF,customType:EF,date:zF,doublePrecision:QF,inet:VF,integer:US,interval:jF,json:NF,jsonb:hF,line:pF,macaddr:PF,macaddr8:eF,numeric:uF,point:T$,geometry:M$,real:J$,serial:W$,smallint:w$,smallserial:E$,text:z$,time:m$,timestamp:Cn,uuid:kn,varchar:co,bit:I$,halfvec:N$,sparsevec:x$,vector:i$}}var Ay=Symbol.for("drizzle:PgInlineForeignKeys"),q$=Symbol.for("drizzle:EnableRLS");class vo extends I{static[k]="PgTable";static Symbol=Object.assign({},I.Symbol,{InlineForeignKeys:Ay,EnableRLS:q$});[Ay]=[];[q$]=!1;[I.Symbol.ExtraConfigBuilder]=void 0}function f0(o,n,T,t,S=o){let f=new vo(o,t,S),y=typeof n==="function"?n(p$()):n,A=Object.fromEntries(Object.entries(y).map(([$,W])=>{let O=W;O.setName($);let G=O.build(f);return f[Ay].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[I.Symbol.Columns]=A,F[I.Symbol.ExtraConfigColumns]=M,T)F[vo.Symbol.ExtraConfigBuilder]=T;return Object.assign(F,{enableRLS:()=>{return F[vo.Symbol.EnableRLS]=!0,F}})}var AT=(o,n,T)=>{return f0(o,n,T,void 0)};function Z$(...o){if(o[0].columns)return new It(o[0].columns,o[0].name);return new It(o)}class It{static[k]="PgPrimaryKeyBuilder";columns;name;constructor(o,n){this.columns=o,this.name=n}build(o){return new P$(o,this.columns,this.name)}}class P${constructor(o,n,T){this.table=o,this.columns=n,this.name=T}static[k]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[vo.Symbol.Name]}_${this.columns.map((o)=>o.name).join("_")}_pk`}}class My{constructor(o,n,T){this.sourceTable=o,this.referencedTable=n,this.relationName=T,this.referencedTableName=n[I.Symbol.Name]}static[k]="Relation";referencedTableName;fieldName}class g${constructor(o,n){this.table=o,this.config=n}static[k]="Relations"}class MT extends My{constructor(o,n,T,t){super(o,n,T?.relationName);this.config=T,this.isNullable=t}static[k]="One";withFieldName(o){let n=new MT(this.sourceTable,this.referencedTable,this.config,this.isNullable);return n.fieldName=o,n}}class jt extends My{constructor(o,n,T){super(o,n,T?.relationName);this.config=T}static[k]="Many";withFieldName(o){let n=new jt(this.sourceTable,this.referencedTable,this.config);return n.fieldName=o,n}}function l$(){return{and:Bt,between:vM,eq:HS,exists:xM,gt:CM,gte:LM,ilike:ZM,inArray:rM,isNull:bM,isNotNull:hM,like:pM,lt:IM,lte:jM,ne:UM,not:BM,notBetween:iM,notExists:cM,notLike:qM,notIlike:PM,notInArray:NM,or:VM,sql:R}}function e$(){return{sql:R,asc:gM,desc:lM}}function d$(o,n){if(Object.keys(o).length===1&&"default"in o&&!X(o.default,I))o=o.default;let T={},t={},S={};for(let[f,y]of Object.entries(o))if(X(y,I)){let A=_T(y),M=t[A];T[A]=f,S[f]={tsName:f,dbName:y[I.Symbol.Name],schema:y[I.Symbol.Schema],columns:y[I.Symbol.Columns],relations:M?.relations??{},primaryKey:M?.primaryKey??[]};for(let $ of Object.values(y[I.Symbol.Columns]))if($.primary)S[f].primaryKey.push($);let F=y[I.Symbol.ExtraConfigBuilder]?.(y[I.Symbol.ExtraConfigColumns]);if(F){for(let $ of Object.values(F))if(X($,It))S[f].primaryKey.push(...$.columns)}}else if(X(y,g$)){let A=_T(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 y0(o){return function n(T,t){return new MT(o,T,t,t?.fields.reduce((S,f)=>S&&f.notNull,!0)??!1)}}function A0(o){return function n(T,t){return new jt(o,T,t)}}function u$(o,n,T){if(X(T,MT)&&T.config)return{fields:T.config.fields,references:T.config.references};let t=n[_T(T.referencedTable)];if(!t)throw new Error(`Table "${T.referencedTable[I.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[_T(f)];if(!y)throw new Error(`Table "${f[I.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[I.Symbol.Name]}". Please specify relation name`);if(A[0]&&X(A[0],MT)&&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 a$(o){return{one:y0(o),many:A0(o)}}function NS(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,MT)?$&&NS(o,o[A.relationTableTsKey],$,A.selection,S):$.map((W)=>NS(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,j))$=F.decoder;else $=F.sql.decoder;f[A.tsKey]=M===null?null:$.mapFromDriverValue(M)}return f}import C0 from"os";import L0 from"fs";var bS=new Map,Fy=new Map,$y=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[$y]=this.handler.debug?new Error:this.tagged&&M0(this.strings)}get origin(){return(this.handler.debug?this[$y].stack:this.tagged&&Fy.has(this.strings)?Fy.get(this.strings):Fy.set(this.strings,this[$y].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 M0(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:s$,postgres:oJ,generic:nJ,notSupported:TJ};function s$(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,s$),f}function oJ(o){let n=new dT(o);return Error.captureStackTrace(n,oJ),n}function nJ(o,n){let T=Object.assign(new Error(o+": "+n),{code:o});return Error.captureStackTrace(T,nJ),T}function TJ(o){let n=Object.assign(new Error(o+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:o});return Error.captureStackTrace(n,TJ),n}var F0={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 cS{then(){Jy()}catch(){Jy()}finally(){Jy()}}class ht extends cS{constructor(o){super();this.value=pS(o)}}class hn extends cS{constructor(o,n,T){super();this.value=o,this.type=n,this.array=T}}class vS extends cS{constructor(o,n){super();this.first=o,this.rest=n}build(o,n,T,t){let S=$0.map(([f,y])=>({fn:y,i:o.search(f)})).sort((f,y)=>f.i-y.i).pop();return S.i===-1?_y(this.first,t):S.fn(this.first,this.rest,n,T,t)}}function iS(o,n,T,t){let S=o instanceof hn?o.value:o;if(S===void 0){if(o instanceof hn?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 hn?(n.push(o.value),o.array?o.array[o.type||xS(o.value)]||o.type||yJ(o.value):o.type):(n.push(o),xS(o)))}var SJ=MJ(F0);function Wy(o,n,T,t,S,f){for(let y=1;y<o.strings.length;y++)n+=Oy(n,T,t,S,f)+o.strings[y],T=o.args[y];return n}function Oy(o,n,T,t,S){return n instanceof vS?n.build(o,T,t,S):n instanceof Xn?Ry(n,T,t,S):n instanceof ht?n.value:n&&n[0]instanceof Xn?n.reduce((f,y)=>f+" "+Ry(y,T,t,S),""):iS(n,T,t,S)}function Ry(o,n,T,t){return o.fragment=!0,Wy(o,o.strings[0],o.args[0],n,T,t)}function fJ(o,n,T,t,S){return o.map((f)=>"("+t.map((y)=>Oy("values",f[y],n,T,S)).join(",")+")").join(",")}function tJ(o,n,T,t,S){let f=Array.isArray(o[0]),y=n.length?n.flat():Object.keys(f?o[0]:o);return fJ(f?o:[o],T,t,y,S)}function hS(o,n,T,t,S){if(typeof o==="string"&&(o=[o].concat(n)),Array.isArray(o))return _y(o,S);let f;return(n.length?n.flat():Object.keys(o)).map((A)=>{return f=o[A],(f instanceof Xn?Ry(f,T,t,S):f instanceof ht?f.value:iS(f,T,t,S))+" as "+pS(S.transform.column.to?S.transform.column.to(A):A)}).join(",")}var $0=Object.entries({values:tJ,in:(...o)=>{let n=tJ(...o);return n==="()"?"(null)":n},select:hS,as:hS,returning:hS,"\\(":hS,update(o,n,T,t,S){return(n.length?n.flat():Object.keys(o)).map((f)=>pS(S.transform.column.to?S.transform.column.to(f):f)+"="+Oy("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"("+_y(f,S)+")values"+fJ(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:J0,parsers:k0}=SJ;function yJ(o){if(Array.isArray(o))return yJ(o[0]);return typeof o==="string"?1009:0}var AJ=function(o){let n=MJ(o||{});return{serializers:Object.assign({},J0,n.serializers),parsers:Object.assign({},k0,n.parsers)}};function MJ(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 _y(o,{transform:{column:n}}){return o.map((T)=>pS(n.to?n.to(T):T)).join(",")}var pS=function o(n){return'"'+n.replace(/"/g,'""').replace(/\./g,'"."')+'"'},xS=function o(n){return n instanceof hn?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},R0=/\\/g,W0=/"/g;function O0(o){return o.replace(R0,"\\\\").replace(W0,"\\\"")}var FJ=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":'"'+O0(T?T(A.type?A.value:A):""+A)+'"'}).join(y)+"}"},ky={i:0,char:null,str:"",quoted:!1,last:0},$J=function o(n,T,t){return ky.i=ky.last=0,JJ(ky,n,T,t)};function JJ(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(JJ(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 wT=(o)=>{let n=o[0];for(let T=1;T<o.length;T++)n+=o[T]==="_"?o[++T].toUpperCase():o[T];return n},KT=(o)=>{let n=o[0].toUpperCase();for(let T=1;T<o.length;T++)n+=o[T]==="_"?o[++T].toUpperCase():o[T];return n},XT=(o)=>o.replace(/_/g,"-"),rt=(o)=>o.replace(/([A-Z])/g,"_$1").toLowerCase(),Nt=(o)=>(o.slice(0,1)+o.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),bt=(o)=>o.replace(/-/g,"_");function wy(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}}wT.column={from:wT};wT.value={from:wy(wT)};rt.column={to:rt};var Ky={...wT};Ky.column.to=rt;KT.column={from:KT};KT.value={from:wy(KT)};Nt.column={to:Nt};var Xy={...KT};Xy.column.to=Nt;XT.column={from:XT};XT.value={from:wy(XT)};bt.column={to:bt};var Ey={...XT};Ey.column.to=bt;import kJ from"net";import X0 from"tls";import xt from"crypto";import Yy from"stream";import{performance as RJ}from"perf_hooks";class ET 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),w0="BCcDdEFfHPpQSX".split("").reduce((o,n)=>{let T=n.charCodeAt(0);return o[n]=()=>{return uo[0]=T,ko.i=5,ko},o},{}),ko=Object.assign(K0,w0,{N:String.fromCharCode(0),i:0,inc(o){return ko.i+=o,ko},str(o){let n=Buffer.byteLength(o);return qS(n),ko.i+=uo.write(o,ko.i,n,"utf8"),ko},i16(o){return qS(2),uo.writeUInt16BE(o,ko.i),ko.i+=2,ko},i32(o,n){if(n||n===0)return uo.writeUInt32BE(o,n),ko;return qS(4),uo.writeUInt32BE(o,ko.i),ko.i+=4,ko},z(o){return qS(o),uo.fill(0,ko.i,ko.i+o),ko.i+=o,ko},raw(o){return uo=Buffer.concat([uo.subarray(0,ko.i),o]),ko.i=uo.length,ko},end(o=1){uo.writeUInt32BE(ko.i-o,o);let n=uo.subarray(0,ko.i);return ko.i=0,uo=Buffer.allocUnsafe(256),n}}),P=ko;function qS(o){if(uo.length-ko.i<o){let n=uo,T=n.length;uo=Buffer.allocUnsafe(T+(T>>1)+o),n.copy(uo)}}function K0(){return ko.i=0,ko}var Hy=_J,E0=1,FT=P().S().end(),WJ=P().H().end(),Y0=P().i32(8).i32(80877103).end(8),G0=Buffer.concat([P().E().str(P.N).i32(0).end(),FT]),z0=P().D().str("S").str(P.N).end(),uT=()=>{},H0=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),m0={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 _J(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:p,target_session_attrs:c}=o,a=Rn(),E=E0++,K={pid:null,secret:null},Q=zy(tf,o.idle_timeout),x=zy(tf,o.max_lifetime),h=zy(hJ,o.connect_timeout),w=null,v,N=new ET,q=Buffer.alloc(0),Jo=o.fetch_types,Oo={},tn={},xn=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,dn=null,jo=null,Xo=null,Yn=null,Ln=null,C=null,nt=null,Zo={queue:n.closed,idleTimer:Q,connect(J){qo=J||!0,uy()},terminate:tt,execute:Tt,cancel:jJ,end:tf,count:0,id:E};return n.closed&&n.closed.push(Zo),Zo;async function IJ(){let J;try{J=o.socket?await Promise.resolve(o.socket(o)):new kJ.Socket}catch(_){HT(_);return}return J.on("error",HT),J.on("close",ay),J.on("drain",ey),J}async function jJ({pid:J,secret:_},g,$o){try{v=P().i32(16).i32(80877102).i32(J).i32(_).end(16),await dy(),w.once("error",$o),w.once("close",g)}catch(Uo){$o(Uo)}}function Tt(J){if(po)return Pt(J,Lo.connection("CONNECTION_DESTROYED",o));if(J.cancelled)return;try{return J.state=K,C?a.push(J):(C=J,C.active=!0),bJ(J),xo(rJ(J))&&!J.describeFirst&&!J.cursorFn&&a.length<Y&&(!J.options.onexecute||J.options.onexecute(Zo))}catch(_){return a.length===0&&xo(FT),In(_),!0}}function rJ(J){if(J.parameters.length>=65534)throw Lo.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return J.options.simple?P().Q().str(J.statement.string+P.N).end():J.describeFirst?Buffer.concat([Py(J),WJ]):J.prepare?J.prepared?Zt(J):Buffer.concat([Py(J),Zt(J)]):NJ(J)}function Py(J){return Buffer.concat([oA(J.statement.string,J.parameters,J.statement.types,J.statement.name),Gk("S",J.statement.name)])}function Zt(J){return Buffer.concat([Yk(J.parameters,J.statement.types,J.statement.name,J.cursorName),J.cursorFn?nA("",J.cursorRows):G0])}function NJ(J){return Buffer.concat([oA(J.statement.string,J.parameters,J.statement.types),z0,Zt(J)])}function bJ(J){let _=[],g=[],$o=Wy(J,J.strings[0],J.args[0],_,g,o);!J.tagged&&J.args.forEach((Uo)=>iS(Uo,_,g,o)),J.prepare=o.prepare&&("prepare"in J.options?J.options.prepare:!0),J.string=$o,J.signature=J.prepare&&g+$o,J.onlyDescribe&&delete tn[J.signature],J.parameters=J.parameters||_,J.prepared=J.prepare&&J.signature in tn,J.describeFirst=J.onlyDescribe||_.length&&!J.prepared,J.statement=J.prepared?tn[J.signature]:{string:$o,types:g,name:J.prepare?xn+H++:""},typeof o.debug==="function"&&o.debug(E,$o,_,g)}function xo(J,_){if(Xo=Xo?Buffer.concat([Xo,J]):Buffer.from(J),_||Xo.length>=1024)return gy(_);return Ko===null&&(Ko=setImmediate(gy)),!0}function gy(J){let _=w.write(Xo,J);return Ko!==null&&clearImmediate(Ko),Xo=Ko=null,_}function hJ(){In(Lo.connection("CONNECT_TIMEOUT",o,w)),w.destroy()}async function ly(){if(xo(Y0),!await new Promise((_)=>w.once("data",(g)=>_(g[0]===83)))&&f==="prefer")return zT();w.removeAllListeners(),w=X0.connect({socket:w,servername:kJ.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",zT),w.on("error",HT),w.on("close",ay),w.on("drain",ey)}function ey(){!C&&T(Zo)}function Tf(J){if(wo){if(wo.push(J),Fo-=J.length,Fo>=0)return}q=wo?Buffer.concat(wo,To-Fo):q.length===0?J:Buffer.concat([q,J],q.length+J.length);while(q.length>4){if(To=q.readUInt32BE(1),To>=q.length){Fo=To-q.length,wo=[q];break}try{xJ(q.subarray(0,To+1))}catch(_){C&&(C.cursorFn||C.describeFirst)&&xo(FT),In(_)}q=q.subarray(To+1),Fo=0,wo=null}}async function dy(){if(po=!1,Oo={},w||(w=await IJ()),!w)return;if(h.start(),o.socket)return f?ly():zT();if(w.on("connect",f?ly:zT),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 uy(){setTimeout(dy,Z?Z+_o-RJ.now():0)}function zT(){try{tn={},Jo=o.fetch_types,xn=Math.random().toString(36).slice(2),H=1,x.start(),w.on("data",Tf),B&&w.setKeepAlive&&w.setKeepAlive(!0,1000*B);let J=Hk();xo(J)}catch(J){HT(J)}}function HT(J){if(Zo.queue===n.connecting&&o.host[Io+1])return;In(J);while(a.length)Pt(a.shift(),J)}function In(J){jo&&(jo.destroy(J),jo=null),C&&Pt(C,J),qo&&(Pt(qo,J),qo=null)}function Pt(J,_){"query"in _||"parameters"in _||Object.defineProperties(_,{stack:{value:_.stack+J.origin.replace(/.*\n/,`
10
- `),enumerable:o.debug},query:{value:J.string,enumerable:o.debug},parameters:{value:J.parameters,enumerable:o.debug},args:{value:J.args,enumerable:o.debug},types:{value:J.statement&&J.statement.types,enumerable:o.debug}}),J.reject(_)}function tf(){return dn||(!Zo.reserved&&t(Zo),!Zo.reserved&&!qo&&!C&&a.length===0?(tt(),new Promise((J)=>w&&w.readyState!=="closed"?w.once("close",J):J())):dn=new Promise((J)=>Yn=J))}function tt(){if(po=!0,jo||C||qo||a.length)HT(Lo.connection("CONNECTION_DESTROYED",o));if(clearImmediate(Ko),w)w.removeListener("data",Tf),w.removeListener("connect",zT),w.readyState==="open"&&w.end(P().X().end());Yn&&(Yn(),dn=Yn=null)}async function ay(J){if(q=Buffer.alloc(0),Fo=0,wo=null,clearImmediate(Ko),w.removeListener("data",Tf),w.removeListener("connect",zT),Q.cancel(),x.cancel(),h.cancel(),w.removeAllListeners(),w=null,qo)return uy();!J&&(C||a.length)&&HT(Lo.connection("CONNECTION_CLOSED",o,w)),Z=RJ.now(),J&&o.shared.retries++,_o=(typeof p==="function"?p(o.shared.retries):p)*1000,S(Zo,Lo.connection("CONNECTION_CLOSED",o,w))}function xJ(J,_=J[0]){(_===68?cJ:_===100?Rk:_===65?Ak:_===83?vJ:_===90?iJ:_===67?pJ:_===50?sy:_===49?qJ:_===116?ZJ:_===84?PJ:_===82?gJ:_===110?sJ:_===75?ok:_===69?fk:_===115?Mk:_===51?Fk:_===71?$k:_===78?Ok:_===72?Jk:_===99?Wk:_===73?_k:_===86?wk:_===118?Kk:_===87?kk:Xk)(J)}function cJ(J){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=J.readInt32BE(_),_+=4,Uo=g===-1?null:C.isRaw===!0?J.subarray(_,_+=g):$o.parser===void 0?J.toString("utf8",_,_+=g):$o.parser.array===!0?$o.parser(J.toString("utf8",_+1,_+=g)):$o.parser(J.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 vJ(J){let[_,g]=J.toString("utf8",5,J.length-1).split(P.N);if(Oo[_]=g,o.parameters[_]!==g)o.parameters[_]=g,z&&z(_,g)}function iJ(J){if(C&&C.options.simple&&C.resolve(En||N),C=En=null,N=new ET,h.cancel(),qo){if(c){if(!Oo.in_hot_standby||!Oo.default_transaction_read_only)return Sk();else if(tk(c,Oo))return tt()}if(Jo)return qo===!0&&(qo=null),nk();qo!==!0&&Tt(qo),o.shared.retries=Io=0,qo=null;return}while(a.length&&(C=a.shift())&&(C.active=!0,C.cancelled))_J(o).cancel(C.state,C.cancelled.resolve,C.cancelled.reject);if(C)return;Zo.reserved?!Zo.reserved.release&&J[5]===73?dn?tt():(Zo.reserved=null,T(Zo)):Zo.reserved():dn?tt():T(Zo)}function pJ(J){Co=0;for(let _=J.length-1;_>0;_--){if(J[_]===32&&J[_+1]<58&&N.count===null)N.count=+J.toString("utf8",_+1,J.length-1);if(J[_-1]>=65){N.command=J.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 sy();if(C.cursorFn)N.count&&C.cursorFn(N),xo(FT);C.resolve(N)}function qJ(){C.parsing=!1}function sy(){!N.statement&&(N.statement=C.statement),N.columns=C.statement.columns}function ZJ(J){let _=J.readUInt16BE(5);for(let g=0;g<_;++g)!C.statement.types[g]&&(C.statement.types[g]=J.readUInt32BE(7+g*4));C.prepare&&(tn[C.signature]=C.statement),C.describeFirst&&!C.onlyDescribe&&(xo(Zt(C)),C.describeFirst=!1)}function PJ(J){if(N.command)En=En||[N],En.push(N=new ET),N.count=null,C.statement.columns=null;let _=J.readUInt16BE(5),g=7,$o;C.statement.columns=Array(_);for(let Uo=0;Uo<_;++Uo){$o=g;while(J[g++]!==0);let Po=J.readUInt32BE(g),ao=J.readUInt16BE(g+4),un=J.readUInt32BE(g+6);C.statement.columns[Uo]={name:O.column.from?O.column.from(J.toString("utf8",$o,g-1)):J.toString("utf8",$o,g-1),parser:W[un],table:Po,number:ao,type:un},g+=18}if(N.statement=C.statement,C.onlyDescribe)return C.resolve(C.statement),xo(FT)}async function gJ(J,_=J.readUInt32BE(5)){(_===3?lJ:_===5?eJ:_===10?dJ:_===11?uJ:_===12?aJ:_!==0?Ek:uT)(J,_)}async function lJ(){let J=await Sf();xo(P().p().str(J).z(1).end())}async function eJ(J){let _="md5"+await OJ(Buffer.concat([Buffer.from(await OJ(await Sf()+A)),J.subarray(9)]));xo(P().p().str(_).z(1).end())}async function dJ(){Ln=(await xt.randomBytes(18)).toString("base64"),P().p().str("SCRAM-SHA-256"+P.N);let J=P.i;xo(P.inc(4).str("n,,n=*,r="+Ln).i32(P.i-J-4,J).end())}async function uJ(J){let _=J.toString("utf8",9).split(",").reduce((ao,un)=>(ao[un[0]]=un.slice(2),ao),{}),g=await xt.pbkdf2Sync(await Sf(),Buffer.from(_.s,"base64"),parseInt(_.i),32,"sha256"),$o=await ZS(g,"Client Key"),Uo="n=*,r="+Ln+",r="+_.r+",s="+_.s+",i="+_.i+",c=biws,r="+_.r;mo=(await ZS(await ZS(g,"Server Key"),Uo)).toString("base64");let Po="c=biws,r="+_.r+",p="+D0($o,Buffer.from(await ZS(await Q0($o),Uo))).toString("base64");xo(P().p().str(Po).end())}function aJ(J){if(J.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 Sf(){return Promise.resolve(typeof o.pass==="function"?o.pass():o.pass)}function sJ(){if(N.statement=C.statement,N.statement.columns=[],C.onlyDescribe)return C.resolve(C.statement),xo(FT)}function ok(J){K.pid=J.readUInt32BE(5),K.secret=J.readUInt32BE(9)}async function nk(){Jo=!1,(await new Xn([`
9
+ `);o.disposalTraces.add({key:T.key,trace:t})}}var tf=(o,n)=>D(n).atoms.has(o),NR=(o,n)=>D(n).selectors.has(o),hR=(o,n)=>D(n).readonlySelectors.has(o),LM=(o,n)=>tf(o,n)||NR(o,n)||hR(o,n);var Af=(o,n)=>{return D(n).selectorGraph.getRelationEntries({downstreamSelectorKey:o}).filter(([S,{source:f}])=>f!==o).map(([S,{source:f}])=>f).filter((S)=>LM(S,n))};var Gt=(o,n,T)=>{let S=[],f=Af(o,T);while(f.length>0){let t=f.shift();if(n.has(t))continue;if(n.add(t),!tf(t,T))f.push(...Af(t,T));else if(!S.includes(t))S.push(t)}return S},IM=(o,n)=>{let T=o.key,S=Af(T,n),f=new Set;return S.flatMap((t)=>tf(t,n)?t:Gt(t,f,n))};var jM=(o,n,T,S)=>{let f=D(S);if(n.type==="atom"||n.type==="mutable_atom")f.selectorAtoms.set({selectorKey:o,atomKey:n.key}),S.logger.info("\uD83D\uDD0D","selector",o,`discovers root atom "${n.key}"`);else{let t=Gt(n.key,T,S);S.logger.info("\uD83D\uDD0D","selector",o,`discovers root atoms: [ ${t.map((A)=>`"${A}"`).join(", ")} ]`);for(let A of t)f.selectorAtoms=f.selectorAtoms.set({selectorKey:o,atomKey:A})}T.add(n.key)};var Mf=(o,n,T)=>({get:(...S)=>{let f=D(T),t;if(S.length===2){let[F,y]=S;switch(F.type){case"molecule_family":return to(T,F,y);default:if(T.config.lifespan==="ephemeral")t=Mo(T,F,y);else{let $=Go(T,F,y);if($)t=$;else throw new An(F,y,T)}}}else[t]=S;if(t.type==="molecule")return to(T,t);let A=d(t,T),M=sn(A,T);return T.logger.info("\uD83D\uDD0C","selector",o,`registers dependency ( "${t.key}" =`,M,")"),f.selectorGraph.set({upstreamSelectorKey:t.key,downstreamSelectorKey:o},{source:t.key}),jM(o,t,n,T),M},set:(...S)=>{let f,t;if(S.length===2)f=S[0],t=S[1];else{let F=S[0],y=S[1];t=S[2];let $=T.config.lifespan==="ephemeral"?Mo(T,F,y):Go(T,F,y);if(!$)throw new An(F,y,T);f=$}let A=D(T),M=d(f,A);dS(M,t,A)},find:(S,f)=>Mo(T,S,f),seek:(S,f)=>Go(T,S,f),json:(S)=>Bo(T,S)});var AS=(o,n,T)=>{let S=D(o),f=new s,t=new Set,{get:A,find:M,seek:F,json:y}=Mf(n.key,t,S),$=()=>{let Q=n.get({get:A,find:M,seek:F,json:y});return On(n.key,Q,f,D(o)),t.clear(),Q},W={...n,subject:f,install:(Q)=>AS(Q,n,T),get:$,type:"readonly_selector",...T&&{family:T}};S.readonlySelectors.set(n.key,W);let O=$();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 JS=(o,n,T)=>{let S=D(o),f=new s,t=new Set,A=Mf(n.key,t,S),{find:M,get:F,seek:y,json:$}=A,W={find:M,get:F,seek:y,json:$},O=(B=n.get,j=D(o))=>{let b=B(W);return On(n.key,b,f,j),t.clear(),b},Q={...n,subject:f,install:(B)=>JS(B,n,T),get:O,set:(B)=>{let j=D(o),b=O(n.get,j),a=eS(B)(b);if(o.logger.info("\uD83D\uDCDD","selector",n.key,"set (",b,"->",a,")"),On(n.key,a,f,j),VT(j,n.key),Co(j))f.next({newValue:a,oldValue:b});n.set(A,a)},type:"selector",...T&&{family:T}};S.selectors.set(n.key,Q);let H=O();o.logger.info("\u2728",Q.type,Q.key,"=",H);let Y={key:n.key,type:"selector"};if(T)Y.family=T;return Y};function En(o,n){if("set"in n){let f=JS(o,n,void 0);return o.on.selectorCreation.next(f),f}let S=AS(o,n,void 0);return o.on.selectorCreation.next(S),S}function CM(o,n){let T=D(n),{key:S}=o,f=d(o,T);if(!f.family)n.logger.error("\u274C","selector",S,"Standalone selectors cannot be disposed.");else{let t=T.molecules.get(f.family.subKey);if(t)t.tokens.delete(S);switch(o.type){case"selector":T.selectors.delete(S),d({key:f.family.key,type:"selector_family"},n).subject.next({type:"state_disposal",token:o});break;case"readonly_selector":T.readonlySelectors.delete(S),d({key:f.family.key,type:"readonly_selector_family"},n).subject.next({type:"state_disposal",token:o});break}if(T.valueMap.delete(S),T.selectorAtoms.delete(S),T.selectorGraph.delete(S),n.logger.info("\uD83D\uDD25",o.type,S,"deleted"),Ao(T)&&T.transactionMeta.phase==="building")T.transactionMeta.update.updates.push({type:"state_disposal",token:o});else n.on.selectorDisposal.next(o)}}function FS(o,n,T){let S={key:n.key,type:"selector_family"},f=o.families.get(n.key);if(f)o.logger.error("\u2757","selector_family",n.key,`Overwriting an existing ${Hn(f)} "${f.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let t=new s,M=Object.assign((F)=>{let y=l(F),$={key:n.key,subKey:y},W=`${n.key}(${y})`,O=D(o),E=JS(O,{key:W,get:n.get(F),set:n.set(F)},$);return t.next({type:"state_creation",token:E}),E},S,{internalRoles:T,subject:t,install:(F)=>FS(F,n),default:(F)=>{return n.get(F)({get:(...$)=>to(o,...$),find:($,W)=>Mo(o,$,W),seek:($,W)=>Go(o,$,W),json:($)=>Bo(o,$)})}});return o.families.set(n.key,M),S}function NM(o,n,T=So.STORE){let S=FS(T,{key:`${o.key}:JSON`,get:(t)=>({seek:A,get:M})=>{let F=A(o,t);if(F)return n.toJson(M(F));let y=l(t),$=T.molecules.get(y);if($){let O=zn($,o,T);return n.toJson(M(O))}if(T.config.lifespan==="immortal")throw new Error(`No molecule found for key "${y}"`);let W=vn(T,o,t);return n.toJson(M(W))},set:(t)=>({seek:A,set:M},F)=>{let y=A(o,t);if(y)M(y,n.fromJson(F));else{let $=l(t),W=T.molecules.get($);if(W){let O=zn(W,o,T);M(O,n.fromJson(F))}else{if(T.config.lifespan==="immortal")throw new Error(`No molecule found for key "${$}"`);M(vn(T,o,t),n.fromJson(F))}}}},["mutable","json"]);return d(o,T).subject.subscribe(`store=${T.config.name}::json-selector-family`,(t)=>{if(t.token.family)Go(T,S,ho(t.token.family.subKey))}),S}var ho=(o)=>JSON.parse(o),l=(o)=>JSON.stringify(o),y4=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var hM=(o,n)=>{let T=D(n);if(T.operation.open)return T.operation.prev.get(o.key);return T.valueMap.get(o.key)};var zt=(o,n)=>{let T=D(n);return IM(o,n).map((f)=>{let t=T.atoms.get(f);if(t===void 0)throw new Error(`Atom "${f}", a dependency of selector "${o.key}", not found in store "${n.config.name}".`);return t.subject.subscribe(`${o.type}:${o.key}`,(A)=>{n.logger.info("\uD83D\uDCE2",o.type,o.key,"root",f,"went",A.oldValue,"->",A.newValue);let M=hM(o,T),F=sn(o,T);n.logger.info("\u2728",o.type,o.key,"went",M,"->",F),o.subject.next({newValue:F,oldValue:M})})})};function eo(o,n,T,S){function f(W){if(S.operation.open){let O=S.on.operationClose.subscribe(`state subscription ${T}`,()=>{O(),n(W)})}else n(W)}let t=d(o,S);S.logger.info("\uD83D\uDC40",t.type,t.key,`Adding subscription "${T}"`);let A=t.type==="selector"||t.type==="readonly_selector",M=null,F=f;if(A)M=zt(t,S),F=(W)=>{if(M)M.length=0,M.push(...zt(t,S));f(W)};let y=t.subject.subscribe(T,F);return()=>{if(S.logger.info("\uD83D\uDE48",t.type,t.key,`Removing subscription "${T}"`),y(),M)for(let W of M)W()}}var Et=(o,n,T,S)=>{let f=d(o,S);S.logger.info("\uD83D\uDC40","timeline",o.key,`Adding subscription "${T}"`);let t=f.subject.subscribe(T,n);return()=>{S.logger.info("\uD83D\uDE48","timeline",o.key,`Removing subscription "${T}" from timeline`),t()}};var Ht=(o,n,T,S)=>{let f=d(o,S);S.logger.info("\uD83D\uDC40","transaction",o.key,`Adding subscription "${T}"`);let t=f.subject.subscribe(T,n);return()=>{S.logger.info("\uD83D\uDE48","transaction",o.key,`Removing subscription "${T}"`),t()}};class oT{Update;initializeState(o,n){let T=`*${o.key}`;n.atoms.delete(T),n.valueMap.delete(T);let S=o.family?{key:`*${o.family.key}`,subKey:o.family.subKey}:void 0,f=tn(n,{key:T,default:null},S);if(n.parent?.valueMap.has(T)){let t=n.parent.valueMap.get(T);n.valueMap.set(T,t)}return f}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(o,n,T){let S=`tracker:${T.config.name}:${Ao(T)?T.transactionMeta.update.key:"main"}:${o.key}`,f=to(T,o);this.unsubscribeFromInnerValue=f.subscribe(S,(t)=>{Qo(T,n,t)}),this.unsubscribeFromState=eo(o,(t)=>{if(t.newValue!==t.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=t.newValue.subscribe(S,(A)=>{Qo(T,n,A)})},S,T)}updateCore(o,n,T){let S=`tracker:${T.config.name}:${Ao(T)?T.transactionMeta.update.key:"main"}:${o.key}`;eo(n,({newValue:f,oldValue:t})=>{let A=T.timelineTopics.getRelatedKey(n.key);if(A){if(T.timelines.get(A)?.timeTraveling){let y=Et({key:A,type:"timeline"},($)=>{y(),Qo(T,o,(W)=>{if($==="redo"&&f)W.do(f);else if($==="undo"&&t)W.undo(t);return W})},S,T);return}}let M=T.on.operationClose.subscribe(S,()=>{M();let F=to(T,o),y=f===null?-1:F.getUpdateNumber(f),$=y-F.cacheUpdateNumber;if(f&&$===1)Qo(T,o,(W)=>(W.do(f),W));else T.logger.info("\u274C","mutable_atom",o.key,`could not be updated. Expected update number ${F.cacheUpdateNumber+1}, but got ${y}`)})},S,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 WS(o,n,T){o.logger.info("\uD83D\uDD28","atom",n.key,`creating in store "${o.config.name}"`);let S=D(o),f=S.atoms.get(n.key);if(f&&f.type==="mutable_atom")return o.logger.error("\u274C","atom",n.key,"Tried to create atom, but it already exists in the store."),lo(f);let t=new s,A={...n,type:"mutable_atom",install:(y)=>{return y.logger.info("\uD83D\uDEE0\uFE0F","atom",n.key,`installing in store "${y.config.name}"`),WS(y,n,T)},subject:t};if(T)A.family=T;let M=n.default();S.atoms.set(A.key,A),Ff(n.key,o),On(n.key,M,t,S);let F=lo(A);if(n.effects){let y=0,$=[];for(let W of n.effects){let O=W({setSelf:(E)=>{Qo(o,F,E)},onSet:(E)=>eo(F,E,`effect[${y}]`,o)});if(O)$.push(O);++y}A.cleanup=()=>{for(let W of $)W()}}if(new oT(F,o),!T)TM(F,n,o);return F}class mt{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`,(S)=>{if(S.token.family){let f=ho(S.token.family.subKey);Go(n,this.latestUpdateAtoms,f),new oT(S.token,n)}}),this.latestUpdateAtoms.subject.subscribe(`store=${n.config.name}::tracker-atom-family`,(S)=>{if(S.token.family){let f=ho(S.token.family.subKey),t=Go(n,this.mutableAtoms,f);if(t)new oT(t,n)}})}}function tS(o,n,T){let S={key:n.key,type:"mutable_atom_family"},f=o.families.get(n.key);if(f)o.logger.error("\u2757","mutable_atom_family",n.key,`Overwriting an existing ${Hn(f)} "${f.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let t=new s,M=Object.assign((F)=>{let y=l(F),$={key:n.key,subKey:y},W=`${n.key}(${y})`,O=D(o),E={key:W,default:()=>n.default(F),toJson:n.toJson,fromJson:n.fromJson,mutable:!0};if(n.effects)E.effects=n.effects(F);let Q=WS(O,E,$);return t.next({type:"state_creation",token:Q}),Q},S,{subject:t,install:(F)=>tS(F,n),toJson:n.toJson,fromJson:n.fromJson,internalRoles:T});return o.families.set(n.key,M),NM(M,n,o),new mt(M,o),S}var Wt=(o,n)=>{let T=D(n),S=`${o.key}:JSON`;return T.families.get(S)};var Bo=(o,n)=>{if(n.family){let S=D(o),t={key:`${n.family.key}:JSON`,type:"selector_family"},A=d(t,S),M=JSON.parse(n.family.subKey);return Mo(o,A,M)}return{type:"selector",key:`${n.key}:JSON`}};var pn=(o)=>{let T={type:"atom",key:`*${o.key}`};if(o.family)T.family={key:`*${o.family.key}`,subKey:o.family.subKey};return T};function OM(o){return typeof o==="object"&&o!==null&&"do"in o&&"undo"in o&&"subscribe"in o}function kS(o,n,T){let S=n.valueMap.get(o.key),f=T.valueMap.get(o.key);if(S===f){if(S===void 0)return typeof o.default==="function"?o.default():o.default;n.logger.info("\uD83D\uDCC3","atom",o.key,"copying");let t=o.toJson(S),A=o.fromJson(t);return T.valueMap.set(o.key,A),new oT(o,n),A}return f}function On(o,n,T,S){let f=S.valueMap.get(o);if(f instanceof fS)f.use(n);if(n instanceof Promise){let t=new fS(n);return S.valueMap.set(o,t),t.then((A)=>{On(o,A,T,S),T.next({newValue:A,oldValue:t})}).catch((A)=>{S.logger.error("\uD83D\uDCA5","state",o,"rejected:",A)}),t}return S.valueMap.set(o,n),n}var FM=(o,n)=>{let T=n.valueMap.get(o.key);if(o.type==="mutable_atom"&&Ao(n)){let{parent:S}=n;T=kS(o,S,n)}return T},JM=(o,n)=>{let T=n.valueMap.get(o);if(T instanceof fS){let S=T,f=n.selectors.get(o)??n.readonlySelectors.get(o);if(f)S.use(f.get());return}if(n.operation.open)n.operation.prev.set(o,T);n.valueMap.delete(o),n.logger.info("\uD83D\uDDD1","state",o,"evicted")};var wM=(o,n)=>{return D(n).atomsThatAreDefault.has(o)},Ff=(o,n)=>{let T=D(n);T.atomsThatAreDefault=new Set(T.atomsThatAreDefault).add(o)},KM=(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 S=D(o),f=S.atoms.get(n.key);if(f&&f.type==="atom")return o.logger.error("\u274C","atom",n.key,"Tried to create atom, but it already exists in the store."),lo(f);let t=new s,A={...n,type:"atom",install:(y)=>{return y.logger.info("\uD83D\uDEE0\uFE0F","atom",n.key,`installing in store "${y.config.name}"`),tn(y,n,T)},subject:t};if(T)A.family=T;let M=n.default;if(n.default instanceof Function)M=n.default();S.atoms.set(A.key,A),Ff(n.key,o),On(n.key,M,t,S);let F=lo(A);if(n.effects){let y=0,$=[];for(let W of n.effects){let O=W({setSelf:(E)=>{Qo(o,F,E)},onSet:(E)=>eo(F,E,`effect[${y}]`,o)});if(O)$.push(O);++y}A.cleanup=()=>{for(let W of $)W()}}return F}function tM(o,n){if("mutable"in n){let f=WS(o,n,void 0);return o.on.atomCreation.next(f),f}let S=tn(o,n,void 0);return o.on.atomCreation.next(S),S}function Yt(o,n){let T=D(n),{key:S}=o,f=d(o,T);if(!f.family)n.logger.error("\u274C","atom",S,"Standalone atoms cannot be disposed.");else{f.cleanup?.();let t=n.valueMap.get(f.key);d({key:f.family.key,type:"atom_family"},n).subject.next({type:"state_disposal",token:o,value:t});let M=T.molecules.get(f.family.subKey);if(M)M.tokens.delete(S);if(T.atoms.delete(S),T.valueMap.delete(S),T.selectorAtoms.delete(S),T.atomsThatAreDefault.delete(S),n.timelineTopics.delete(S),o.type==="mutable_atom"){let F=pn(o);Yt(F,n),n.trackers.delete(S)}if(n.logger.info("\uD83D\uDD25","atom",S,"deleted"),Ao(T)&&T.transactionMeta.phase==="building")T.transactionMeta.update.updates.push({type:"state_disposal",token:o});else n.on.atomDisposal.next(o)}}var Qt=(o)=>{let n=tn(o,{key:"\uD83D\uDD0D Atom Token Index (Internal)",default:()=>{let T=new Map;for(let[S,f]of o.atoms)if(!S.includes("\uD83D\uDD0D")){let t=lo(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,t)}else T.set(S,t)}return T},effects:[({setSelf:T})=>{o.on.atomCreation.subscribe("introspection",(S)=>{if(S.key.includes("\uD83D\uDD0D"))return;T((f)=>{if(S.family){let{key:t,subKey:A}=S.family,M=f.get(t);if(M===void 0||!("familyMembers"in M))M={key:t,familyMembers:new Map},f.set(t,M);M.familyMembers.set(A,S)}else f.set(S.key,S);return f})}),o.on.atomDisposal.subscribe("introspection",(S)=>{T((f)=>{if(S.family){let{key:t,subKey:A}=S.family,M=f.get(t);if(M&&"familyMembers"in M){if(M.familyMembers.delete(A),M.familyMembers.size===0)f.delete(t)}}else f.delete(S.key);return f})})}]},void 0);return En(o,{key:"\uD83D\uDD0D Atom Token Index",get:({get:T})=>T(n)})};var Dt=(o)=>{let n=tn(o,{key:"\uD83D\uDD0D Selector Token Index (Internal)",default:()=>{let T=new Map;for(let S of[o.readonlySelectors,o.selectors])for(let[f,t]of S)if(!f.includes("\uD83D\uDD0D")){let A=lo(t);if(t.family){let M=T.get(t.family.key);if(!M||!("familyMembers"in M))M={key:t.family.key,familyMembers:new Map},T.set(t.family.key,M);M.familyMembers.set(t.family.subKey,A)}else T.set(f,A)}return T},effects:[({setSelf:T})=>{o.on.selectorCreation.subscribe("introspection",(S)=>{if(S.key.includes("\uD83D\uDD0D"))return;T((f)=>{if(S.family){let{key:t,subKey:A}=S.family,M=f.get(t);if(M===void 0||!("familyMembers"in M))M={key:t,familyMembers:new Map},f.set(t,M);M.familyMembers.set(A,S)}else f.set(S.key,S);return f})}),o.on.selectorDisposal.subscribe("introspection",(S)=>{T((f)=>{if(S.family){let{key:t,subKey:A}=S.family,M=f.get(t);if(M&&"familyMembers"in M){if(M.familyMembers.delete(A),M.familyMembers.size===0)f.delete(t)}}else f.delete(S.key);return f})})}]},void 0);return En(o,{key:"\uD83D\uDD0D Selector Token Index",get:({get:T})=>T(n)})};class yf{supported;constructor(o){this.supported=o}refine(o){for(let[n,T]of Object.entries(this.supported))try{if(T(o)===!0&&T!==Boolean)return{type:n,data:o}}catch(S){try{if(o instanceof T)return{type:n,data:o}}catch(f){}}return null}}var Ut=new yf({number:(o)=>typeof o==="number",string:(o)=>typeof o==="string",boolean:(o)=>typeof o==="boolean",null:(o)=>o===null});function Vt(o){if(!o)return!1;return Object.getPrototypeOf(o)===Object.prototype}var Bt=new yf({object:Vt,array:(o)=>Array.isArray(o)}),bR=new yf({...Ut.supported,...Bt.supported}),BT=(o)=>{if(o===void 0)return"undefined";let n=bR.refine(o);if(n)return n.type;return Object.getPrototypeOf(o).constructor.name};class bM{store;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(o=So.STORE){this.store=o;this.atomIndex=Qt(this.store),this.selectorIndex=Dt(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=bM.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");let n=Ft(this.atomIndex),T=Ft(this.selectorIndex),S=[...n.values()].filter((M)=>("familyMembers"in M)),f=[...T.values()].filter((M)=>("familyMembers"in M)),t=performance.now(),A=[];if(o.atomFamilies)for(let M of S){let F=M.familyMembers.values();for(let y of F){let W=this.statesCreatedAt.get(y.key)??this.auditorCreatedAt,O=t-W;A.push([y,O])}}if(o.selectorFamilies)for(let M of f){let F=M.familyMembers.values();for(let y of F){let W=this.statesCreatedAt.get(y.key)??this.auditorCreatedAt,O=t-W;A.push([y,O])}}return A}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}}var Ct=(o,n)=>{let T=(S,f)=>{let A=((F,y)=>{let $=n(F,y);if($)return $;return null})(S,f);if(A?.jobComplete??A?.pathComplete)return A;let M=Array.isArray(f)?f.map((F,y)=>[y,F]):Vt(f)?Object.entries(f):[];for(let[F,y]of M){let $=T([...S,F],y);if($?.jobComplete)return $}return{}};T([],o)};function rR(o,n){return{summary:`${o<n?"+":"-"}${Math.abs(o-n)} (${o} \u2192 ${n})`}}function xR(o,n){return{summary:`${o.length<n.length?"+":"-"}${Math.abs(o.length-n.length)} ("${o}" \u2192 "${n}")`}}function cR(o,n){return{summary:`${o} \u2192 ${n}`}}function rM(o,n,T){let S="",f=[],t=[],A=[];return Ct(o,(M,F)=>{let y;for(y of M){let $=n[y];if($===void 0)t.push([y,JSON.stringify(F)]);else{let W=T(F,$);if(W.summary!=="No Change")A.push([y,W])}}}),Ct(n,(M,F)=>{let y;for(y of M)if(o[y]===void 0)f.push([y,JSON.stringify(F)])}),S=`\uFF5E${A.length} \uFF0B${f.length} \uFF0D${t.length}`,{summary:S,added:f,removed:t,changed:A}}function vR(o,n,T){return rM(o,n,T)}class xM{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(o,n,T){this.leafRefinery=o,this.treeRefinery=n,this.leafDiffers={},this.treeDiffers={};for(let S of Object.keys(o.supported)){let f=T[S];this.leafDiffers[S]=f}for(let S of Object.keys(n.supported)){let f=T[S];this.treeDiffers[S]=f}}diff(o,n){if(o===n)return{summary:"No Change"};let T=this.leafRefinery.refine(o)??this.treeRefinery.refine(o),S=this.leafRefinery.refine(n)??this.treeRefinery.refine(n);if(T!==null&&S!==null){if(T.type===S.type){if(T.type in this.leafDiffers)return this.leafDiffers[T.type](T.data,S.data);if(T.type in this.treeDiffers)return this.treeDiffers[T.type](T.data,S.data,(M,F)=>this.diff(M,F))}}let f=BT(o),t=BT(n);if(f===t)return{summary:`${f} \u2192 ${t}`};return{summary:`Type change: ${f} \u2192 ${t}`}}}var Y8=new xM(Ut,Bt,{number:rR,string:xR,boolean:cR,null:()=>({summary:"No Change"}),object:rM,array:vR});class cM 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 $f{key;type="continuity";globals=[];actions=[];perspectives=[];constructor(o){this.key=o}static existing=new cM;static create(o,n){let T=new $f(o),{type:S,globals:f,actions:t,perspectives:A}=n(T),M={type:S,key:o,globals:f,actions:t,perspectives:A};return $f.existing.set(o,M),M}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,S]=o;this.perspectives.push({type:"realtime_perspective",resourceAtoms:T,viewAtoms:S})}break}return this}}function V8(o){let{key:n,config:T}=o,S=$f.create(n,T),{actions:f}=S;for(let t of f)DM(n,t.key,So.STORE);return zM(n,-1,So.STORE),S}var j8=UT({key:"usersInRoomIndex",mutable:!0,default:()=>new bo,toJson:(o)=>o.toJSON(),fromJson:(o)=>bo.fromJSON(o)}),Lt=UT({key:"roomIndex",default:()=>new bo,mutable:!0,toJson:(o)=>o.toJSON(),fromJson:(o)=>bo.fromJSON(o)}),qR={enteredAtEpoch:0},OS=sS({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(o)=>typeof o==="string",isBType:(o)=>typeof o==="string"},qR),N8=lS({key:"usersInMyRoomView",get:(o)=>({find:n})=>{let T=GM(OS);return[n(T,o)]}});import{spawn as iR}from"child_process";class CT{emit;listeners;globalListeners;handleEvent(o,...n){for(let S of this.globalListeners)S(o,...n);let T=this.listeners.get(o);if(T)for(let S of T)S(...n)}id="no_id_retrieved";constructor(o){this.emit=o;this.listeners=new Map,this.globalListeners=new Set}on(o,n){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 It extends CT{incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";process;key;logger;handleLog(o){if(Array.isArray(o)){let[n,...T]=o;switch(n){case"i":this.logger.info(...T);break;case"w":this.logger.warn(...T);break;case"e":this.logger.error(...T);break}}}constructor(o,n,T){super((S,...f)=>{let t=JSON.stringify([S,...f])+"\x03",A=(M)=>{if(M.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",A)};return this.process.stdin.once("error",A),this.process.stdin.write(t),this});if(this.process=o,this.key=n,this.logger=T??{info:(...S)=>{console.info(this.id,this.key,...S)},warn:(...S)=>{console.warn(this.id,this.key,...S)},error:(...S)=>{console.error(this.id,this.key,...S)}},this.process.stdout.on("data",(S)=>{let f=S.toString();if(f==="ALIVE")return;this.unprocessedEvents.push(...f.split("\x03"));let t=this.unprocessedEvents.shift();this.incompleteData+=t??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let A=ho(this.incompleteData);this.handleEvent(...A);while(this.unprocessedEvents.length>0){let M=this.unprocessedEvents.shift();if(M){if(this.unprocessedEvents.length===0)this.incompleteData=M;A=ho(M),this.handleEvent(...A)}}this.incompleteData=""}catch(A){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error(A)}}),this.process.stderr.on("data",(S)=>{let f=S.toString();this.unprocessedLogs.push(...f.split("\x03"));let t=this.unprocessedLogs.shift();this.incompleteLog+=t??"";try{let A=ho(this.incompleteLog);this.handleLog(A);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)A=ho(this.incompleteLog),this.handleLog(A)}catch(A){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error(A),console.error("\u274C\u274C\u274C\uFE0F")}}),o.pid)this.id=o.pid.toString()}}class vM extends CT{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 jt extends CT{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...o){this.process.stderr.write(l(o.map((n)=>n instanceof bo?`{ ${n.toJSON().members.join(" | ")} }`:n))+"\x03")}logger={info:(...o)=>{this.log("i",...o)},warn:(...o)=>{this.log("w",...o)},error:(...o)=>{this.log("e",...o)}};constructor(){super((o,...n)=>{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 S=ho(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",S),this.handleEvent(...S);while(this.unprocessedEvents.length>0){let f=this.unprocessedEvents.shift();if(f){if(this.unprocessedEvents.length===0)this.incompleteData=f;let t=ho(f);this.handleEvent(...t)}}this.incompleteData=""}catch(S){if(S instanceof Error)this.logger.error("\u2757",S.message,S.cause,S.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(o)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${o}`)}),process.on("end",()=>{this.logger.info("\uD83D\uDD25",this.id,"ended"),process.exit(0)}),process.on("SIGTERM",()=>{this.logger.error("\uD83D\uDD25",this.id,"terminated"),process.exit(0)}),process.on("SIGINT",()=>{this.logger.error("\uD83D\uDD25",this.id,"interrupted"),process.exit(0)}),process.pid)this.id=process.pid?.toString();this.on("user-joins",(o)=>{this.logger.info("\uD83D\uDC64","user",o,"joined");let n=new vM(`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 S=T(n);if(S)n.disposalFunctions.push(S)}this.on(`user:${o}`,(...T)=>{n.in.next(T)}),n.out.subscribe("socket",(T)=>{this.emit(...T)})}),this.on("user-leaves",(o)=>{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 Nt=$T({key:"roomArguments",default:["echo",["Hello World!"]]}),qM=lS({key:"room",get:(o)=>async({get:n,find:T})=>{let S=T(Nt,o),f=n(S),[t,A]=f,M=await new Promise((F)=>{let y=iR(t,A,{env:process.env}),$=(W)=>{if(W.toString()==="ALIVE")y.stdout.off("data",$),F(y)};y.stdout.on("data",$)});return new It(M,o)}});var y5=$S({key:"createRoom",do:({get:o,set:n,find:T},S,f,t)=>{let A=t?[f,t]:[f],M=T(Nt,S);n(M,A),n(Lt,($)=>$.add(S));let F=T(qM,S);return o(F)}}),$5=$S({key:"joinRoom",do:(o,n,T,S)=>{let f={enteredAtEpoch:S};return nf(OS,(t)=>{t.set({room:n,user:T},f)},o.env().store),f}}),k5=$S({key:"leaveRoom",do:(o,n,T)=>{nf(OS,(S)=>{S.delete({room:n,user:T})},o.env().store)}}),R5=$S({key:"destroyRoom",do:(o,n)=>{nf(OS,(T)=>{T.delete({room:n})},o.env().store),o.set(Lt,(T)=>(T.delete(n),T))}});function ht(o,n){return n.map((T)=>{switch(T.type){case"transaction_update":{let S=ht(o,T.updates);return{...T,updates:S}}default:return T}}).filter((T)=>{switch(T.type){case"atom_update":case"selector_update":return o.includes(T.key);case"state_creation":return o.includes(T.token.key);case"molecule_creation":return!0;case"transaction_update":return!0}})}var O5=$T({key:"redactor",default:{occlude:(o)=>o}}),LT=$T({key:"unacknowledgedUpdates",default:()=>[]});var iM=$T({key:"sockets",default:null}),Y5=UT({key:"socketsIndex",mutable:!0,default:()=>new bo,toJson:(o)=>o.toJSON(),fromJson:(o)=>bo.fromJSON(o)}),G5=UT({key:"usersIndex",mutable:!0,default:()=>new bo,toJson:(o)=>o.toJSON(),fromJson:(o)=>bo.fromJSON(o)}),bt=sS({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(o)=>o.startsWith("user::"),isBType:(o)=>o.startsWith("socket::")});function pM(o,n,T,S){let f=n.key;return function t(){let A=[];for(let F of n.globals){let y=F.type==="mutable_atom"?Bo(o,F):F,$=to(o,y);A.push(y,$)}for(let F of n.perspectives){let{viewAtoms:y,resourceAtoms:$}=F,W=Mo(o,y,T),O=to(o,W);o.logger.info("\uD83D\uDC41","atom",$.key,`${T} can see`,{viewAtoms:y,resourceAtoms:$,userView:O});for(let E of O){let Q=E.type==="mutable_atom"?Bo(o,E):E,H=to(o,Q);A.push(Q,H)}}let M=Co(o)?o.transactionMeta.epoch.get(f)??null:null;S?.emit(`continuity-init:${f}`,M,A)}}function ZM(o,n,T){let S=n.key;return function f(t){o.logger.info("\uD83D\uDECE\uFE0F","continuity",S,"received",t);let{key:A,id:M}=t,F=`tx-run:${A}:${M}`,y=`${F}:start`,$=`${F}:end`;performance.mark(y);try{an({type:"transaction",key:A},M,o)(...t.params)}catch(O){if(O instanceof Error)o.logger.error("\u274C","continuity",S,`failed to run transaction ${A} from ${T} with update ${M}`,O.message)}performance.mark($);let W=performance.measure(F,y,$);o?.logger.info("\uD83D\uDE80","transaction",A,M,T,W.duration)}}function PM(o,n,T,S){let f=n.key;return function t(A){if(o.logger.info("\uD83D\uDC4D","continuity",f,`${T} acknowledged epoch ${A}`),S[0]?.epoch===A)Qo(o,LT,T,(F)=>{return F.shift(),o.logger.info("\uD83D\uDC4D","continuity",f,`${T} unacknowledged update queue now has`,F.length,"items"),F})}}function gM(o,n,T,S){let f=n.key,t=[];for(let A of n.actions){let M=Ht(A,(F)=>{try{let y=n.globals.map((O)=>{if(O.type==="atom")return O.key;return pn(O).key}).concat(n.perspectives.flatMap((O)=>{let{viewAtoms:E}=O,Q=Mo(o,E,T);return to(o,Q).map((Y)=>{return Y.type==="mutable_atom"?"*"+Y.key:Y.key})})),$=ht(y,F.updates),W={...F,updates:$};Qo(o,LT,T,(O)=>{if(W)O.push(W),O.sort((E,Q)=>E.epoch-Q.epoch),o.logger.info("\uD83D\uDC4D","continuity",f,`${T} unacknowledged update queue now has`,O.length,"items");return O}),S?.emit(`tx-new:${f}`,W)}catch(y){if(y instanceof Error)o.logger.error("\u274C","continuity",f,`${T} failed to send update from transaction ${A.key} to ${T}`,y.message)}},`sync-continuity:${f}:${T}`,o);t.push(M)}return t}function lM(o,n,T,S){let f=n.key,t=[];for(let A of n.perspectives){let{viewAtoms:M}=A,F=Mo(o,M,T),y=eo(F,({oldValue:$,newValue:W})=>{let O=$.map((Y)=>Y.key),E=W.map((Y)=>Y.key),Q=$.filter((Y)=>!E.includes(Y.key)),H=W.filter((Y)=>!O.includes(Y.key)).flatMap((Y)=>{let B=Y.type==="mutable_atom"?Bo(o,Y):Y,j=to(o,B);return[B,j]});if(o.logger.info("\uD83D\uDC41","atom",A.resourceAtoms.key,`${T} has a new perspective`,{oldKeys:O,newKeys:E,revealed:H,concealed:Q}),H.length>0)S?.emit(`reveal:${f}`,H);if(Q.length>0)S?.emit(`conceal:${f}`,Q)},`sync-continuity:${f}:${T}:perspective:${A.resourceAtoms.key}`,o);t.push(y)}return t}function u5({socket:o,store:n=So.STORE}){return function T(S){let f=o,t=S.key,A=of(bt,`socket::${f.id}`,n).userKeyOfSocket,M=to(n,A);if(!M)return n.logger.error("\u274C","continuity",t,`Tried to create a synchronizer for a socket (${f.id}) that is not connected to a user.`),()=>{};let F=of(bt,M,n).socketKeyOfUser,y=eo(F,({newValue:B})=>{if(n.logger.info("\uD83D\uDC4B","continuity",t,`seeing ${M} on new socket ${B}`),B===null){n.logger.warn("\u274C","continuity",t,`User (${M}) is not connected to a socket, waiting for them to reappear.`);return}let j=Mo(n,iM,B);f=to(n,j);for(let a of $)f?.emit(`tx-new:${t}`,a)},`sync-continuity:${t}:${M}`,n),$=to(n,LT,M),W=[],O=lM(n,S,M,f),E=gM(n,S,M,f);W.push(...O,...E);let Q=pM(n,S,M,o);f.off(`get:${t}`,Q),f.on(`get:${t}`,Q);let H=ZM(n,S,M);f.off(`tx-run:${t}`,H),f.on(`tx-run:${t}`,H);let Y=PM(n,S,M,$);return f?.on(`ack:${t}`,Y),()=>{for(let B of W)B();f?.off(`ack:${t}`,Y),f?.off(`get:${t}`,Q),f?.off(`tx-run:${t}`,H)}}}var{file:Bk,serve:AW}=globalThis.Bun;import{readFileSync as FF}from"fs";import{resolve as it}from"path";function pR(o,n){let T={},S=[];for(let f in o){let t=o[f],A=n[f],M=t["~standard"].validate(A);if(M instanceof Promise)throw new Error(`Validation must be synchronous, but ${f} returned a Promise.`);if(M.issues){S.push(...M.issues.map((F)=>({...F,path:[f,...F.path??[]]})));continue}T[f]=M.value}if(S.length)return{issues:S};return{value:T}}function eM(o){let n=o.runtimeEnvStrict??o.runtimeEnv??process.env;if(o.emptyStringAsUndefined??!1){for(let[j,b]of Object.entries(n))if(b==="")delete n[j]}if(!!o.skipValidation)return n;let f=typeof o.client==="object"?o.client:{},t=typeof o.server==="object"?o.server:{},A=typeof o.shared==="object"?o.shared:{},M=o.isServer??(typeof window==="undefined"||("Deno"in window)),F=M?{...t,...A,...f}:{...f,...A},y=pR(F,n),$=o.onValidationError??((j)=>{throw console.error("\u274C Invalid environment variables:",j),new Error("Invalid environment variables")}),W=o.onInvalidAccess??(()=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(y.issues)return $(y.issues);let O=(j)=>{if(!o.clientPrefix)return!0;return!j.startsWith(o.clientPrefix)&&!(j in A)},E=(j)=>{return M||!O(j)},Q=(j)=>{return j==="__esModule"||j==="$$typeof"},H=(o.extends??[]).reduce((j,b)=>{return Object.assign(j,b)},{}),Y=Object.assign(y.value,H);return new Proxy(Y,{get(j,b){if(typeof b!=="string")return;if(Q(b))return;if(!E(b))return W(b);return Reflect.get(j,b)}})}var Fo;(function(o){o.assertEqual=(f)=>f;function n(f){}o.assertIs=n;function T(f){throw new Error}o.assertNever=T,o.arrayToEnum=(f)=>{let t={};for(let A of f)t[A]=A;return t},o.getValidEnumValues=(f)=>{let t=o.objectKeys(f).filter((M)=>typeof f[f[M]]!=="number"),A={};for(let M of t)A[M]=f[M];return o.objectValues(A)},o.objectValues=(f)=>{return o.objectKeys(f).map(function(t){return f[t]})},o.objectKeys=typeof Object.keys==="function"?(f)=>Object.keys(f):(f)=>{let t=[];for(let A in f)if(Object.prototype.hasOwnProperty.call(f,A))t.push(A);return t},o.find=(f,t)=>{for(let A of f)if(t(A))return A;return},o.isInteger=typeof Number.isInteger==="function"?(f)=>Number.isInteger(f):(f)=>typeof f==="number"&&isFinite(f)&&Math.floor(f)===f;function S(f,t=" | "){return f.map((A)=>typeof A==="string"?`'${A}'`:A).join(t)}o.joinValues=S,o.jsonStringifyReplacer=(f,t)=>{if(typeof t==="bigint")return t.toString();return t}})(Fo||(Fo={}));var xt;(function(o){o.mergeShapes=(n,T)=>{return{...n,...T}}})(xt||(xt={}));var h=Fo.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Pn=(o)=>{switch(typeof o){case"undefined":return h.undefined;case"string":return h.string;case"number":return isNaN(o)?h.nan:h.number;case"boolean":return h.boolean;case"function":return h.function;case"bigint":return h.bigint;case"symbol":return h.symbol;case"object":if(Array.isArray(o))return h.array;if(o===null)return h.null;if(o.then&&typeof o.then==="function"&&o.catch&&typeof o.catch==="function")return h.promise;if(typeof Map!=="undefined"&&o instanceof Map)return h.map;if(typeof Set!=="undefined"&&o instanceof Set)return h.set;if(typeof Date!=="undefined"&&o instanceof Date)return h.date;return h.object;default:return h.unknown}},m=Fo.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"]),ZR=(o)=>{return JSON.stringify(o,null,2).replace(/"([^"]+)":/g,"$1:")};class kn extends Error{get errors(){return this.issues}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}format(o){let n=o||function(f){return f.message},T={_errors:[]},S=(f)=>{for(let t of f.issues)if(t.code==="invalid_union")t.unionErrors.map(S);else if(t.code==="invalid_return_type")S(t.returnTypeError);else if(t.code==="invalid_arguments")S(t.argumentsError);else if(t.path.length===0)T._errors.push(n(t));else{let A=T,M=0;while(M<t.path.length){let F=t.path[M];if(M!==t.path.length-1)A[F]=A[F]||{_errors:[]};else A[F]=A[F]||{_errors:[]},A[F]._errors.push(n(t));A=A[F],M++}}};return S(this),T}static assert(o){if(!(o instanceof kn))throw new Error(`Not a ZodError: ${o}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Fo.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(o=(n)=>n.message){let n={},T=[];for(let S of this.issues)if(S.path.length>0)n[S.path[0]]=n[S.path[0]]||[],n[S.path[0]].push(o(S));else T.push(o(S));return{formErrors:T,fieldErrors:n}}get formErrors(){return this.flatten()}}kn.create=(o)=>{return new kn(o)};var hT=(o,n)=>{let T;switch(o.code){case m.invalid_type:if(o.received===h.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,Fo.jsonStringifyReplacer)}`;break;case m.unrecognized_keys:T=`Unrecognized key(s) in object: ${Fo.joinValues(o.keys,", ")}`;break;case m.invalid_union:T="Invalid input";break;case m.invalid_union_discriminator:T=`Invalid discriminator value. Expected ${Fo.joinValues(o.options)}`;break;case m.invalid_enum_value:T=`Invalid enum value. Expected ${Fo.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 Fo.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,Fo.assertNever(o)}return{message:T}},aM=hT;function PR(o){aM=o}function kf(){return aM}var Rf=(o)=>{let{data:n,path:T,errorMaps:S,issueData:f}=o,t=[...T,...f.path||[]],A={...f,path:t};if(f.message!==void 0)return{...f,path:t,message:f.message};let M="",F=S.filter((y)=>!!y).slice().reverse();for(let y of F)M=y(A,{data:n,defaultError:M}).message;return{...f,path:t,message:M}},gR=[];function L(o,n){let T=kf(),S=Rf({issueData:n,data:o.data,path:o.path,errorMaps:[o.common.contextualErrorMap,o.schemaErrorMap,T,T===hT?void 0:hT].filter((f)=>!!f)});o.common.issues.push(S)}class uo{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 S of n){if(S.status==="aborted")return u;if(S.status==="dirty")o.dirty();T.push(S.value)}return{status:o.value,value:T}}static async mergeObjectAsync(o,n){let T=[];for(let S of n){let f=await S.key,t=await S.value;T.push({key:f,value:t})}return uo.mergeObjectSync(o,T)}static mergeObjectSync(o,n){let T={};for(let S of n){let{key:f,value:t}=S;if(f.status==="aborted")return u;if(t.status==="aborted")return u;if(f.status==="dirty")o.dirty();if(t.status==="dirty")o.dirty();if(f.value!=="__proto__"&&(typeof t.value!=="undefined"||S.alwaysSet))T[f.value]=t.value}return{status:o.value,value:T}}}var u=Object.freeze({status:"aborted"}),jT=(o)=>({status:"dirty",value:o}),nn=(o)=>({status:"valid",value:o}),ct=(o)=>o.status==="aborted",vt=(o)=>o.status==="dirty",kT=(o)=>o.status==="valid",KS=(o)=>typeof Promise!=="undefined"&&o instanceof Promise;function Jf(o,n,T,S){if(T==="a"&&!S)throw new TypeError("Private accessor was defined without a getter");if(typeof n==="function"?o!==n||!S:!n.has(o))throw new TypeError("Cannot read private member from an object whose class did not declare it");return T==="m"?S:T==="a"?S.call(o):S?S.value:n.get(o)}function sM(o,n,T,S,f){if(S==="m")throw new TypeError("Private method is not writable");if(S==="a"&&!f)throw new TypeError("Private accessor was defined without a setter");if(typeof n==="function"?o!==n||!f:!n.has(o))throw new TypeError("Cannot write private member to an object whose class did not declare it");return S==="a"?f.call(o,T):f?f.value=T:n.set(o,T),T}var i;(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})(i||(i={}));var _S,wS;class Un{constructor(o,n,T,S){this._cachedPath=[],this.parent=o,this.data=n,this._path=T,this._key=S}get path(){if(!this._cachedPath.length)if(this._key instanceof Array)this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var dM=(o,n)=>{if(kT(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 kn(o.common.issues);return this._error=T,this._error}}}};function oo(o){if(!o)return{};let{errorMap:n,invalid_type_error:T,required_error:S,description:f}=o;if(n&&(T||S))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(n)return{errorMap:n,description:f};return{errorMap:(A,M)=>{var F,y;let{message:$}=o;if(A.code==="invalid_enum_value")return{message:$!==null&&$!==void 0?$:M.defaultError};if(typeof M.data==="undefined")return{message:(F=$!==null&&$!==void 0?$:S)!==null&&F!==void 0?F:M.defaultError};if(A.code!=="invalid_type")return{message:M.defaultError};return{message:(y=$!==null&&$!==void 0?$:T)!==null&&y!==void 0?y:M.defaultError}},description:f}}class no{get description(){return this._def.description}_getType(o){return Pn(o.data)}_getOrReturnCtx(o,n){return n||{common:o.parent.common,data:o.data,parsedType:Pn(o.data),schemaErrorMap:this._def.errorMap,path:o.path,parent:o.parent}}_processInputParams(o){return{status:new uo,ctx:{common:o.parent.common,data:o.data,parsedType:Pn(o.data),schemaErrorMap:this._def.errorMap,path:o.path,parent:o.parent}}}_parseSync(o){let n=this._parse(o);if(KS(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 S={common:{issues:[],async:(T=n===null||n===void 0?void 0:n.async)!==null&&T!==void 0?T:!1,contextualErrorMap:n===null||n===void 0?void 0:n.errorMap},path:(n===null||n===void 0?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:o,parsedType:Pn(o)},f=this._parseSync({data:o,path:S.path,parent:S});return dM(S,f)}"~validate"(o){var n,T;let S={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:o,parsedType:Pn(o)};if(!this["~standard"].async)try{let f=this._parseSync({data:o,path:[],parent:S});return kT(f)?{value:f.value}:{issues:S.common.issues}}catch(f){if((T=(n=f===null||f===void 0?void 0:f.message)===null||n===void 0?void 0:n.toLowerCase())===null||T===void 0?void 0:T.includes("encountered"))this["~standard"].async=!0;S.common={issues:[],async:!0}}return this._parseAsync({data:o,path:[],parent:S}).then((f)=>kT(f)?{value:f.value}:{issues:S.common.issues})}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:Pn(o)},S=this._parse({data:o,path:T.path,parent:T}),f=await(KS(S)?S:Promise.resolve(S));return dM(T,f)}refine(o,n){let T=(S)=>{if(typeof n==="string"||typeof n==="undefined")return{message:n};else if(typeof n==="function")return n(S);else return n};return this._refinement((S,f)=>{let t=o(S),A=()=>f.addIssue({code:m.custom,...T(S)});if(typeof Promise!=="undefined"&&t instanceof Promise)return t.then((M)=>{if(!M)return A(),!1;else return!0});if(!t)return A(),!1;else return!0})}refinement(o,n){return this._refinement((T,S)=>{if(!o(T))return S.addIssue(typeof n==="function"?n(T,S):n),!1;else return!0})}_refinement(o){return new wn({schema:this,typeName:e.ZodEffects,effect:{type:"refinement",refinement:o}})}superRefine(o){return this._refinement(o)}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),this["~standard"]={version:1,vendor:"zod",validate:(n)=>this["~validate"](n)}}optional(){return Dn.create(this,this._def)}nullable(){return gn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Qn.create(this)}promise(){return OT.create(this,this._def)}or(o){return cT.create([this,o],this._def)}and(o){return vT.create(this,o,this._def)}transform(o){return new wn({...oo(this._def),schema:this,typeName:e.ZodEffects,effect:{type:"transform",transform:o}})}default(o){let n=typeof o==="function"?o:()=>o;return new ZT({...oo(this._def),innerType:this,defaultValue:n,typeName:e.ZodDefault})}brand(){return new Of({typeName:e.ZodBranded,type:this,...oo(this._def)})}catch(o){let n=typeof o==="function"?o:()=>o;return new PT({...oo(this._def),innerType:this,catchValue:n,typeName:e.ZodCatch})}describe(o){return new this.constructor({...this._def,description:o})}pipe(o){return zS.create(this,o)}readonly(){return gT.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var lR=/^c[^\s-]{8,}$/i,eR=/^[0-9a-z]+$/,dR=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uR=/^[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,aR=/^[a-z0-9_-]{21}$/i,sR=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,oJ=/^[-+]?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)?)??$/,nJ=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,TJ="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",rt,SJ=/^(?:(?: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])$/,fJ=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,tJ=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,AJ=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,MJ=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,FJ=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,oF="((\\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])))",yJ=new RegExp(`^${oF}$`);function nF(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 $J(o){return new RegExp(`^${nF(o)}$`)}function TF(o){let n=`${oF}T${nF(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 kJ(o,n){if((n==="v4"||!n)&&SJ.test(o))return!0;if((n==="v6"||!n)&&tJ.test(o))return!0;return!1}function RJ(o,n){if(!sR.test(o))return!1;try{let[T]=o.split("."),S=T.replace(/-/g,"+").replace(/_/g,"/").padEnd(T.length+(4-T.length%4)%4,"="),f=JSON.parse(atob(S));if(typeof f!=="object"||f===null)return!1;if(!f.typ||!f.alg)return!1;if(n&&f.alg!==n)return!1;return!0}catch(T){return!1}}function JJ(o,n){if((n==="v4"||!n)&&fJ.test(o))return!0;if((n==="v6"||!n)&&AJ.test(o))return!0;return!1}class mn extends no{_parse(o){if(this._def.coerce)o.data=String(o.data);if(this._getType(o)!==h.string){let f=this._getOrReturnCtx(o);return L(f,{code:m.invalid_type,expected:h.string,received:f.parsedType}),u}let T=new uo,S=void 0;for(let f of this._def.checks)if(f.kind==="min"){if(o.data.length<f.value)S=this._getOrReturnCtx(o,S),L(S,{code:m.too_small,minimum:f.value,type:"string",inclusive:!0,exact:!1,message:f.message}),T.dirty()}else if(f.kind==="max"){if(o.data.length>f.value)S=this._getOrReturnCtx(o,S),L(S,{code:m.too_big,maximum:f.value,type:"string",inclusive:!0,exact:!1,message:f.message}),T.dirty()}else if(f.kind==="length"){let t=o.data.length>f.value,A=o.data.length<f.value;if(t||A){if(S=this._getOrReturnCtx(o,S),t)L(S,{code:m.too_big,maximum:f.value,type:"string",inclusive:!0,exact:!0,message:f.message});else if(A)L(S,{code:m.too_small,minimum:f.value,type:"string",inclusive:!0,exact:!0,message:f.message});T.dirty()}}else if(f.kind==="email"){if(!nJ.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"email",code:m.invalid_string,message:f.message}),T.dirty()}else if(f.kind==="emoji"){if(!rt)rt=new RegExp(TJ,"u");if(!rt.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"emoji",code:m.invalid_string,message:f.message}),T.dirty()}else if(f.kind==="uuid"){if(!uR.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"uuid",code:m.invalid_string,message:f.message}),T.dirty()}else if(f.kind==="nanoid"){if(!aR.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"nanoid",code:m.invalid_string,message:f.message}),T.dirty()}else if(f.kind==="cuid"){if(!lR.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"cuid",code:m.invalid_string,message:f.message}),T.dirty()}else if(f.kind==="cuid2"){if(!eR.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"cuid2",code:m.invalid_string,message:f.message}),T.dirty()}else if(f.kind==="ulid"){if(!dR.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"ulid",code:m.invalid_string,message:f.message}),T.dirty()}else if(f.kind==="url")try{new URL(o.data)}catch(t){S=this._getOrReturnCtx(o,S),L(S,{validation:"url",code:m.invalid_string,message:f.message}),T.dirty()}else if(f.kind==="regex"){if(f.regex.lastIndex=0,!f.regex.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"regex",code:m.invalid_string,message:f.message}),T.dirty()}else if(f.kind==="trim")o.data=o.data.trim();else if(f.kind==="includes"){if(!o.data.includes(f.value,f.position))S=this._getOrReturnCtx(o,S),L(S,{code:m.invalid_string,validation:{includes:f.value,position:f.position},message:f.message}),T.dirty()}else if(f.kind==="toLowerCase")o.data=o.data.toLowerCase();else if(f.kind==="toUpperCase")o.data=o.data.toUpperCase();else if(f.kind==="startsWith"){if(!o.data.startsWith(f.value))S=this._getOrReturnCtx(o,S),L(S,{code:m.invalid_string,validation:{startsWith:f.value},message:f.message}),T.dirty()}else if(f.kind==="endsWith"){if(!o.data.endsWith(f.value))S=this._getOrReturnCtx(o,S),L(S,{code:m.invalid_string,validation:{endsWith:f.value},message:f.message}),T.dirty()}else if(f.kind==="datetime"){if(!TF(f).test(o.data))S=this._getOrReturnCtx(o,S),L(S,{code:m.invalid_string,validation:"datetime",message:f.message}),T.dirty()}else if(f.kind==="date"){if(!yJ.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{code:m.invalid_string,validation:"date",message:f.message}),T.dirty()}else if(f.kind==="time"){if(!$J(f).test(o.data))S=this._getOrReturnCtx(o,S),L(S,{code:m.invalid_string,validation:"time",message:f.message}),T.dirty()}else if(f.kind==="duration"){if(!oJ.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"duration",code:m.invalid_string,message:f.message}),T.dirty()}else if(f.kind==="ip"){if(!kJ(o.data,f.version))S=this._getOrReturnCtx(o,S),L(S,{validation:"ip",code:m.invalid_string,message:f.message}),T.dirty()}else if(f.kind==="jwt"){if(!RJ(o.data,f.alg))S=this._getOrReturnCtx(o,S),L(S,{validation:"jwt",code:m.invalid_string,message:f.message}),T.dirty()}else if(f.kind==="cidr"){if(!JJ(o.data,f.version))S=this._getOrReturnCtx(o,S),L(S,{validation:"cidr",code:m.invalid_string,message:f.message}),T.dirty()}else if(f.kind==="base64"){if(!MJ.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"base64",code:m.invalid_string,message:f.message}),T.dirty()}else if(f.kind==="base64url"){if(!FJ.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"base64url",code:m.invalid_string,message:f.message}),T.dirty()}else Fo.assertNever(f);return{status:T.value,value:o.data}}_regex(o,n,T){return this.refinement((S)=>o.test(S),{validation:n,code:m.invalid_string,...i.errToObj(T)})}_addCheck(o){return new mn({...this._def,checks:[...this._def.checks,o]})}email(o){return this._addCheck({kind:"email",...i.errToObj(o)})}url(o){return this._addCheck({kind:"url",...i.errToObj(o)})}emoji(o){return this._addCheck({kind:"emoji",...i.errToObj(o)})}uuid(o){return this._addCheck({kind:"uuid",...i.errToObj(o)})}nanoid(o){return this._addCheck({kind:"nanoid",...i.errToObj(o)})}cuid(o){return this._addCheck({kind:"cuid",...i.errToObj(o)})}cuid2(o){return this._addCheck({kind:"cuid2",...i.errToObj(o)})}ulid(o){return this._addCheck({kind:"ulid",...i.errToObj(o)})}base64(o){return this._addCheck({kind:"base64",...i.errToObj(o)})}base64url(o){return this._addCheck({kind:"base64url",...i.errToObj(o)})}jwt(o){return this._addCheck({kind:"jwt",...i.errToObj(o)})}ip(o){return this._addCheck({kind:"ip",...i.errToObj(o)})}cidr(o){return this._addCheck({kind:"cidr",...i.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,...i.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,...i.errToObj(o===null||o===void 0?void 0:o.message)})}duration(o){return this._addCheck({kind:"duration",...i.errToObj(o)})}regex(o,n){return this._addCheck({kind:"regex",regex:o,...i.errToObj(n)})}includes(o,n){return this._addCheck({kind:"includes",value:o,position:n===null||n===void 0?void 0:n.position,...i.errToObj(n===null||n===void 0?void 0:n.message)})}startsWith(o,n){return this._addCheck({kind:"startsWith",value:o,...i.errToObj(n)})}endsWith(o,n){return this._addCheck({kind:"endsWith",value:o,...i.errToObj(n)})}min(o,n){return this._addCheck({kind:"min",value:o,...i.errToObj(n)})}max(o,n){return this._addCheck({kind:"max",value:o,...i.errToObj(n)})}length(o,n){return this._addCheck({kind:"length",value:o,...i.errToObj(n)})}nonempty(o){return this.min(1,i.errToObj(o))}trim(){return new mn({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new mn({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new mn({...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 isCIDR(){return!!this._def.checks.find((o)=>o.kind==="cidr")}get isBase64(){return!!this._def.checks.find((o)=>o.kind==="base64")}get isBase64url(){return!!this._def.checks.find((o)=>o.kind==="base64url")}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}}mn.create=(o)=>{var n;return new mn({checks:[],typeName:e.ZodString,coerce:(n=o===null||o===void 0?void 0:o.coerce)!==null&&n!==void 0?n:!1,...oo(o)})};function WJ(o,n){let T=(o.toString().split(".")[1]||"").length,S=(n.toString().split(".")[1]||"").length,f=T>S?T:S,t=parseInt(o.toFixed(f).replace(".","")),A=parseInt(n.toFixed(f).replace(".",""));return t%A/Math.pow(10,f)}class TT extends no{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(o){if(this._def.coerce)o.data=Number(o.data);if(this._getType(o)!==h.number){let f=this._getOrReturnCtx(o);return L(f,{code:m.invalid_type,expected:h.number,received:f.parsedType}),u}let T=void 0,S=new uo;for(let f of this._def.checks)if(f.kind==="int"){if(!Fo.isInteger(o.data))T=this._getOrReturnCtx(o,T),L(T,{code:m.invalid_type,expected:"integer",received:"float",message:f.message}),S.dirty()}else if(f.kind==="min"){if(f.inclusive?o.data<f.value:o.data<=f.value)T=this._getOrReturnCtx(o,T),L(T,{code:m.too_small,minimum:f.value,type:"number",inclusive:f.inclusive,exact:!1,message:f.message}),S.dirty()}else if(f.kind==="max"){if(f.inclusive?o.data>f.value:o.data>=f.value)T=this._getOrReturnCtx(o,T),L(T,{code:m.too_big,maximum:f.value,type:"number",inclusive:f.inclusive,exact:!1,message:f.message}),S.dirty()}else if(f.kind==="multipleOf"){if(WJ(o.data,f.value)!==0)T=this._getOrReturnCtx(o,T),L(T,{code:m.not_multiple_of,multipleOf:f.value,message:f.message}),S.dirty()}else if(f.kind==="finite"){if(!Number.isFinite(o.data))T=this._getOrReturnCtx(o,T),L(T,{code:m.not_finite,message:f.message}),S.dirty()}else Fo.assertNever(f);return{status:S.value,value:o.data}}gte(o,n){return this.setLimit("min",o,!0,i.toString(n))}gt(o,n){return this.setLimit("min",o,!1,i.toString(n))}lte(o,n){return this.setLimit("max",o,!0,i.toString(n))}lt(o,n){return this.setLimit("max",o,!1,i.toString(n))}setLimit(o,n,T,S){return new TT({...this._def,checks:[...this._def.checks,{kind:o,value:n,inclusive:T,message:i.toString(S)}]})}_addCheck(o){return new TT({...this._def,checks:[...this._def.checks,o]})}int(o){return this._addCheck({kind:"int",message:i.toString(o)})}positive(o){return this._addCheck({kind:"min",value:0,inclusive:!1,message:i.toString(o)})}negative(o){return this._addCheck({kind:"max",value:0,inclusive:!1,message:i.toString(o)})}nonpositive(o){return this._addCheck({kind:"max",value:0,inclusive:!0,message:i.toString(o)})}nonnegative(o){return this._addCheck({kind:"min",value:0,inclusive:!0,message:i.toString(o)})}multipleOf(o,n){return this._addCheck({kind:"multipleOf",value:o,message:i.toString(n)})}finite(o){return this._addCheck({kind:"finite",message:i.toString(o)})}safe(o){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:i.toString(o)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:i.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"&&Fo.isInteger(o.value))}get isFinite(){let o=null,n=null;for(let T of this._def.checks)if(T.kind==="finite"||T.kind==="int"||T.kind==="multipleOf")return!0;else if(T.kind==="min"){if(n===null||T.value>n)n=T.value}else if(T.kind==="max"){if(o===null||T.value<o)o=T.value}return Number.isFinite(n)&&Number.isFinite(o)}}TT.create=(o)=>{return new TT({checks:[],typeName:e.ZodNumber,coerce:(o===null||o===void 0?void 0:o.coerce)||!1,...oo(o)})};class ST extends no{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(o){if(this._def.coerce)try{o.data=BigInt(o.data)}catch(f){return this._getInvalidInput(o)}if(this._getType(o)!==h.bigint)return this._getInvalidInput(o);let T=void 0,S=new uo;for(let f of this._def.checks)if(f.kind==="min"){if(f.inclusive?o.data<f.value:o.data<=f.value)T=this._getOrReturnCtx(o,T),L(T,{code:m.too_small,type:"bigint",minimum:f.value,inclusive:f.inclusive,message:f.message}),S.dirty()}else if(f.kind==="max"){if(f.inclusive?o.data>f.value:o.data>=f.value)T=this._getOrReturnCtx(o,T),L(T,{code:m.too_big,type:"bigint",maximum:f.value,inclusive:f.inclusive,message:f.message}),S.dirty()}else if(f.kind==="multipleOf"){if(o.data%f.value!==BigInt(0))T=this._getOrReturnCtx(o,T),L(T,{code:m.not_multiple_of,multipleOf:f.value,message:f.message}),S.dirty()}else Fo.assertNever(f);return{status:S.value,value:o.data}}_getInvalidInput(o){let n=this._getOrReturnCtx(o);return L(n,{code:m.invalid_type,expected:h.bigint,received:n.parsedType}),u}gte(o,n){return this.setLimit("min",o,!0,i.toString(n))}gt(o,n){return this.setLimit("min",o,!1,i.toString(n))}lte(o,n){return this.setLimit("max",o,!0,i.toString(n))}lt(o,n){return this.setLimit("max",o,!1,i.toString(n))}setLimit(o,n,T,S){return new ST({...this._def,checks:[...this._def.checks,{kind:o,value:n,inclusive:T,message:i.toString(S)}]})}_addCheck(o){return new ST({...this._def,checks:[...this._def.checks,o]})}positive(o){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:i.toString(o)})}negative(o){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:i.toString(o)})}nonpositive(o){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:i.toString(o)})}nonnegative(o){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:i.toString(o)})}multipleOf(o,n){return this._addCheck({kind:"multipleOf",value:o,message:i.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}}ST.create=(o)=>{var n;return new ST({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)!==h.boolean){let T=this._getOrReturnCtx(o);return L(T,{code:m.invalid_type,expected:h.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 RT extends no{_parse(o){if(this._def.coerce)o.data=new Date(o.data);if(this._getType(o)!==h.date){let f=this._getOrReturnCtx(o);return L(f,{code:m.invalid_type,expected:h.date,received:f.parsedType}),u}if(isNaN(o.data.getTime())){let f=this._getOrReturnCtx(o);return L(f,{code:m.invalid_date}),u}let T=new uo,S=void 0;for(let f of this._def.checks)if(f.kind==="min"){if(o.data.getTime()<f.value)S=this._getOrReturnCtx(o,S),L(S,{code:m.too_small,message:f.message,inclusive:!0,exact:!1,minimum:f.value,type:"date"}),T.dirty()}else if(f.kind==="max"){if(o.data.getTime()>f.value)S=this._getOrReturnCtx(o,S),L(S,{code:m.too_big,message:f.message,inclusive:!0,exact:!1,maximum:f.value,type:"date"}),T.dirty()}else Fo.assertNever(f);return{status:T.value,value:new Date(o.data.getTime())}}_addCheck(o){return new RT({...this._def,checks:[...this._def.checks,o]})}min(o,n){return this._addCheck({kind:"min",value:o.getTime(),message:i.toString(n)})}max(o,n){return this._addCheck({kind:"max",value:o.getTime(),message:i.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}}RT.create=(o)=>{return new RT({checks:[],coerce:(o===null||o===void 0?void 0:o.coerce)||!1,typeName:e.ZodDate,...oo(o)})};class XS extends no{_parse(o){if(this._getType(o)!==h.symbol){let T=this._getOrReturnCtx(o);return L(T,{code:m.invalid_type,expected:h.symbol,received:T.parsedType}),u}return nn(o.data)}}XS.create=(o)=>{return new XS({typeName:e.ZodSymbol,...oo(o)})};class rT extends no{_parse(o){if(this._getType(o)!==h.undefined){let T=this._getOrReturnCtx(o);return L(T,{code:m.invalid_type,expected:h.undefined,received:T.parsedType}),u}return nn(o.data)}}rT.create=(o)=>{return new rT({typeName:e.ZodUndefined,...oo(o)})};class xT extends no{_parse(o){if(this._getType(o)!==h.null){let T=this._getOrReturnCtx(o);return L(T,{code:m.invalid_type,expected:h.null,received:T.parsedType}),u}return nn(o.data)}}xT.create=(o)=>{return new xT({typeName:e.ZodNull,...oo(o)})};class JT extends no{constructor(){super(...arguments);this._any=!0}_parse(o){return nn(o.data)}}JT.create=(o)=>{return new JT({typeName:e.ZodAny,...oo(o)})};class nT extends no{constructor(){super(...arguments);this._unknown=!0}_parse(o){return nn(o.data)}}nT.create=(o)=>{return new nT({typeName:e.ZodUnknown,...oo(o)})};class Nn extends no{_parse(o){let n=this._getOrReturnCtx(o);return L(n,{code:m.invalid_type,expected:h.never,received:n.parsedType}),u}}Nn.create=(o)=>{return new Nn({typeName:e.ZodNever,...oo(o)})};class YS extends no{_parse(o){if(this._getType(o)!==h.undefined){let T=this._getOrReturnCtx(o);return L(T,{code:m.invalid_type,expected:h.void,received:T.parsedType}),u}return nn(o.data)}}YS.create=(o)=>{return new YS({typeName:e.ZodVoid,...oo(o)})};class Qn extends no{_parse(o){let{ctx:n,status:T}=this._processInputParams(o),S=this._def;if(n.parsedType!==h.array)return L(n,{code:m.invalid_type,expected:h.array,received:n.parsedType}),u;if(S.exactLength!==null){let t=n.data.length>S.exactLength.value,A=n.data.length<S.exactLength.value;if(t||A)L(n,{code:t?m.too_big:m.too_small,minimum:A?S.exactLength.value:void 0,maximum:t?S.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:S.exactLength.message}),T.dirty()}if(S.minLength!==null){if(n.data.length<S.minLength.value)L(n,{code:m.too_small,minimum:S.minLength.value,type:"array",inclusive:!0,exact:!1,message:S.minLength.message}),T.dirty()}if(S.maxLength!==null){if(n.data.length>S.maxLength.value)L(n,{code:m.too_big,maximum:S.maxLength.value,type:"array",inclusive:!0,exact:!1,message:S.maxLength.message}),T.dirty()}if(n.common.async)return Promise.all([...n.data].map((t,A)=>{return S.type._parseAsync(new Un(n,t,n.path,A))})).then((t)=>{return uo.mergeArray(T,t)});let f=[...n.data].map((t,A)=>{return S.type._parseSync(new Un(n,t,n.path,A))});return uo.mergeArray(T,f)}get element(){return this._def.type}min(o,n){return new Qn({...this._def,minLength:{value:o,message:i.toString(n)}})}max(o,n){return new Qn({...this._def,maxLength:{value:o,message:i.toString(n)}})}length(o,n){return new Qn({...this._def,exactLength:{value:o,message:i.toString(n)}})}nonempty(o){return this.min(1,o)}}Qn.create=(o,n)=>{return new Qn({type:o,minLength:null,maxLength:null,exactLength:null,typeName:e.ZodArray,...oo(n)})};function IT(o){if(o instanceof Do){let n={};for(let T in o.shape){let S=o.shape[T];n[T]=Dn.create(IT(S))}return new Do({...o._def,shape:()=>n})}else if(o instanceof Qn)return new Qn({...o._def,type:IT(o.element)});else if(o instanceof Dn)return Dn.create(IT(o.unwrap()));else if(o instanceof gn)return gn.create(IT(o.unwrap()));else if(o instanceof hn)return hn.create(o.items.map((n)=>IT(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=Fo.objectKeys(o);return this._cached={shape:o,keys:n}}_parse(o){if(this._getType(o)!==h.object){let F=this._getOrReturnCtx(o);return L(F,{code:m.invalid_type,expected:h.object,received:F.parsedType}),u}let{status:T,ctx:S}=this._processInputParams(o),{shape:f,keys:t}=this._getCached(),A=[];if(!(this._def.catchall instanceof Nn&&this._def.unknownKeys==="strip")){for(let F in S.data)if(!t.includes(F))A.push(F)}let M=[];for(let F of t){let y=f[F],$=S.data[F];M.push({key:{status:"valid",value:F},value:y._parse(new Un(S,$,S.path,F)),alwaysSet:F in S.data})}if(this._def.catchall instanceof Nn){let F=this._def.unknownKeys;if(F==="passthrough")for(let y of A)M.push({key:{status:"valid",value:y},value:{status:"valid",value:S.data[y]}});else if(F==="strict"){if(A.length>0)L(S,{code:m.unrecognized_keys,keys:A}),T.dirty()}else if(F==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let F=this._def.catchall;for(let y of A){let $=S.data[y];M.push({key:{status:"valid",value:y},value:F._parse(new Un(S,$,S.path,y)),alwaysSet:y in S.data})}}if(S.common.async)return Promise.resolve().then(async()=>{let F=[];for(let y of M){let $=await y.key,W=await y.value;F.push({key:$,value:W,alwaysSet:y.alwaysSet})}return F}).then((F)=>{return uo.mergeObjectSync(T,F)});else return uo.mergeObjectSync(T,M)}get shape(){return this._def.shape()}strict(o){return i.errToObj,new Do({...this._def,unknownKeys:"strict",...o!==void 0?{errorMap:(n,T)=>{var S,f,t,A;let M=(t=(f=(S=this._def).errorMap)===null||f===void 0?void 0:f.call(S,n,T).message)!==null&&t!==void 0?t:T.defaultError;if(n.code==="unrecognized_keys")return{message:(A=i.errToObj(o).message)!==null&&A!==void 0?A:M};return{message:M}}}:{}})}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 Fo.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 Fo.objectKeys(this.shape).forEach((T)=>{if(!o[T])n[T]=this.shape[T]}),new Do({...this._def,shape:()=>n})}deepPartial(){return IT(this)}partial(o){let n={};return Fo.objectKeys(this.shape).forEach((T)=>{let S=this.shape[T];if(o&&!o[T])n[T]=S;else n[T]=S.optional()}),new Do({...this._def,shape:()=>n})}required(o){let n={};return Fo.objectKeys(this.shape).forEach((T)=>{if(o&&!o[T])n[T]=this.shape[T];else{let f=this.shape[T];while(f instanceof Dn)f=f._def.innerType;n[T]=f}}),new Do({...this._def,shape:()=>n})}keyof(){return SF(Fo.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 cT extends no{_parse(o){let{ctx:n}=this._processInputParams(o),T=this._def.options;function S(f){for(let A of f)if(A.result.status==="valid")return A.result;for(let A of f)if(A.result.status==="dirty")return n.common.issues.push(...A.ctx.common.issues),A.result;let t=f.map((A)=>new kn(A.ctx.common.issues));return L(n,{code:m.invalid_union,unionErrors:t}),u}if(n.common.async)return Promise.all(T.map(async(f)=>{let t={...n,common:{...n.common,issues:[]},parent:null};return{result:await f._parseAsync({data:n.data,path:n.path,parent:t}),ctx:t}})).then(S);else{let f=void 0,t=[];for(let M of T){let F={...n,common:{...n.common,issues:[]},parent:null},y=M._parseSync({data:n.data,path:n.path,parent:F});if(y.status==="valid")return y;else if(y.status==="dirty"&&!f)f={result:y,ctx:F};if(F.common.issues.length)t.push(F.common.issues)}if(f)return n.common.issues.push(...f.ctx.common.issues),f.result;let A=t.map((M)=>new kn(M));return L(n,{code:m.invalid_union,unionErrors:A}),u}}get options(){return this._def.options}}cT.create=(o,n)=>{return new cT({options:o,typeName:e.ZodUnion,...oo(n)})};var Zn=(o)=>{if(o instanceof qT)return Zn(o.schema);else if(o instanceof wn)return Zn(o.innerType());else if(o instanceof iT)return[o.value];else if(o instanceof fT)return o.options;else if(o instanceof pT)return Fo.objectValues(o.enum);else if(o instanceof ZT)return Zn(o._def.innerType);else if(o instanceof rT)return[void 0];else if(o instanceof xT)return[null];else if(o instanceof Dn)return[void 0,...Zn(o.unwrap())];else if(o instanceof gn)return[null,...Zn(o.unwrap())];else if(o instanceof Of)return Zn(o.unwrap());else if(o instanceof gT)return Zn(o.unwrap());else if(o instanceof PT)return Zn(o._def.innerType);else return[]};class Wf extends no{_parse(o){let{ctx:n}=this._processInputParams(o);if(n.parsedType!==h.object)return L(n,{code:m.invalid_type,expected:h.object,received:n.parsedType}),u;let T=this.discriminator,S=n.data[T],f=this.optionsMap.get(S);if(!f)return L(n,{code:m.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[T]}),u;if(n.common.async)return f._parseAsync({data:n.data,path:n.path,parent:n});else return f._parseSync({data:n.data,path:n.path,parent:n})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(o,n,T){let S=new Map;for(let f of n){let t=Zn(f.shape[o]);if(!t.length)throw new Error(`A discriminator value for key \`${o}\` could not be extracted from all schema options`);for(let A of t){if(S.has(A))throw new Error(`Discriminator property ${String(o)} has duplicate value ${String(A)}`);S.set(A,f)}}return new Wf({typeName:e.ZodDiscriminatedUnion,discriminator:o,options:n,optionsMap:S,...oo(T)})}}function qt(o,n){let T=Pn(o),S=Pn(n);if(o===n)return{valid:!0,data:o};else if(T===h.object&&S===h.object){let f=Fo.objectKeys(n),t=Fo.objectKeys(o).filter((M)=>f.indexOf(M)!==-1),A={...o,...n};for(let M of t){let F=qt(o[M],n[M]);if(!F.valid)return{valid:!1};A[M]=F.data}return{valid:!0,data:A}}else if(T===h.array&&S===h.array){if(o.length!==n.length)return{valid:!1};let f=[];for(let t=0;t<o.length;t++){let A=o[t],M=n[t],F=qt(A,M);if(!F.valid)return{valid:!1};f.push(F.data)}return{valid:!0,data:f}}else if(T===h.date&&S===h.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),S=(f,t)=>{if(ct(f)||ct(t))return u;let A=qt(f.value,t.value);if(!A.valid)return L(T,{code:m.invalid_intersection_types}),u;if(vt(f)||vt(t))n.dirty();return{status:n.value,value:A.data}};if(T.common.async)return Promise.all([this._def.left._parseAsync({data:T.data,path:T.path,parent:T}),this._def.right._parseAsync({data:T.data,path:T.path,parent:T})]).then(([f,t])=>S(f,t));else return S(this._def.left._parseSync({data:T.data,path:T.path,parent:T}),this._def.right._parseSync({data:T.data,path:T.path,parent:T}))}}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!==h.array)return L(T,{code:m.invalid_type,expected:h.array,received:T.parsedType}),u;if(T.data.length<this._def.items.length)return L(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)L(T,{code:m.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty();let f=[...T.data].map((t,A)=>{let M=this._def.items[A]||this._def.rest;if(!M)return null;return M._parse(new Un(T,t,T.path,A))}).filter((t)=>!!t);if(T.common.async)return Promise.all(f).then((t)=>{return uo.mergeArray(n,t)});else return uo.mergeArray(n,f)}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 GS 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!==h.object)return L(T,{code:m.invalid_type,expected:h.object,received:T.parsedType}),u;let S=[],f=this._def.keyType,t=this._def.valueType;for(let A in T.data)S.push({key:f._parse(new Un(T,A,T.path,A)),value:t._parse(new Un(T,T.data[A],T.path,A)),alwaysSet:A in T.data});if(T.common.async)return uo.mergeObjectAsync(n,S);else return uo.mergeObjectSync(n,S)}get element(){return this._def.valueType}static create(o,n,T){if(n instanceof no)return new GS({keyType:o,valueType:n,typeName:e.ZodRecord,...oo(T)});return new GS({keyType:mn.create(),valueType:o,typeName:e.ZodRecord,...oo(n)})}}class ES 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!==h.map)return L(T,{code:m.invalid_type,expected:h.map,received:T.parsedType}),u;let S=this._def.keyType,f=this._def.valueType,t=[...T.data.entries()].map(([A,M],F)=>{return{key:S._parse(new Un(T,A,T.path,[F,"key"])),value:f._parse(new Un(T,M,T.path,[F,"value"]))}});if(T.common.async){let A=new Map;return Promise.resolve().then(async()=>{for(let M of t){let F=await M.key,y=await M.value;if(F.status==="aborted"||y.status==="aborted")return u;if(F.status==="dirty"||y.status==="dirty")n.dirty();A.set(F.value,y.value)}return{status:n.value,value:A}})}else{let A=new Map;for(let M of t){let{key:F,value:y}=M;if(F.status==="aborted"||y.status==="aborted")return u;if(F.status==="dirty"||y.status==="dirty")n.dirty();A.set(F.value,y.value)}return{status:n.value,value:A}}}}ES.create=(o,n,T)=>{return new ES({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!==h.set)return L(T,{code:m.invalid_type,expected:h.set,received:T.parsedType}),u;let S=this._def;if(S.minSize!==null){if(T.data.size<S.minSize.value)L(T,{code:m.too_small,minimum:S.minSize.value,type:"set",inclusive:!0,exact:!1,message:S.minSize.message}),n.dirty()}if(S.maxSize!==null){if(T.data.size>S.maxSize.value)L(T,{code:m.too_big,maximum:S.maxSize.value,type:"set",inclusive:!0,exact:!1,message:S.maxSize.message}),n.dirty()}let f=this._def.valueType;function t(M){let F=new Set;for(let y of M){if(y.status==="aborted")return u;if(y.status==="dirty")n.dirty();F.add(y.value)}return{status:n.value,value:F}}let A=[...T.data.values()].map((M,F)=>f._parse(new Un(T,M,T.path,F)));if(T.common.async)return Promise.all(A).then((M)=>t(M));else return t(A)}min(o,n){return new WT({...this._def,minSize:{value:o,message:i.toString(n)}})}max(o,n){return new WT({...this._def,maxSize:{value:o,message:i.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!==h.function)return L(n,{code:m.invalid_type,expected:h.function,received:n.parsedType}),u;function T(A,M){return Rf({data:A,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,kf(),hT].filter((F)=>!!F),issueData:{code:m.invalid_arguments,argumentsError:M}})}function S(A,M){return Rf({data:A,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,kf(),hT].filter((F)=>!!F),issueData:{code:m.invalid_return_type,returnTypeError:M}})}let f={errorMap:n.common.contextualErrorMap},t=n.data;if(this._def.returns instanceof OT){let A=this;return nn(async function(...M){let F=new kn([]),y=await A._def.args.parseAsync(M,f).catch((O)=>{throw F.addIssue(T(M,O)),F}),$=await Reflect.apply(t,this,y);return await A._def.returns._def.type.parseAsync($,f).catch((O)=>{throw F.addIssue(S($,O)),F})})}else{let A=this;return nn(function(...M){let F=A._def.args.safeParse(M,f);if(!F.success)throw new kn([T(M,F.error)]);let y=Reflect.apply(t,this,F.data),$=A._def.returns.safeParse(y,f);if(!$.success)throw new kn([S(y,$.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(nT.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(nT.create()),returns:n||nT.create(),typeName:e.ZodFunction,...oo(T)})}}class qT 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})}}qT.create=(o,n)=>{return new qT({getter:o,typeName:e.ZodLazy,...oo(n)})};class iT extends no{_parse(o){if(o.data!==this._def.value){let n=this._getOrReturnCtx(o);return L(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}}iT.create=(o,n)=>{return new iT({value:o,typeName:e.ZodLiteral,...oo(n)})};function SF(o,n){return new fT({values:o,typeName:e.ZodEnum,...oo(n)})}class fT extends no{constructor(){super(...arguments);_S.set(this,void 0)}_parse(o){if(typeof o.data!=="string"){let n=this._getOrReturnCtx(o),T=this._def.values;return L(n,{expected:Fo.joinValues(T),received:n.parsedType,code:m.invalid_type}),u}if(!Jf(this,_S,"f"))sM(this,_S,new Set(this._def.values),"f");if(!Jf(this,_S,"f").has(o.data)){let n=this._getOrReturnCtx(o),T=this._def.values;return L(n,{received:n.data,code:m.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 fT.create(o,{...this._def,...n})}exclude(o,n=this._def){return fT.create(this.options.filter((T)=>!o.includes(T)),{...this._def,...n})}}_S=new WeakMap;fT.create=SF;class pT extends no{constructor(){super(...arguments);wS.set(this,void 0)}_parse(o){let n=Fo.getValidEnumValues(this._def.values),T=this._getOrReturnCtx(o);if(T.parsedType!==h.string&&T.parsedType!==h.number){let S=Fo.objectValues(n);return L(T,{expected:Fo.joinValues(S),received:T.parsedType,code:m.invalid_type}),u}if(!Jf(this,wS,"f"))sM(this,wS,new Set(Fo.getValidEnumValues(this._def.values)),"f");if(!Jf(this,wS,"f").has(o.data)){let S=Fo.objectValues(n);return L(T,{received:T.data,code:m.invalid_enum_value,options:S}),u}return nn(o.data)}get enum(){return this._def.values}}wS=new WeakMap;pT.create=(o,n)=>{return new pT({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!==h.promise&&n.common.async===!1)return L(n,{code:m.invalid_type,expected:h.promise,received:n.parsedType}),u;let T=n.parsedType===h.promise?n.data:Promise.resolve(n.data);return nn(T.then((S)=>{return this._def.type.parseAsync(S,{path:n.path,errorMap:n.common.contextualErrorMap})}))}}OT.create=(o,n)=>{return new OT({type:o,typeName:e.ZodPromise,...oo(n)})};class wn 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),S=this._def.effect||null,f={addIssue:(t)=>{if(L(T,t),t.fatal)n.abort();else n.dirty()},get path(){return T.path}};if(f.addIssue=f.addIssue.bind(f),S.type==="preprocess"){let t=S.transform(T.data,f);if(T.common.async)return Promise.resolve(t).then(async(A)=>{if(n.value==="aborted")return u;let M=await this._def.schema._parseAsync({data:A,path:T.path,parent:T});if(M.status==="aborted")return u;if(M.status==="dirty")return jT(M.value);if(n.value==="dirty")return jT(M.value);return M});else{if(n.value==="aborted")return u;let A=this._def.schema._parseSync({data:t,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}}if(S.type==="refinement"){let t=(A)=>{let M=S.refinement(A,f);if(T.common.async)return Promise.resolve(M);if(M instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return A};if(T.common.async===!1){let A=this._def.schema._parseSync({data:T.data,path:T.path,parent:T});if(A.status==="aborted")return u;if(A.status==="dirty")n.dirty();return t(A.value),{status:n.value,value:A.value}}else return this._def.schema._parseAsync({data:T.data,path:T.path,parent:T}).then((A)=>{if(A.status==="aborted")return u;if(A.status==="dirty")n.dirty();return t(A.value).then(()=>{return{status:n.value,value:A.value}})})}if(S.type==="transform")if(T.common.async===!1){let t=this._def.schema._parseSync({data:T.data,path:T.path,parent:T});if(!kT(t))return t;let A=S.transform(t.value,f);if(A instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:A}}else return this._def.schema._parseAsync({data:T.data,path:T.path,parent:T}).then((t)=>{if(!kT(t))return t;return Promise.resolve(S.transform(t.value,f)).then((A)=>({status:n.value,value:A}))});Fo.assertNever(S)}}wn.create=(o,n,T)=>{return new wn({schema:o,typeName:e.ZodEffects,effect:n,...oo(T)})};wn.createWithPreprocess=(o,n,T)=>{return new wn({schema:n,effect:{type:"preprocess",transform:o},typeName:e.ZodEffects,...oo(T)})};class Dn extends no{_parse(o){if(this._getType(o)===h.undefined)return nn(void 0);return this._def.innerType._parse(o)}unwrap(){return this._def.innerType}}Dn.create=(o,n)=>{return new Dn({innerType:o,typeName:e.ZodOptional,...oo(n)})};class gn extends no{_parse(o){if(this._getType(o)===h.null)return nn(null);return this._def.innerType._parse(o)}unwrap(){return this._def.innerType}}gn.create=(o,n)=>{return new gn({innerType:o,typeName:e.ZodNullable,...oo(n)})};class ZT extends no{_parse(o){let{ctx:n}=this._processInputParams(o),T=n.data;if(n.parsedType===h.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:e.ZodDefault,defaultValue:typeof n.default==="function"?n.default:()=>n.default,...oo(n)})};class PT extends no{_parse(o){let{ctx:n}=this._processInputParams(o),T={...n,common:{...n.common,issues:[]}},S=this._def.innerType._parse({data:T.data,path:T.path,parent:{...T}});if(KS(S))return S.then((f)=>{return{status:"valid",value:f.status==="valid"?f.value:this._def.catchValue({get error(){return new kn(T.common.issues)},input:T.data})}});else return{status:"valid",value:S.status==="valid"?S.value:this._def.catchValue({get error(){return new kn(T.common.issues)},input:T.data})}}removeCatch(){return this._def.innerType}}PT.create=(o,n)=>{return new PT({innerType:o,typeName:e.ZodCatch,catchValue:typeof n.catch==="function"?n.catch:()=>n.catch,...oo(n)})};class HS extends no{_parse(o){if(this._getType(o)!==h.nan){let T=this._getOrReturnCtx(o);return L(T,{code:m.invalid_type,expected:h.nan,received:T.parsedType}),u}return{status:"valid",value:o.data}}}HS.create=(o)=>{return new HS({typeName:e.ZodNaN,...oo(o)})};var OJ=Symbol("zod_brand");class Of 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 zS extends no{_parse(o){let{status:n,ctx:T}=this._processInputParams(o);if(T.common.async)return(async()=>{let f=await this._def.in._parseAsync({data:T.data,path:T.path,parent:T});if(f.status==="aborted")return u;if(f.status==="dirty")return n.dirty(),jT(f.value);else return this._def.out._parseAsync({data:f.value,path:T.path,parent:T})})();else{let S=this._def.in._parseSync({data:T.data,path:T.path,parent:T});if(S.status==="aborted")return u;if(S.status==="dirty")return n.dirty(),{status:"dirty",value:S.value};else return this._def.out._parseSync({data:S.value,path:T.path,parent:T})}}static create(o,n){return new zS({in:o,out:n,typeName:e.ZodPipeline})}}class gT extends no{_parse(o){let n=this._def.innerType._parse(o),T=(S)=>{if(kT(S))S.value=Object.freeze(S.value);return S};return KS(n)?n.then((S)=>T(S)):T(n)}unwrap(){return this._def.innerType}}gT.create=(o,n)=>{return new gT({innerType:o,typeName:e.ZodReadonly,...oo(n)})};function fF(o,n={},T){if(o)return JT.create().superRefine((S,f)=>{var t,A;if(!o(S)){let M=typeof n==="function"?n(S):typeof n==="string"?{message:n}:n,F=(A=(t=M.fatal)!==null&&t!==void 0?t:T)!==null&&A!==void 0?A:!0,y=typeof M==="string"?{message:M}:M;f.addIssue({code:"custom",...y,fatal:F})}});return JT.create()}var _J={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 wJ=(o,n={message:`Input not instance of ${o.name}`})=>fF((T)=>T instanceof o,n),tF=mn.create,AF=TT.create,KJ=HS.create,XJ=ST.create,MF=bT.create,YJ=RT.create,GJ=XS.create,EJ=rT.create,HJ=xT.create,zJ=JT.create,mJ=nT.create,QJ=Nn.create,DJ=YS.create,UJ=Qn.create,VJ=Do.create,BJ=Do.strictCreate,CJ=cT.create,LJ=Wf.create,IJ=vT.create,jJ=hn.create,NJ=GS.create,hJ=ES.create,bJ=WT.create,rJ=NT.create,xJ=qT.create,cJ=iT.create,vJ=fT.create,qJ=pT.create,iJ=OT.create,uM=wn.create,pJ=Dn.create,ZJ=gn.create,PJ=wn.createWithPreprocess,gJ=zS.create,lJ=()=>tF().optional(),eJ=()=>AF().optional(),dJ=()=>MF().optional(),uJ={string:(o)=>mn.create({...o,coerce:!0}),number:(o)=>TT.create({...o,coerce:!0}),boolean:(o)=>bT.create({...o,coerce:!0}),bigint:(o)=>ST.create({...o,coerce:!0}),date:(o)=>RT.create({...o,coerce:!0})},aJ=u,Eo=Object.freeze({__proto__:null,defaultErrorMap:hT,setErrorMap:PR,getErrorMap:kf,makeIssue:Rf,EMPTY_PATH:gR,addIssueToContext:L,ParseStatus:uo,INVALID:u,DIRTY:jT,OK:nn,isAborted:ct,isDirty:vt,isValid:kT,isAsync:KS,get util(){return Fo},get objectUtil(){return xt},ZodParsedType:h,getParsedType:Pn,ZodType:no,datetimeRegex:TF,ZodString:mn,ZodNumber:TT,ZodBigInt:ST,ZodBoolean:bT,ZodDate:RT,ZodSymbol:XS,ZodUndefined:rT,ZodNull:xT,ZodAny:JT,ZodUnknown:nT,ZodNever:Nn,ZodVoid:YS,ZodArray:Qn,ZodObject:Do,ZodUnion:cT,ZodDiscriminatedUnion:Wf,ZodIntersection:vT,ZodTuple:hn,ZodRecord:GS,ZodMap:ES,ZodSet:WT,ZodFunction:NT,ZodLazy:qT,ZodLiteral:iT,ZodEnum:fT,ZodNativeEnum:pT,ZodPromise:OT,ZodEffects:wn,ZodTransformer:wn,ZodOptional:Dn,ZodNullable:gn,ZodDefault:ZT,ZodCatch:PT,ZodNaN:HS,BRAND:OJ,ZodBranded:Of,ZodPipeline:zS,ZodReadonly:gT,custom:fF,Schema:no,ZodSchema:no,late:_J,get ZodFirstPartyTypeKind(){return e},coerce:uJ,any:zJ,array:UJ,bigint:XJ,boolean:MF,date:YJ,discriminatedUnion:LJ,effect:uM,enum:vJ,function:rJ,instanceof:wJ,intersection:IJ,lazy:xJ,literal:cJ,map:hJ,nan:KJ,nativeEnum:qJ,never:QJ,null:HJ,nullable:ZJ,number:AF,object:VJ,oboolean:dJ,onumber:eJ,optional:pJ,ostring:lJ,pipeline:gJ,preprocess:PJ,promise:iJ,record:NJ,set:bJ,strictObject:BJ,string:tF,symbol:GJ,transformer:uM,tuple:jJ,undefined:EJ,union:CJ,unknown:mJ,void:DJ,NEVER:aJ,ZodIssueCode:m,quotelessJson:ZR,ZodError:kn});var sJ="__vite_start_time"in globalThis,o0=typeof window!=="undefined",D6="vitest"in globalThis,Vn=eM({isServer:!sJ&&!o0,server:{CI:Eo.string().transform((o)=>!0).optional(),POSTGRES_USER:Eo.string(),POSTGRES_PASSWORD:Eo.string(),POSTGRES_DATABASE:Eo.string(),POSTGRES_HOST:Eo.string(),POSTGRES_PORT:Eo.string().transform((o)=>Number.parseInt(o,10)),BACKEND_PORT:Eo.string().transform((o)=>Number.parseInt(o,10)),RUN_WORKERS_FROM_SOURCE:Eo.union([Eo.literal("true"),Eo.literal("false")]).optional().transform((o)=>o==="true"),FRONTEND_PORT:Eo.string().transform((o)=>Number.parseInt(o,10)),FRONTEND_ORIGINS:Eo.string().transform((o)=>JSON.parse(o)).pipe(Eo.array(Eo.string())),OPENAI_API_KEY:Eo.string().optional()},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:Eo.string(),VITE_USE_SELF_SIGNED_CERTIFICATE:Eo.union([Eo.literal("true"),Eo.literal("false")]).optional().transform((o)=>o==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var yF=it(import.meta.dirname,"../dev"),$F=Vn.VITE_USE_SELF_SIGNED_CERTIFICATE?{cert:FF(it(yF,"./cert.pem"),"utf-8"),key:FF(it(yF,"./key.pem"),"utf-8")}:void 0;import TW from"path";var R=Symbol.for("drizzle:entityKind"),I6=Symbol.for("drizzle:hasOwnEntityKind");function K(o,n){if(!o||typeof o!=="object")return!1;if(o instanceof n)return!0;if(!Object.prototype.hasOwnProperty.call(n,R))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(R in T&&T[R]===n[R])return!0;T=Object.getPrototypeOf(T)}return!1}class Jo{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[R]="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 pt{static[R]="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 Bn=Symbol.for("drizzle:Name");class Zt{static[R]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(o,n){if(this.reference=()=>{let{name:T,columns:S,foreignColumns:f}=o();return{name:T,columns:S,foreignTable:f[0].table,foreignColumns:f}},n)this._onUpdate=n.onUpdate,this._onDelete=n.onDelete}onUpdate(o){return this._onUpdate=o===void 0?"no action":o,this}onDelete(o){return this._onDelete=o===void 0?"no action":o,this}build(o){return new kF(o,this)}}class kF{constructor(o,n){this.table=o,this.reference=n.reference,this.onUpdate=n._onUpdate,this.onDelete=n._onDelete}static[R]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:o,columns:n,foreignColumns:T}=this.reference(),S=n.map((A)=>A.name),f=T.map((A)=>A.name),t=[this.table[Bn],...S,T[0].table[Bn],...f];return o??`${t.join("_")}_fk`}}function _f(o,...n){return o(...n)}function RF(o,n){return`${o[Bn]}_${n.join("_")}_unique`}function JF(o,n,T){for(let S=n;S<o.length;S++){let f=o[S];if(f==="\\"){S++;continue}if(f==='"')return[o.slice(n,S).replace(/\\/g,""),S+1];if(T)continue;if(f===","||f==="}")return[o.slice(n,S).replace(/\\/g,""),S]}return[o.slice(n).replace(/\\/g,""),o.length]}function WF(o,n=0){let T=[],S=n,f=!1;while(S<o.length){let t=o[S];if(t===","){if(f||S===n)T.push("");f=!0,S++;continue}if(f=!1,t==="\\"){S+=2;continue}if(t==='"'){let[F,y]=JF(o,S+1,!0);T.push(F),S=y;continue}if(t==="}")return[T,S+1];if(t==="{"){let[F,y]=WF(o,S+1);T.push(F),S=y;continue}let[A,M]=JF(o,S,!1);T.push(A),S=M}return[T,S]}function OF(o){let[n]=WF(o,1);return n}function Pt(o){return`{${o.map((n)=>{if(Array.isArray(n))return Pt(n);if(typeof n==="string")return`"${n.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${n}`}).join(",")}}`}class x extends pt{foreignKeyConfigs=[];static[R]="PgColumnBuilder";array(o){return new wF(this.config.name,this,o)}references(o,n={}){return this.foreignKeyConfigs.push({ref:o,actions:n}),this}unique(o,n){return this.config.isUnique=!0,this.config.uniqueName=o,this.config.uniqueType=n?.nulls,this}generatedAlwaysAs(o){return this.config.generated={as:o,type:"always",mode:"stored"},this}buildForeignKeys(o,n){return this.foreignKeyConfigs.map(({ref:T,actions:S})=>{return _f((f,t)=>{let A=new Zt(()=>{let M=f();return{columns:[o],foreignColumns:[M]}});if(t.onUpdate)A.onUpdate(t.onUpdate);if(t.onDelete)A.onDelete(t.onDelete);return A.build(n)},T,S)})}buildExtraConfigColumn(o){return new _F(o,this.config)}}class V extends Jo{constructor(o,n){if(!n.uniqueName)n.uniqueName=RF(o,[n.name]);super(o,n);this.table=o}static[R]="PgColumn"}class _F extends V{static[R]="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 mS{static[R]="IndexedColumn";constructor(o,n,T,S){this.name=o,this.keyAsName=n,this.type=T,this.indexConfig=S}name;keyAsName;type;indexConfig}class wF extends x{static[R]="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 gt(o,this.config,n)}}class gt extends V{constructor(o,n,T,S){super(o,n);this.baseColumn=T,this.range=S,this.size=n.size}size;static[R]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(o){if(typeof o==="string")o=OF(o);return o.map((n)=>this.baseColumn.mapFromDriverValue(n))}mapToDriverValue(o,n=!1){let T=o.map((S)=>S===null?null:K(this.baseColumn,gt)?this.baseColumn.mapToDriverValue(S,!0):this.baseColumn.mapToDriverValue(S));if(n)return T;return Pt(T)}}var lt=Symbol.for("drizzle:isPgEnum");function KF(o){return!!o&&typeof o==="function"&&lt in o&&o[lt]===!0}class XF extends x{static[R]="PgEnumColumnBuilder";constructor(o,n){super(o,"string","PgEnumColumn");this.config.enum=n}build(o){return new YF(o,this.config)}}class YF extends V{static[R]="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 wf(o,n){return n0(o,n,void 0)}function n0(o,n,T){let S=Object.assign((f)=>new XF(f??"",S),{enumName:o,enumValues:n,schema:T,[lt]:!0});return S}class ro{static[R]="Subquery";constructor(o,n,T,S=!1){this._={brand:"Subquery",sql:o,selectedFields:n,alias:T,isWith:S}}}class QS extends ro{static[R]="WithSubquery"}var GF="0.39.1";var et,dt,Wo={startActiveSpan(o,n){if(!et)return n();if(!dt)dt=et.trace.getTracer("drizzle-orm",GF);return _f((T,S)=>S.startActiveSpan(o,(f)=>{try{return n(f)}catch(t){throw f.setStatus({code:T.SpanStatusCode.ERROR,message:t instanceof Error?t.message:"Unknown error"}),t}finally{f.end()}}),et,dt)}};var Ko=Symbol.for("drizzle:ViewBaseConfig");var Kf=Symbol.for("drizzle:Schema"),Xf=Symbol.for("drizzle:Columns"),EF=Symbol.for("drizzle:ExtraConfigColumns"),ut=Symbol.for("drizzle:OriginalName"),at=Symbol.for("drizzle:BaseName"),DS=Symbol.for("drizzle:IsAlias"),HF=Symbol.for("drizzle:ExtraConfigBuilder"),T0=Symbol.for("drizzle:IsDrizzleTable");class I{static[R]="Table";static Symbol={Name:Bn,Schema:Kf,OriginalName:ut,Columns:Xf,ExtraConfigColumns:EF,BaseName:at,IsAlias:DS,ExtraConfigBuilder:HF};[Bn];[ut];[Kf];[Xf];[EF];[at];[DS]=!1;[T0]=!0;[HF]=void 0;constructor(o,n,T){this[Bn]=this[ut]=o,this[Kf]=n,this[at]=T}}function co(o){return o[Bn]}function _T(o){return`${o[Kf]??"public"}.${o[Bn]}`}function st(o){return o!==null&&o!==void 0&&typeof o.getSQL==="function"}function S0(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 xo{static[R]="StringChunk";value;constructor(o){this.value=Array.isArray(o)?o:[o]}getSQL(){return new N([this])}}class N{constructor(o){this.queryChunks=o}static[R]="SQL";decoder=mF;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:S,escapeName:f,escapeParam:t,prepareTyping:A,inlineParams:M,paramStartIndex:F}=T;return S0(o.map((y)=>{if(K(y,xo))return{sql:y.value.join(""),params:[]};if(K(y,Yf))return{sql:f(y.value),params:[]};if(y===void 0)return{sql:"",params:[]};if(Array.isArray(y)){let $=[new xo("(")];for(let[W,O]of y.entries())if($.push(O),W<y.length-1)$.push(new xo(", "));return $.push(new xo(")")),this.buildQueryFromSourceParams($,T)}if(K(y,N))return this.buildQueryFromSourceParams(y.queryChunks,{...T,inlineParams:M||y.shouldInlineParams});if(K(y,I)){let $=y[I.Symbol.Schema],W=y[I.Symbol.Name];return{sql:$===void 0||y[DS]?f(W):f($)+"."+f(W),params:[]}}if(K(y,Jo)){let $=S.getColumnCasing(y);if(n.invokeSource==="indexes")return{sql:f($),params:[]};let W=y.table[I.Symbol.Schema];return{sql:y.table[DS]||W===void 0?f(y.table[I.Symbol.Name])+"."+f($):f(W)+"."+f(y.table[I.Symbol.Name])+"."+f($),params:[]}}if(K(y,Mn)){let $=y[Ko].schema,W=y[Ko].name;return{sql:$===void 0||y[Ko].isAlias?f(W):f($)+"."+f(W),params:[]}}if(K(y,Rn)){if(K(y.value,tT))return{sql:t(F.value++,y),params:[y],typings:["none"]};let $=y.value===null?null:y.encoder.mapToDriverValue(y.value);if(K($,N))return this.buildQueryFromSourceParams([$],T);if(M)return{sql:this.mapInlineParam($,T),params:[]};let W=["none"];if(A)W=[A(y.encoder)];return{sql:t(F.value++,$),params:[$],typings:W}}if(K(y,tT))return{sql:t(F.value++,y),params:[y],typings:["none"]};if(K(y,N.Aliased)&&y.fieldAlias!==void 0)return{sql:f(y.fieldAlias),params:[]};if(K(y,ro)){if(y._.isWith)return{sql:f(y._.alias),params:[]};return this.buildQueryFromSourceParams([new xo("("),y._.sql,new xo(") "),new Yf(y._.alias)],T)}if(KF(y)){if(y.schema)return{sql:f(y.schema)+"."+f(y.enumName),params:[]};return{sql:f(y.enumName),params:[]}}if(st(y)){if(y.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([y.getSQL()],T);return this.buildQueryFromSourceParams([new xo("("),y.getSQL(),new xo(")")],T)}if(M)return{sql:this.mapInlineParam(y,T),params:[]};return{sql:t(F.value++,y),params:[y],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 N.Aliased(this,o)}mapWith(o){return this.decoder=typeof o==="function"?{mapFromDriverValue:o}:o,this}inlineParams(){return this.shouldInlineParams=!0,this}if(o){return o?this:void 0}}class Yf{constructor(o){this.value=o}static[R]="Name";brand;getSQL(){return new N([this])}}function zF(o){return typeof o==="object"&&o!==null&&"mapToDriverValue"in o&&typeof o.mapToDriverValue==="function"}var mF={mapFromDriverValue:(o)=>o},QF={mapToDriverValue:(o)=>o},GY={...mF,...QF};class Rn{constructor(o,n=QF){this.value=o,this.encoder=n}static[R]="Param";brand;getSQL(){return new N([this])}}function J(o,...n){let T=[];if(n.length>0||o.length>0&&o[0]!=="")T.push(new xo(o[0]));for(let[S,f]of n.entries())T.push(f,new xo(o[S+1]));return new N(T)}((o)=>{function n(){return new N([])}o.empty=n;function T(F){return new N(F)}o.fromList=T;function S(F){return new N([new xo(F)])}o.raw=S;function f(F,y){let $=[];for(let[W,O]of F.entries()){if(W>0&&y!==void 0)$.push(y);$.push(O)}return new N($)}o.join=f;function t(F){return new Yf(F)}o.identifier=t;function A(F){return new tT(F)}o.placeholder=A;function M(F,y){return new Rn(F,y)}o.param=M})(J||(J={}));((o)=>{class n{constructor(T,S){this.sql=T,this.fieldAlias=S}static[R]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new n(this.sql,this.fieldAlias)}}o.Aliased=n})(N||(N={}));class tT{constructor(o){this.name=o}static[R]="Placeholder";getSQL(){return new N([this])}}function oA(o,n){return o.map((T)=>{if(K(T,tT)){if(!(T.name in n))throw new Error(`No value for placeholder "${T.name}" was provided`);return n[T.name]}if(K(T,Rn)&&K(T.value,tT)){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})}var f0=Symbol.for("drizzle:IsDrizzleView");class Mn{static[R]="View";[Ko];[f0]=!0;constructor({name:o,schema:n,selectedFields:T,query:S}){this[Ko]={name:o,originalName:o,schema:n,selectedFields:T,query:S,isExisting:!S,isAlias:!1}}getSQL(){return new N([this])}}Jo.prototype.getSQL=function(){return new N([this])};I.prototype.getSQL=function(){return new N([this])};ro.prototype.getSQL=function(){return new N([this])};class lT{constructor(o){this.table=o}static[R]="ColumnAliasProxyHandler";get(o,n){if(n==="table")return this.table;return o[n]}}class US{constructor(o,n){this.alias=o,this.replaceOriginalName=n}static[R]="TableAliasProxyHandler";get(o,n){if(n===I.Symbol.IsAlias)return!0;if(n===I.Symbol.Name)return this.alias;if(this.replaceOriginalName&&n===I.Symbol.OriginalName)return this.alias;if(n===Ko)return{...o[Ko],name:this.alias,isAlias:!0};if(n===I.Symbol.Columns){let S=o[I.Symbol.Columns];if(!S)return S;let f={};return Object.keys(S).map((t)=>{f[t]=new Proxy(S[t],new lT(new Proxy(o,this)))}),f}let T=o[n];if(K(T,Jo))return new Proxy(T,new lT(new Proxy(o,this)));return T}}function Gf(o,n){return new Proxy(o,new US(n,!1))}function bn(o,n){return new Proxy(o,new lT(new Proxy(o.table,new US(n,!1))))}function nA(o,n){return new N.Aliased(VS(o.sql,n),o.fieldAlias)}function VS(o,n){return J.join(o.queryChunks.map((T)=>{if(K(T,Jo))return bn(T,n);if(K(T,N))return VS(T,n);if(K(T,N.Aliased))return nA(T,n);return T}))}class Ef extends Error{static[R]="DrizzleError";constructor({message:o,cause:n}){super(o);this.name="DrizzleError",this.cause=n}}class TA extends Ef{static[R]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}function Fn(o,n){if(zF(n)&&!st(o)&&!K(o,Rn)&&!K(o,tT)&&!K(o,Jo)&&!K(o,I)&&!K(o,Mn))return new Rn(o,n);return o}var Hf=(o,n)=>{return J`${o} = ${Fn(n,o)}`},DF=(o,n)=>{return J`${o} <> ${Fn(n,o)}`};function BS(...o){let n=o.filter((T)=>T!==void 0);if(n.length===0)return;if(n.length===1)return new N(n);return new N([new xo("("),J.join(n,new xo(" and ")),new xo(")")])}function UF(...o){let n=o.filter((T)=>T!==void 0);if(n.length===0)return;if(n.length===1)return new N(n);return new N([new xo("("),J.join(n,new xo(" or ")),new xo(")")])}function VF(o){return J`not ${o}`}var BF=(o,n)=>{return J`${o} > ${Fn(n,o)}`},CF=(o,n)=>{return J`${o} >= ${Fn(n,o)}`},LF=(o,n)=>{return J`${o} < ${Fn(n,o)}`},IF=(o,n)=>{return J`${o} <= ${Fn(n,o)}`};function jF(o,n){if(Array.isArray(n)){if(n.length===0)return J`false`;return J`${o} in ${n.map((T)=>Fn(T,o))}`}return J`${o} in ${Fn(n,o)}`}function NF(o,n){if(Array.isArray(n)){if(n.length===0)return J`true`;return J`${o} not in ${n.map((T)=>Fn(T,o))}`}return J`${o} not in ${Fn(n,o)}`}function hF(o){return J`${o} is null`}function bF(o){return J`${o} is not null`}function rF(o){return J`exists ${o}`}function xF(o){return J`not exists ${o}`}function cF(o,n,T){return J`${o} between ${Fn(n,o)} and ${Fn(T,o)}`}function vF(o,n,T){return J`${o} not between ${Fn(n,o)} and ${Fn(T,o)}`}function qF(o,n){return J`${o} like ${n}`}function iF(o,n){return J`${o} not like ${n}`}function pF(o,n){return J`${o} ilike ${n}`}function ZF(o,n){return J`${o} not ilike ${n}`}function PF(o){return J`${o} asc`}function gF(o){return J`${o} desc`}class lF{static[R]="ConsoleLogWriter";write(o){console.log(o)}}class SA{static[R]="DefaultLogger";writer;constructor(o){this.writer=o?.writer??new lF}logQuery(o,n){let T=n.map((f)=>{try{return JSON.stringify(f)}catch{return String(f)}}),S=T.length?` -- params: [${T.join(", ")}]`:"";this.writer.write(`Query: ${o}${S}`)}}class fA{static[R]="NoopLogger";logQuery(){}}class Tn{static[R]="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 eF(o,n,T){let S={},f=o.reduce((t,{path:A,field:M},F)=>{let y;if(K(M,Jo))y=M;else if(K(M,N))y=M.decoder;else y=M.sql.decoder;let $=t;for(let[W,O]of A.entries())if(W<A.length-1){if(!(O in $))$[O]={};$=$[O]}else{let E=n[F],Q=$[O]=E===null?null:y.mapFromDriverValue(E);if(T&&K(M,Jo)&&A.length===2){let H=A[0];if(!(H in S))S[H]=Q===null?co(M.table):!1;else if(typeof S[H]==="string"&&S[H]!==co(M.table))S[H]=!1}}return t},{});if(T&&Object.keys(S).length>0){for(let[t,A]of Object.entries(S))if(typeof A==="string"&&!T[A])f[t]=null}return f}function Kn(o,n){return Object.entries(o).reduce((T,[S,f])=>{if(typeof S!=="string")return T;let t=n?[...n,S]:[S];if(K(f,Jo)||K(f,N)||K(f,N.Aliased))T.push({path:t,field:f});else if(K(f,I))T.push(...Kn(f[I.Symbol.Columns],t));else T.push(...Kn(f,t));return T},[])}function CS(o,n){let T=Object.keys(o),S=Object.keys(n);if(T.length!==S.length)return!1;for(let[f,t]of T.entries())if(t!==S[f])return!1;return!0}function zf(o,n){let T=Object.entries(n).filter(([,S])=>S!==void 0).map(([S,f])=>{if(K(f,N)||K(f,Jo))return[S,f];else return[S,new Rn(f,o[I.Symbol.Columns][S])]});if(T.length===0)throw new Error("No values to set");return Object.fromEntries(T)}function dF(o,n){for(let T of n)for(let S of Object.getOwnPropertyNames(T.prototype)){if(S==="constructor")continue;Object.defineProperty(o.prototype,S,Object.getOwnPropertyDescriptor(T.prototype,S)||Object.create(null))}}function uF(o){return o[I.Symbol.Columns]}function ln(o){return K(o,ro)?o._.alias:K(o,Mn)?o[Ko].name:K(o,N)?void 0:o[I.Symbol.IsAlias]?o[I.Symbol.Name]:o[I.Symbol.BaseName]}function fo(o,n){return{name:typeof o==="string"&&o.length>0?o:"",config:typeof o==="object"?o:n}}function aF(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 AT extends x{static[R]="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 sF extends AT{static[R]="PgBigInt53Builder";constructor(o){super(o,"number","PgBigInt53")}build(o){return new oy(o,this.config)}}class oy extends V{static[R]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}}class ny extends AT{static[R]="PgBigInt64Builder";constructor(o){super(o,"bigint","PgBigInt64")}build(o){return new Ty(o,this.config)}}class Ty extends V{static[R]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(o){return BigInt(o)}}function Sy(o,n){let{name:T,config:S}=fo(o,n);if(S.mode==="number")return new sF(T);return new ny(T)}class fy extends x{static[R]="PgBigSerial53Builder";constructor(o){super(o,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new ty(o,this.config)}}class ty extends V{static[R]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}}class Ay extends x{static[R]="PgBigSerial64Builder";constructor(o){super(o,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(o){return new My(o,this.config)}}class My extends V{static[R]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(o){return BigInt(o)}}function Fy(o,n){let{name:T,config:S}=fo(o,n);if(S.mode==="number")return new fy(T);return new Ay(T)}class yy extends x{static[R]="PgBooleanBuilder";constructor(o){super(o,"boolean","PgBoolean")}build(o){return new $y(o,this.config)}}class $y extends V{static[R]="PgBoolean";getSQLType(){return"boolean"}}function LS(o){return new yy(o??"")}class ky extends x{static[R]="PgCharBuilder";constructor(o,n){super(o,"string","PgChar");this.config.length=n.length,this.config.enumValues=n.enum}build(o){return new Ry(o,this.config)}}class Ry extends V{static[R]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function Jy(o,n={}){let{name:T,config:S}=fo(o,n);return new ky(T,S)}class Wy extends x{static[R]="PgCidrBuilder";constructor(o){super(o,"string","PgCidr")}build(o){return new Oy(o,this.config)}}class Oy extends V{static[R]="PgCidr";getSQLType(){return"cidr"}}function _y(o){return new Wy(o??"")}class wy extends x{static[R]="PgCustomColumnBuilder";constructor(o,n,T){super(o,"custom","PgCustomColumn");this.config.fieldConfig=n,this.config.customTypeParams=T}build(o){return new Ky(o,this.config)}}class Ky extends V{static[R]="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 Xy(o){return(n,T)=>{let{name:S,config:f}=fo(n,T);return new wy(S,f,o)}}class en extends x{static[R]="PgDateColumnBaseBuilder";defaultNow(){return this.default(J`now()`)}}class Yy extends en{static[R]="PgDateBuilder";constructor(o){super(o,"date","PgDate")}build(o){return new mf(o,this.config)}}class mf extends V{static[R]="PgDate";getSQLType(){return"date"}mapFromDriverValue(o){return new Date(o)}mapToDriverValue(o){return o.toISOString()}}class Gy extends en{static[R]="PgDateStringBuilder";constructor(o){super(o,"string","PgDateString")}build(o){return new Qf(o,this.config)}}class Qf extends V{static[R]="PgDateString";getSQLType(){return"date"}}function Ey(o,n){let{name:T,config:S}=fo(o,n);if(S?.mode==="date")return new Yy(T);return new Gy(T)}class Hy extends x{static[R]="PgDoublePrecisionBuilder";constructor(o){super(o,"number","PgDoublePrecision")}build(o){return new zy(o,this.config)}}class zy extends V{static[R]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseFloat(o);return o}}function my(o){return new Hy(o??"")}class Qy extends x{static[R]="PgInetBuilder";constructor(o){super(o,"string","PgInet")}build(o){return new Dy(o,this.config)}}class Dy extends V{static[R]="PgInet";getSQLType(){return"inet"}}function Uy(o){return new Qy(o??"")}class Vy extends AT{static[R]="PgIntegerBuilder";constructor(o){super(o,"number","PgInteger")}build(o){return new By(o,this.config)}}class By extends V{static[R]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseInt(o);return o}}function Df(o){return new Vy(o??"")}class Cy extends x{static[R]="PgIntervalBuilder";constructor(o,n){super(o,"string","PgInterval");this.config.intervalConfig=n}build(o){return new Ly(o,this.config)}}class Ly extends V{static[R]="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 Iy(o,n={}){let{name:T,config:S}=fo(o,n);return new Cy(T,S)}class jy extends x{static[R]="PgJsonBuilder";constructor(o){super(o,"json","PgJson")}build(o){return new Uf(o,this.config)}}class Uf extends V{static[R]="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 Ny(o){return new jy(o??"")}class hy extends x{static[R]="PgJsonbBuilder";constructor(o){super(o,"json","PgJsonb")}build(o){return new Vf(o,this.config)}}class Vf extends V{static[R]="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 by(o){return new hy(o??"")}class ry extends x{static[R]="PgLineBuilder";constructor(o){super(o,"array","PgLine")}build(o){return new xy(o,this.config)}}class xy extends V{static[R]="PgLine";getSQLType(){return"line"}mapFromDriverValue(o){let[n,T,S]=o.slice(1,-1).split(",");return[Number.parseFloat(n),Number.parseFloat(T),Number.parseFloat(S)]}mapToDriverValue(o){return`{${o[0]},${o[1]},${o[2]}}`}}class cy extends x{static[R]="PgLineABCBuilder";constructor(o){super(o,"json","PgLineABC")}build(o){return new vy(o,this.config)}}class vy extends V{static[R]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(o){let[n,T,S]=o.slice(1,-1).split(",");return{a:Number.parseFloat(n),b:Number.parseFloat(T),c:Number.parseFloat(S)}}mapToDriverValue(o){return`{${o.a},${o.b},${o.c}}`}}function qy(o,n){let{name:T,config:S}=fo(o,n);if(!S?.mode||S.mode==="tuple")return new ry(T);return new cy(T)}class iy extends x{static[R]="PgMacaddrBuilder";constructor(o){super(o,"string","PgMacaddr")}build(o){return new py(o,this.config)}}class py extends V{static[R]="PgMacaddr";getSQLType(){return"macaddr"}}function Zy(o){return new iy(o??"")}class Py extends x{static[R]="PgMacaddr8Builder";constructor(o){super(o,"string","PgMacaddr8")}build(o){return new gy(o,this.config)}}class gy extends V{static[R]="PgMacaddr8";getSQLType(){return"macaddr8"}}function ly(o){return new Py(o??"")}class ey extends x{static[R]="PgNumericBuilder";constructor(o,n,T){super(o,"string","PgNumeric");this.config.precision=n,this.config.scale=T}build(o){return new Bf(o,this.config)}}class Bf extends V{static[R]="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 dy(o,n){let{name:T,config:S}=fo(o,n);return new ey(T,S?.precision,S?.scale)}class uy extends x{static[R]="PgPointTupleBuilder";constructor(o){super(o,"array","PgPointTuple")}build(o){return new ay(o,this.config)}}class ay extends V{static[R]="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 sy extends x{static[R]="PgPointObjectBuilder";constructor(o){super(o,"json","PgPointObject")}build(o){return new o$(o,this.config)}}class o$ extends V{static[R]="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 n$(o,n){let{name:T,config:S}=fo(o,n);if(!S?.mode||S.mode==="tuple")return new uy(T);return new sy(T)}function t0(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 T$(o,n){let T=new ArrayBuffer(8),S=new DataView(T);for(let f=0;f<8;f++)S.setUint8(f,o[n+f]);return S.getFloat64(0,!0)}function tA(o){let n=t0(o),T=0,S=n[T];T+=1;let f=new DataView(n.buffer),t=f.getUint32(T,S===1);T+=4;let A;if(t&536870912)A=f.getUint32(T,S===1),T+=4;if((t&65535)===1){let M=T$(n,T);T+=8;let F=T$(n,T);return T+=8,[M,F]}throw new Error("Unsupported geometry type")}class S$ extends x{static[R]="PgGeometryBuilder";constructor(o){super(o,"array","PgGeometry")}build(o){return new f$(o,this.config)}}class f$ extends V{static[R]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(o){return tA(o)}mapToDriverValue(o){return`point(${o[0]} ${o[1]})`}}class t$ extends x{static[R]="PgGeometryObjectBuilder";constructor(o){super(o,"json","PgGeometryObject")}build(o){return new A$(o,this.config)}}class A$ extends V{static[R]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(o){let n=tA(o);return{x:n[0],y:n[1]}}mapToDriverValue(o){return`point(${o.x} ${o.y})`}}function M$(o,n){let{name:T,config:S}=fo(o,n);if(!S?.mode||S.mode==="tuple")return new S$(T);return new t$(T)}class F$ extends x{static[R]="PgRealBuilder";constructor(o,n){super(o,"number","PgReal");this.config.length=n}build(o){return new y$(o,this.config)}}class y$ extends V{static[R]="PgReal";constructor(o,n){super(o,n)}getSQLType(){return"real"}mapFromDriverValue=(o)=>{if(typeof o==="string")return Number.parseFloat(o);return o}}function $$(o){return new F$(o??"")}class k$ extends x{static[R]="PgSerialBuilder";constructor(o){super(o,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new R$(o,this.config)}}class R$ extends V{static[R]="PgSerial";getSQLType(){return"serial"}}function J$(o){return new k$(o??"")}class W$ extends AT{static[R]="PgSmallIntBuilder";constructor(o){super(o,"number","PgSmallInt")}build(o){return new O$(o,this.config)}}class O$ extends V{static[R]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(o)=>{if(typeof o==="string")return Number(o);return o}}function _$(o){return new W$(o??"")}class w$ extends x{static[R]="PgSmallSerialBuilder";constructor(o){super(o,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new K$(o,this.config)}}class K$ extends V{static[R]="PgSmallSerial";getSQLType(){return"smallserial"}}function X$(o){return new w$(o??"")}class Y$ extends x{static[R]="PgTextBuilder";constructor(o,n){super(o,"string","PgText");this.config.enumValues=n.enum}build(o){return new G$(o,this.config)}}class G$ extends V{static[R]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function E$(o,n={}){let{name:T,config:S}=fo(o,n);return new Y$(T,S)}class H$ extends en{constructor(o,n,T){super(o,"string","PgTime");this.withTimezone=n,this.precision=T,this.config.withTimezone=n,this.config.precision=T}static[R]="PgTimeBuilder";build(o){return new Cf(o,this.config)}}class Cf extends V{static[R]="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 z$(o,n={}){let{name:T,config:S}=fo(o,n);return new H$(T,S.withTimezone??!1,S.precision)}class m$ extends en{static[R]="PgTimestampBuilder";constructor(o,n,T){super(o,"date","PgTimestamp");this.config.withTimezone=n,this.config.precision=T}build(o){return new Lf(o,this.config)}}class Lf extends V{static[R]="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 Q$ extends en{static[R]="PgTimestampStringBuilder";constructor(o,n,T){super(o,"string","PgTimestampString");this.config.withTimezone=n,this.config.precision=T}build(o){return new If(o,this.config)}}class If extends V{static[R]="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 Cn(o,n={}){let{name:T,config:S}=fo(o,n);if(S?.mode==="string")return new Q$(T,S.withTimezone??!1,S.precision);return new m$(T,S?.withTimezone??!1,S?.precision)}class D$ extends x{static[R]="PgUUIDBuilder";constructor(o){super(o,"string","PgUUID")}defaultRandom(){return this.default(J`gen_random_uuid()`)}build(o){return new jf(o,this.config)}}class jf extends V{static[R]="PgUUID";getSQLType(){return"uuid"}}function Jn(o){return new D$(o??"")}class U$ extends x{static[R]="PgVarcharBuilder";constructor(o,n){super(o,"string","PgVarchar");this.config.length=n.length,this.config.enumValues=n.enum}build(o){return new V$(o,this.config)}}class V$ extends V{static[R]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function qo(o,n={}){let{name:T,config:S}=fo(o,n);return new U$(T,S)}class B$ extends x{static[R]="PgBinaryVectorBuilder";constructor(o,n){super(o,"string","PgBinaryVector");this.config.dimensions=n.dimensions}build(o){return new C$(o,this.config)}}class C$ extends V{static[R]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function L$(o,n){let{name:T,config:S}=fo(o,n);return new B$(T,S)}class I$ extends x{static[R]="PgHalfVectorBuilder";constructor(o,n){super(o,"array","PgHalfVector");this.config.dimensions=n.dimensions}build(o){return new j$(o,this.config)}}class j$ extends V{static[R]="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 N$(o,n){let{name:T,config:S}=fo(o,n);return new I$(T,S)}class h$ extends x{static[R]="PgSparseVectorBuilder";constructor(o,n){super(o,"string","PgSparseVector");this.config.dimensions=n.dimensions}build(o){return new b$(o,this.config)}}class b$ extends V{static[R]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function r$(o,n){let{name:T,config:S}=fo(o,n);return new h$(T,S)}class x$ extends x{static[R]="PgVectorBuilder";constructor(o,n){super(o,"array","PgVector");this.config.dimensions=n.dimensions}build(o){return new c$(o,this.config)}}class c$ extends V{static[R]="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 v$(o,n){let{name:T,config:S}=fo(o,n);return new x$(T,S)}function q$(){return{bigint:Sy,bigserial:Fy,boolean:LS,char:Jy,cidr:_y,customType:Xy,date:Ey,doublePrecision:my,inet:Uy,integer:Df,interval:Iy,json:Ny,jsonb:by,line:qy,macaddr:Zy,macaddr8:ly,numeric:dy,point:n$,geometry:M$,real:$$,serial:J$,smallint:_$,smallserial:X$,text:E$,time:z$,timestamp:Cn,uuid:Jn,varchar:qo,bit:L$,halfvec:N$,sparsevec:r$,vector:v$}}var AA=Symbol.for("drizzle:PgInlineForeignKeys"),i$=Symbol.for("drizzle:EnableRLS");class io extends I{static[R]="PgTable";static Symbol=Object.assign({},I.Symbol,{InlineForeignKeys:AA,EnableRLS:i$});[AA]=[];[i$]=!1;[I.Symbol.ExtraConfigBuilder]=void 0}function A0(o,n,T,S,f=o){let t=new io(o,S,f),A=typeof n==="function"?n(q$()):n,M=Object.fromEntries(Object.entries(A).map(([$,W])=>{let O=W;O.setName($);let E=O.build(t);return t[AA].push(...O.buildForeignKeys(E,t)),[$,E]})),F=Object.fromEntries(Object.entries(A).map(([$,W])=>{let O=W;O.setName($);let E=O.buildExtraConfigColumn(t);return[$,E]})),y=Object.assign(t,M);if(y[I.Symbol.Columns]=M,y[I.Symbol.ExtraConfigColumns]=F,T)y[io.Symbol.ExtraConfigBuilder]=T;return Object.assign(y,{enableRLS:()=>{return y[io.Symbol.EnableRLS]=!0,y}})}var MT=(o,n,T)=>{return A0(o,n,T,void 0)};function p$(...o){if(o[0].columns)return new IS(o[0].columns,o[0].name);return new IS(o)}class IS{static[R]="PgPrimaryKeyBuilder";columns;name;constructor(o,n){this.columns=o,this.name=n}build(o){return new Z$(o,this.columns,this.name)}}class Z${constructor(o,n,T){this.table=o,this.columns=n,this.name=T}static[R]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[io.Symbol.Name]}_${this.columns.map((o)=>o.name).join("_")}_pk`}}class MA{constructor(o,n,T){this.sourceTable=o,this.referencedTable=n,this.relationName=T,this.referencedTableName=n[I.Symbol.Name]}static[R]="Relation";referencedTableName;fieldName}class P${constructor(o,n){this.table=o,this.config=n}static[R]="Relations"}class FT extends MA{constructor(o,n,T,S){super(o,n,T?.relationName);this.config=T,this.isNullable=S}static[R]="One";withFieldName(o){let n=new FT(this.sourceTable,this.referencedTable,this.config,this.isNullable);return n.fieldName=o,n}}class jS extends MA{constructor(o,n,T){super(o,n,T?.relationName);this.config=T}static[R]="Many";withFieldName(o){let n=new jS(this.sourceTable,this.referencedTable,this.config);return n.fieldName=o,n}}function g$(){return{and:BS,between:cF,eq:Hf,exists:rF,gt:BF,gte:CF,ilike:pF,inArray:jF,isNull:hF,isNotNull:bF,like:qF,lt:LF,lte:IF,ne:DF,not:VF,notBetween:vF,notExists:xF,notLike:iF,notIlike:ZF,notInArray:NF,or:UF,sql:J}}function l$(){return{sql:J,asc:PF,desc:gF}}function e$(o,n){if(Object.keys(o).length===1&&"default"in o&&!K(o.default,I))o=o.default;let T={},S={},f={};for(let[t,A]of Object.entries(o))if(K(A,I)){let M=_T(A),F=S[M];T[M]=t,f[t]={tsName:t,dbName:A[I.Symbol.Name],schema:A[I.Symbol.Schema],columns:A[I.Symbol.Columns],relations:F?.relations??{},primaryKey:F?.primaryKey??[]};for(let $ of Object.values(A[I.Symbol.Columns]))if($.primary)f[t].primaryKey.push($);let y=A[I.Symbol.ExtraConfigBuilder]?.(A[I.Symbol.ExtraConfigColumns]);if(y){for(let $ of Object.values(y))if(K($,IS))f[t].primaryKey.push(...$.columns)}}else if(K(A,P$)){let M=_T(A.table),F=T[M],y=A.config(n(A.table)),$;for(let[W,O]of Object.entries(y))if(F){let E=f[F];if(E.relations[W]=O,$)E.primaryKey.push(...$)}else{if(!(M in S))S[M]={relations:{},primaryKey:$};S[M].relations[W]=O}}return{tables:f,tableNamesMap:T}}function M0(o){return function n(T,S){return new FT(o,T,S,S?.fields.reduce((f,t)=>f&&t.notNull,!0)??!1)}}function F0(o){return function n(T,S){return new jS(o,T,S)}}function d$(o,n,T){if(K(T,FT)&&T.config)return{fields:T.config.fields,references:T.config.references};let S=n[_T(T.referencedTable)];if(!S)throw new Error(`Table "${T.referencedTable[I.Symbol.Name]}" not found in schema`);let f=o[S];if(!f)throw new Error(`Table "${S}" not found in schema`);let t=T.sourceTable,A=n[_T(t)];if(!A)throw new Error(`Table "${t[I.Symbol.Name]}" not found in schema`);let M=[];for(let F of Object.values(f.relations))if(T.relationName&&T!==F&&F.relationName===T.relationName||!T.relationName&&F.referencedTable===T.sourceTable)M.push(F);if(M.length>1)throw T.relationName?new Error(`There are multiple relations with name "${T.relationName}" in table "${S}"`):new Error(`There are multiple relations between "${S}" and "${T.sourceTable[I.Symbol.Name]}". Please specify relation name`);if(M[0]&&K(M[0],FT)&&M[0].config)return{fields:M[0].config.references,references:M[0].config.fields};throw new Error(`There is not enough information to infer relation "${A}.${T.fieldName}"`)}function u$(o){return{one:M0(o),many:F0(o)}}function Nf(o,n,T,S,f=(t)=>t){let t={};for(let[A,M]of S.entries())if(M.isJson){let F=n.relations[M.tsKey],y=T[A],$=typeof y==="string"?JSON.parse(y):y;t[M.tsKey]=K(F,FT)?$&&Nf(o,o[M.relationTableTsKey],$,M.selection,f):$.map((W)=>Nf(o,o[M.relationTableTsKey],W,M.selection,f))}else{let F=f(T[A]),y=M.field,$;if(K(y,Jo))$=y;else if(K(y,N))$=y.decoder;else $=y.sql.decoder;t[M.tsKey]=F===null?null:$.mapFromDriverValue(F)}return t}import L0 from"os";import I0 from"fs";var hf=new Map,FA=new Map,yA=Symbol("OriginError"),eT={};class Xn extends Promise{constructor(o,n,T,S,f={}){let t,A;super((M,F)=>{t=M,A=F});this.tagged=Array.isArray(o.raw),this.strings=o,this.args=n,this.handler=T,this.canceller=S,this.options=f,this.state=null,this.statement=null,this.resolve=(M)=>(this.active=!1,t(M)),this.reject=(M)=>(this.active=!1,A(M)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[yA]=this.handler.debug?new Error:this.tagged&&y0(this.strings)}get origin(){return(this.handler.debug?this[yA].stack:this.tagged&&FA.has(this.strings)?FA.get(this.strings):FA.set(this.strings,this[yA].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 S=new Promise((f,t)=>{this.cursorFn=(A)=>{return f({value:A,done:!1}),new Promise((M)=>T=M)},this.resolve=()=>(this.active=!1,f({done:!0})),this.reject=(A)=>(this.active=!1,t(A))});return this.execute(),S},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 y0(o){if(hf.has(o))return hf.get(o);let n=Error.stackTraceLimit;return Error.stackTraceLimit=4,hf.set(o,new Error),Error.stackTraceLimit=n,hf.get(o)}class dT extends Error{constructor(o){super(o.message);this.name=this.constructor.name,Object.assign(this,o)}}var Io={connection:a$,postgres:s$,generic:ok,notSupported:nk};function a$(o,n,T){let{host:S,port:f}=T||n,t=Object.assign(new Error("write "+o+" "+(n.path||S+":"+f)),{code:o,errno:o,address:n.path||S},n.path?{}:{port:f});return Error.captureStackTrace(t,a$),t}function s$(o){let n=new dT(o);return Error.captureStackTrace(n,s$),n}function ok(o,n){let T=Object.assign(new Error(o+": "+n),{code:o});return Error.captureStackTrace(T,ok),T}function nk(o){let n=Object.assign(new Error(o+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:o});return Error.captureStackTrace(n,nk),n}var $0={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 xf{then(){$A()}catch(){$A()}finally(){$A()}}class rS extends xf{constructor(o){super();this.value=qf(o)}}class rn extends xf{constructor(o,n,T){super();this.value=o,this.type=n,this.array=T}}class cf extends xf{constructor(o,n){super();this.first=o,this.rest=n}build(o,n,T,S){let f=k0.map(([t,A])=>({fn:A,i:o.search(t)})).sort((t,A)=>t.i-A.i).pop();return f.i===-1?OA(this.first,S):f.fn(this.first,this.rest,n,T,S)}}function vf(o,n,T,S){let f=o instanceof rn?o.value:o;if(f===void 0){if(o instanceof rn?o.value=S.transform.undefined:f=o=S.transform.undefined,f===void 0)throw Io.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+T.push(o instanceof rn?(n.push(o.value),o.array?o.array[o.type||rf(o.value)]||o.type||tk(o.value):o.type):(n.push(o),rf(o)))}var Sk=Mk($0);function JA(o,n,T,S,f,t){for(let A=1;A<o.strings.length;A++)n+=WA(n,T,S,f,t)+o.strings[A],T=o.args[A];return n}function WA(o,n,T,S,f){return n instanceof cf?n.build(o,T,S,f):n instanceof Xn?RA(n,T,S,f):n instanceof rS?n.value:n&&n[0]instanceof Xn?n.reduce((t,A)=>t+" "+RA(A,T,S,f),""):vf(n,T,S,f)}function RA(o,n,T,S){return o.fragment=!0,JA(o,o.strings[0],o.args[0],n,T,S)}function fk(o,n,T,S,f){return o.map((t)=>"("+S.map((A)=>WA("values",t[A],n,T,f)).join(",")+")").join(",")}function Tk(o,n,T,S,f){let t=Array.isArray(o[0]),A=n.length?n.flat():Object.keys(t?o[0]:o);return fk(t?o:[o],T,S,A,f)}function bf(o,n,T,S,f){if(typeof o==="string"&&(o=[o].concat(n)),Array.isArray(o))return OA(o,f);let t;return(n.length?n.flat():Object.keys(o)).map((M)=>{return t=o[M],(t instanceof Xn?RA(t,T,S,f):t instanceof rS?t.value:vf(t,T,S,f))+" as "+qf(f.transform.column.to?f.transform.column.to(M):M)}).join(",")}var k0=Object.entries({values:Tk,in:(...o)=>{let n=Tk(...o);return n==="()"?"(null)":n},select:bf,as:bf,returning:bf,"\\(":bf,update(o,n,T,S,f){return(n.length?n.flat():Object.keys(o)).map((t)=>qf(f.transform.column.to?f.transform.column.to(t):t)+"="+WA("values",o[t],T,S,f))},insert(o,n,T,S,f){let t=n.length?n.flat():Object.keys(Array.isArray(o)?o[0]:o);return"("+OA(t,f)+")values"+fk(Array.isArray(o)?o:[o],T,S,t,f)}}).map(([o,n])=>[new RegExp("((?:^|[\\s(])"+o+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),n]);function $A(){throw Io.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:R0,parsers:J0}=Sk;function tk(o){if(Array.isArray(o))return tk(o[0]);return typeof o==="string"?1009:0}var Ak=function(o){let n=Mk(o||{});return{serializers:Object.assign({},R0,n.serializers),parsers:Object.assign({},J0,n.parsers)}};function Mk(o){return Object.keys(o).reduce((n,T)=>{if(o[T].from&&[].concat(o[T].from).forEach((S)=>n.parsers[S]=o[T].parse),o[T].serialize)n.serializers[o[T].to]=o[T].serialize,o[T].from&&[].concat(o[T].from).forEach((S)=>n.serializers[S]=o[T].serialize);return n},{parsers:{},serializers:{}})}function OA(o,{transform:{column:n}}){return o.map((T)=>qf(n.to?n.to(T):T)).join(",")}var qf=function o(n){return'"'+n.replace(/"/g,'""').replace(/\./g,'"."')+'"'},rf=function o(n){return n instanceof rn?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},W0=/\\/g,O0=/"/g;function _0(o){return o.replace(W0,"\\\\").replace(O0,"\\\"")}var Fk=function o(n,T,S,f){if(Array.isArray(n)===!1)return n;if(!n.length)return"{}";let t=n[0],A=f===1020?";":",";if(Array.isArray(t)&&!t.type)return"{"+n.map((M)=>o(M,T,S,f)).join(A)+"}";return"{"+n.map((M)=>{if(M===void 0){if(M=S.transform.undefined,M===void 0)throw Io.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return M===null?"null":'"'+_0(T?T(M.type?M.value:M):""+M)+'"'}).join(A)+"}"},kA={i:0,char:null,str:"",quoted:!1,last:0},yk=function o(n,T,S){return kA.i=kA.last=0,$k(kA,n,T,S)};function $k(o,n,T,S){let f=[],t=S===1020?";":",";for(;o.i<n.length;o.i++){if(o.char=n[o.i],o.quoted)if(o.char==="\\")o.str+=n[++o.i];else if(o.char==='"')f.push(T?T(o.str):o.str),o.str="",o.quoted=n[o.i+1]==='"',o.last=o.i+2;else o.str+=o.char;else if(o.char==='"')o.quoted=!0;else if(o.char==="{")o.last=++o.i,f.push($k(o,n,T,S));else if(o.char==="}"){o.quoted=!1,o.last<o.i&&f.push(T?T(n.slice(o.last,o.i)):n.slice(o.last,o.i)),o.last=o.i+1;break}else if(o.char===t&&o.p!=="}"&&o.p!=='"')f.push(T?T(n.slice(o.last,o.i)):n.slice(o.last,o.i)),o.last=o.i+1;o.p=o.char}return o.last<o.i&&f.push(T?T(n.slice(o.last,o.i+1)):n.slice(o.last,o.i+1)),f}var wT=(o)=>{let n=o[0];for(let T=1;T<o.length;T++)n+=o[T]==="_"?o[++T].toUpperCase():o[T];return n},KT=(o)=>{let n=o[0].toUpperCase();for(let T=1;T<o.length;T++)n+=o[T]==="_"?o[++T].toUpperCase():o[T];return n},XT=(o)=>o.replace(/_/g,"-"),NS=(o)=>o.replace(/([A-Z])/g,"_$1").toLowerCase(),hS=(o)=>(o.slice(0,1)+o.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),bS=(o)=>o.replace(/-/g,"_");function _A(o){return function n(T,S){return typeof T==="object"&&T!==null&&(S.type===114||S.type===3802)?Array.isArray(T)?T.map((f)=>n(f,S)):Object.entries(T).reduce((f,[t,A])=>Object.assign(f,{[o(t)]:n(A,S)}),{}):T}}wT.column={from:wT};wT.value={from:_A(wT)};NS.column={to:NS};var wA={...wT};wA.column.to=NS;KT.column={from:KT};KT.value={from:_A(KT)};hS.column={to:hS};var KA={...KT};KA.column.to=hS;XT.column={from:XT};XT.value={from:_A(XT)};bS.column={to:bS};var XA={...XT};XA.column.to=bS;import kk from"net";import Y0 from"tls";import xS from"crypto";import YA from"stream";import{performance as Rk}from"perf_hooks";class YT 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 Wn=w0;function w0(o=[]){let n=o.slice(),T=0;return{get length(){return n.length-T},remove:(S)=>{let f=n.indexOf(S);return f===-1?null:(n.splice(f,1),S)},push:(S)=>(n.push(S),S),shift:()=>{let S=n[T++];if(T===n.length)T=0,n=[];else n[T-1]=void 0;return S}}}var ao=Buffer.allocUnsafe(256),K0="BCcDdEFfHPpQSX".split("").reduce((o,n)=>{let T=n.charCodeAt(0);return o[n]=()=>{return ao[0]=T,Ro.i=5,Ro},o},{}),Ro=Object.assign(X0,K0,{N:String.fromCharCode(0),i:0,inc(o){return Ro.i+=o,Ro},str(o){let n=Buffer.byteLength(o);return pf(n),Ro.i+=ao.write(o,Ro.i,n,"utf8"),Ro},i16(o){return pf(2),ao.writeUInt16BE(o,Ro.i),Ro.i+=2,Ro},i32(o,n){if(n||n===0)return ao.writeUInt32BE(o,n),Ro;return pf(4),ao.writeUInt32BE(o,Ro.i),Ro.i+=4,Ro},z(o){return pf(o),ao.fill(0,Ro.i,Ro.i+o),Ro.i+=o,Ro},raw(o){return ao=Buffer.concat([ao.subarray(0,Ro.i),o]),Ro.i=ao.length,Ro},end(o=1){ao.writeUInt32BE(Ro.i-o,o);let n=ao.subarray(0,Ro.i);return Ro.i=0,ao=Buffer.allocUnsafe(256),n}}),P=Ro;function pf(o){if(ao.length-Ro.i<o){let n=ao,T=n.length;ao=Buffer.allocUnsafe(T+(T>>1)+o),n.copy(ao)}}function X0(){return Ro.i=0,Ro}var HA=Ok,G0=1,yT=P().S().end(),Jk=P().H().end(),E0=P().i32(8).i32(80877103).end(8),H0=Buffer.concat([P().E().str(P.N).i32(0).end(),yT]),z0=P().D().str("S").str(P.N).end(),uT=()=>{},m0=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),Q0={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 Ok(o,n={},{onopen:T=uT,onend:S=uT,onclose:f=uT}={}){let{ssl:t,max:A,user:M,host:F,port:y,database:$,parsers:W,transform:O,onnotice:E,onnotify:Q,onparameter:H,max_pipeline:Y,keep_alive:B,backoff:j,target_session_attrs:b}=o,a=Wn(),X=G0++,G={pid:null,secret:null},U=EA(St,o.idle_timeout),v=EA(St,o.max_lifetime),c=EA(bk,o.connect_timeout),w=null,q,r=new YT,p=Buffer.alloc(0),ko=o.fetch_types,Oo={},fn={},xn=Math.random().toString(36).slice(2),z=1,Z=0,yo=0,Ho=0,jo=0,To=0,_o=0,Lo=0,mo=null,Xo=null,po=!1,wo=null,Yn=null,Zo=null,dn=null,No=null,Yo=null,Gn=null,Ln=null,C=null,nS=null,Po={queue:n.closed,idleTimer:U,connect(k){Zo=k||!0,dA()},terminate:SS,execute:TS,cancel:Ik,end:St,count:0,id:X};return n.closed&&n.closed.push(Po),Po;async function Lk(){let k;try{k=o.socket?await Promise.resolve(o.socket(o)):new kk.Socket}catch(_){zT(_);return}return k.on("error",zT),k.on("close",uA),k.on("drain",lA),k}async function Ik({pid:k,secret:_},g,$o){try{q=P().i32(16).i32(80877102).i32(k).i32(_).end(16),await eA(),w.once("error",$o),w.once("close",g)}catch(Uo){$o(Uo)}}function TS(k){if(po)return PS(k,Io.connection("CONNECTION_DESTROYED",o));if(k.cancelled)return;try{return k.state=G,C?a.push(k):(C=k,C.active=!0),hk(k),vo(jk(k))&&!k.describeFirst&&!k.cursorFn&&a.length<Y&&(!k.options.onexecute||k.options.onexecute(Po))}catch(_){return a.length===0&&vo(yT),In(_),!0}}function jk(k){if(k.parameters.length>=65534)throw Io.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([ZA(k),Jk]):k.prepare?k.prepared?ZS(k):Buffer.concat([ZA(k),ZS(k)]):Nk(k)}function ZA(k){return Buffer.concat([sA(k.statement.string,k.parameters,k.statement.types,k.statement.name),GR("S",k.statement.name)])}function ZS(k){return Buffer.concat([YR(k.parameters,k.statement.types,k.statement.name,k.cursorName),k.cursorFn?oM("",k.cursorRows):H0])}function Nk(k){return Buffer.concat([sA(k.statement.string,k.parameters,k.statement.types),z0,ZS(k)])}function hk(k){let _=[],g=[],$o=JA(k,k.strings[0],k.args[0],_,g,o);!k.tagged&&k.args.forEach((Uo)=>vf(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 fn[k.signature],k.parameters=k.parameters||_,k.prepared=k.prepare&&k.signature in fn,k.describeFirst=k.onlyDescribe||_.length&&!k.prepared,k.statement=k.prepared?fn[k.signature]:{string:$o,types:g,name:k.prepare?xn+z++:""},typeof o.debug==="function"&&o.debug(X,$o,_,g)}function vo(k,_){if(Yo=Yo?Buffer.concat([Yo,k]):Buffer.from(k),_||Yo.length>=1024)return PA(_);return Xo===null&&(Xo=setImmediate(PA)),!0}function PA(k){let _=w.write(Yo,k);return Xo!==null&&clearImmediate(Xo),Yo=Xo=null,_}function bk(){In(Io.connection("CONNECT_TIMEOUT",o,w)),w.destroy()}async function gA(){if(vo(E0),!await new Promise((_)=>w.once("data",(g)=>_(g[0]===83)))&&t==="prefer")return HT();w.removeAllListeners(),w=Y0.connect({socket:w,servername:kk.isIP(w.host)?void 0:w.host,...t==="require"||t==="allow"||t==="prefer"?{rejectUnauthorized:!1}:t==="verify-full"?{}:typeof t==="object"?t:{}}),w.on("secureConnect",HT),w.on("error",zT),w.on("close",uA),w.on("drain",lA)}function lA(){!C&&T(Po)}function Tt(k){if(wo){if(wo.push(k),yo-=k.length,yo>=0)return}p=wo?Buffer.concat(wo,To-yo):p.length===0?k:Buffer.concat([p,k],p.length+k.length);while(p.length>4){if(To=p.readUInt32BE(1),To>=p.length){yo=To-p.length,wo=[p];break}try{rk(p.subarray(0,To+1))}catch(_){C&&(C.cursorFn||C.describeFirst)&&vo(yT),In(_)}p=p.subarray(To+1),yo=0,wo=null}}async function eA(){if(po=!1,Oo={},w||(w=await Lk()),!w)return;if(c.start(),o.socket)return t?gA():HT();if(w.on("connect",t?gA:HT),o.path)return w.connect(o.path);w.ssl=t,w.connect(y[Ho],F[Ho]),w.host=F[Ho],w.port=y[Ho],Ho=(Ho+1)%y.length}function dA(){setTimeout(eA,Z?Z+_o-Rk.now():0)}function HT(){try{fn={},ko=o.fetch_types,xn=Math.random().toString(36).slice(2),z=1,v.start(),w.on("data",Tt),B&&w.setKeepAlive&&w.setKeepAlive(!0,1000*B);let k=HR();vo(k)}catch(k){zT(k)}}function zT(k){if(Po.queue===n.connecting&&o.host[jo+1])return;In(k);while(a.length)PS(a.shift(),k)}function In(k){No&&(No.destroy(k),No=null),C&&PS(C,k),Zo&&(PS(Zo,k),Zo=null)}function PS(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 St(){return dn||(!Po.reserved&&S(Po),!Po.reserved&&!Zo&&!C&&a.length===0?(SS(),new Promise((k)=>w&&w.readyState!=="closed"?w.once("close",k):k())):dn=new Promise((k)=>Gn=k))}function SS(){if(po=!0,No||C||Zo||a.length)zT(Io.connection("CONNECTION_DESTROYED",o));if(clearImmediate(Xo),w)w.removeListener("data",Tt),w.removeListener("connect",HT),w.readyState==="open"&&w.end(P().X().end());Gn&&(Gn(),dn=Gn=null)}async function uA(k){if(p=Buffer.alloc(0),yo=0,wo=null,clearImmediate(Xo),w.removeListener("data",Tt),w.removeListener("connect",HT),U.cancel(),v.cancel(),c.cancel(),w.removeAllListeners(),w=null,Zo)return dA();!k&&(C||a.length)&&zT(Io.connection("CONNECTION_CLOSED",o,w)),Z=Rk.now(),k&&o.shared.retries++,_o=(typeof j==="function"?j(o.shared.retries):j)*1000,f(Po,Io.connection("CONNECTION_CLOSED",o,w))}function rk(k,_=k[0]){(_===68?xk:_===100?RR:_===65?AR:_===83?ck:_===90?vk:_===67?qk:_===50?aA:_===49?ik:_===116?pk:_===84?Zk:_===82?Pk:_===110?ak:_===75?sk:_===69?fR:_===115?MR:_===51?FR:_===71?yR:_===78?WR:_===72?$R:_===99?JR:_===73?OR:_===86?_R:_===118?wR:_===87?kR:KR)(k)}function xk(k){let _=7,g,$o,Uo,go=C.isRaw?new Array(C.statement.columns.length):{};for(let so=0;so<C.statement.columns.length;so++)$o=C.statement.columns[so],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?go[so]=C.isRaw===!0?Uo:O.value.from?O.value.from(Uo,$o):Uo:go[$o.name]=O.value.from?O.value.from(Uo,$o):Uo;C.forEachFn?C.forEachFn(O.row.from?O.row.from(go):go,r):r[Lo++]=O.row.from?O.row.from(go):go}function ck(k){let[_,g]=k.toString("utf8",5,k.length-1).split(P.N);if(Oo[_]=g,o.parameters[_]!==g)o.parameters[_]=g,H&&H(_,g)}function vk(k){if(C&&C.options.simple&&C.resolve(Yn||r),C=Yn=null,r=new YT,c.cancel(),Zo){if(b){if(!Oo.in_hot_standby||!Oo.default_transaction_read_only)return SR();else if(TR(b,Oo))return SS()}if(ko)return Zo===!0&&(Zo=null),oR();Zo!==!0&&TS(Zo),o.shared.retries=jo=0,Zo=null;return}while(a.length&&(C=a.shift())&&(C.active=!0,C.cancelled))Ok(o).cancel(C.state,C.cancelled.resolve,C.cancelled.reject);if(C)return;Po.reserved?!Po.reserved.release&&k[5]===73?dn?SS():(Po.reserved=null,T(Po)):Po.reserved():dn?SS():T(Po)}function qk(k){Lo=0;for(let _=k.length-1;_>0;_--){if(k[_]===32&&k[_+1]<58&&r.count===null)r.count=+k.toString("utf8",_+1,k.length-1);if(k[_-1]>=65){r.command=k.toString("utf8",5,_),r.state=G;break}}if(nS&&(nS(),nS=null),r.command==="BEGIN"&&A!==1&&!Po.reserved)return In(Io.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(C.options.simple)return aA();if(C.cursorFn)r.count&&C.cursorFn(r),vo(yT);C.resolve(r)}function ik(){C.parsing=!1}function aA(){!r.statement&&(r.statement=C.statement),r.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&&(fn[C.signature]=C.statement),C.describeFirst&&!C.onlyDescribe&&(vo(ZS(C)),C.describeFirst=!1)}function Zk(k){if(r.command)Yn=Yn||[r],Yn.push(r=new YT),r.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 go=k.readUInt32BE(g),so=k.readUInt16BE(g+4),un=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[un],table:go,number:so,type:un},g+=18}if(r.statement=C.statement,C.onlyDescribe)return C.resolve(C.statement),vo(yT)}async function Pk(k,_=k.readUInt32BE(5)){(_===3?gk:_===5?lk:_===10?ek:_===11?dk:_===12?uk:_!==0?XR:uT)(k,_)}async function gk(){let k=await ft();vo(P().p().str(k).z(1).end())}async function lk(k){let _="md5"+await Wk(Buffer.concat([Buffer.from(await Wk(await ft()+M)),k.subarray(9)]));vo(P().p().str(_).z(1).end())}async function ek(){Ln=(await xS.randomBytes(18)).toString("base64"),P().p().str("SCRAM-SHA-256"+P.N);let k=P.i;vo(P.inc(4).str("n,,n=*,r="+Ln).i32(P.i-k-4,k).end())}async function dk(k){let _=k.toString("utf8",9).split(",").reduce((so,un)=>(so[un[0]]=un.slice(2),so),{}),g=await xS.pbkdf2Sync(await ft(),Buffer.from(_.s,"base64"),parseInt(_.i),32,"sha256"),$o=await Zf(g,"Client Key"),Uo="n=*,r="+Ln+",r="+_.r+",s="+_.s+",i="+_.i+",c=biws,r="+_.r;mo=(await Zf(await Zf(g,"Server Key"),Uo)).toString("base64");let go="c=biws,r="+_.r+",p="+U0($o,Buffer.from(await Zf(await D0($o),Uo))).toString("base64");vo(P().p().str(go).end())}function uk(k){if(k.toString("utf8",9).split(P.N,1)[0].slice(2)===mo)return;In(Io.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),w.destroy()}function ft(){return Promise.resolve(typeof o.pass==="function"?o.pass():o.pass)}function ak(){if(r.statement=C.statement,r.statement.columns=[],C.onlyDescribe)return C.resolve(C.statement),vo(yT)}function sk(k){G.pid=k.readUInt32BE(5),G.secret=k.readUInt32BE(9)}async function oR(){ko=!1,(await new Xn([`
11
11
  select b.oid, b.typarray
12
12
  from pg_catalog.pg_type a
13
13
  left join pg_catalog.pg_type b on b.oid = a.typelem
14
14
  where a.typcategory = 'A'
15
15
  group by b.oid, b.typarray
16
16
  order by b.oid
17
- `],[],Tt)).forEach(({oid:_,typarray:g})=>Tk(_,g))}function Tk(J,_){if(!!o.parsers[_]&&!!o.serializers[_])return;let g=o.parsers[J];o.shared.typeArrayMap[J]=_,o.parsers[_]=($o)=>$J($o,g,_),o.parsers[_].array=!0,o.serializers[_]=($o)=>FJ($o,o.serializers[J],o,_)}function tk(J,_){return J==="read-write"&&_.default_transaction_read_only==="on"||J==="read-only"&&_.default_transaction_read_only==="off"||J==="primary"&&_.in_hot_standby==="on"||J==="standby"&&_.in_hot_standby==="off"||J==="prefer-standby"&&_.in_hot_standby==="off"&&o.host[Io]}function Sk(){let J=new Xn([`
17
+ `],[],TS)).forEach(({oid:_,typarray:g})=>nR(_,g))}function nR(k,_){if(!!o.parsers[_]&&!!o.serializers[_])return;let g=o.parsers[k];o.shared.typeArrayMap[k]=_,o.parsers[_]=($o)=>yk($o,g,_),o.parsers[_].array=!0,o.serializers[_]=($o)=>Fk($o,o.serializers[k],o,_)}function TR(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[jo]}function SR(){let k=new Xn([`
18
18
  show transaction_read_only;
19
19
  select pg_catalog.pg_is_in_recovery()
20
- `],[],Tt,null,{simple:!0});J.resolve=([[_],[g]])=>{Oo.default_transaction_read_only=_.transaction_read_only,Oo.in_hot_standby=g.pg_is_in_recovery?"on":"off"},J.execute()}function fk(J){C&&(C.cursorFn||C.describeFirst)&&xo(FT);let _=Lo.postgres(Gy(J));C&&C.retried?In(C.retried):C&&C.prepared&&H0.has(_.routine)?yk(C,_):In(_)}function yk(J,_){delete tn[J.signature],J.retried=_,Tt(J)}function Ak(J){if(!D)return;let _=9;while(J[_++]!==0);D(J.toString("utf8",9,_-1),J.toString("utf8",_,J.length-1))}async function Mk(){try{let J=await Promise.resolve(C.cursorFn(N));Co=0,J===eT?xo(zk(C.portal)):(N=new ET,xo(nA("",C.cursorRows)))}catch(J){xo(FT),C.reject(J)}}function Fk(){N.count&&C.cursorFn(N),C.resolve(N)}function $k(){jo=new Yy.Writable({autoDestroy:!0,write(J,_,g){w.write(P().d().raw(J).end(),g)},destroy(J,_){_(J),w.write(P().f().str(J+P.N).end()),jo=null},final(J){w.write(P().c().end()),nt=J}}),C.resolve(jo)}function Jk(){jo=new Yy.Readable({read(){w.resume()}}),C.resolve(jo)}function kk(){jo=new Yy.Duplex({autoDestroy:!0,read(){w.resume()},write(J,_,g){w.write(P().d().raw(J).end(),g)},destroy(J,_){_(J),w.write(P().f().str(J+P.N).end()),jo=null},final(J){w.write(P().c().end()),nt=J}}),C.resolve(jo)}function Rk(J){jo&&(jo.push(J.subarray(5))||w.pause())}function Wk(){jo&&jo.push(null),jo=null}function Ok(J){G?G(Gy(J)):console.log(Gy(J))}function _k(){}function wk(){In(Lo.notSupported("FunctionCallResponse"))}function Kk(){In(Lo.notSupported("NegotiateProtocolVersion"))}function Xk(J){console.error("Postgres.js : Unknown Message:",J[0])}function Ek(J,_){console.error("Postgres.js : Unknown Auth:",_)}function Yk(J,_,g="",$o=""){let Uo,Po;return P().B().str($o+P.N).str(g+P.N).i16(0).i16(J.length),J.forEach((ao,un)=>{if(ao===null)return P.i32(4294967295);Po=_[un],J[un]=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 oA(J,_,g,$o=""){return P().P().str($o+P.N).str(J+P.N).i16(_.length),_.forEach((Uo,Po)=>P.i32(g[Po]||0)),P.end()}function Gk(J,_=""){return P().D().str(J).str(_+P.N).end()}function nA(J="",_=0){return Buffer.concat([P().E().str(J+P.N).i32(_).end(),WJ])}function zk(J=""){return Buffer.concat([P().C().str("P").str(J+P.N).end(),P().S().end()])}function Hk(){return v||P().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:A,database:$,client_encoding:"UTF8"},o.connection)).filter(([,J])=>J).map(([J,_])=>J+P.N+_).join(P.N)).z(2).end(0)}}function Gy(o){let n={},T=5;for(let t=5;t<o.length-1;t++)if(o[t]===0)n[m0[o[T]]]=o.toString("utf8",T+1,t),T=t+1;return n}function OJ(o){return xt.createHash("md5").update(o).digest("hex")}function ZS(o,n){return xt.createHmac("sha256",o).update(n).digest()}function Q0(o){return xt.createHash("sha256").update(o).digest()}function D0(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 zy(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 wJ=()=>{};function my(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=wJ,p=wJ){if(z=B0(z),!f)f=G(M,t,n.publications);let c={fn:Y,onsubscribe:B},a=T.has(z)?T.get(z).add(c):T.set(z,new Set([c])).get(z),E=()=>{a.delete(c),a.size===0&&T.delete(z)};return f.then((K)=>{return O(K),B(),y&&y.on("error",p),{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 p=await z.unsafe(`CREATE_REPLICATION_SLOT ${Y} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[c]=p,a=await z.unsafe(`START_REPLICATION SLOT ${Y} LOGICAL ${c.consistent_point} (proto_version '1', publication_names '${B}')`).writable(),E={lsn:Buffer.concat(c.consistent_point.split("/").map((w)=>Buffer.from(("00000000"+w).slice(-8),"hex")))};return a.on("data",Q),a.on("error",K),a.on("close",z.close),{stream:a,state:p.state};function K(w){console.error("Unexpected error during logical streaming - reconnecting",w)}function Q(w){if(w[0]===119)V0(w.subarray(25),E,z.options.parsers,x,n.transform);else if(w[0]===107&&w[17])E.lsn=w.subarray(1,9),h()}function x(w,v){let N=v.relation.schema+"."+v.relation.table;D("*",w,v),D("*:"+N,w,v),v.relation.keys.length&&D("*:"+N+"="+v.relation.keys.map((q)=>w[q.name]),w,v),D(v.command,w,v),D(v.command+":"+N,w,v),v.relation.keys.length&&D(v.command+":"+N+"="+v.relation.keys.map((q)=>w[q.name]),w,v)}function h(){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:p})=>p(Y,B,z))}}function U0(o){return new Date(Date.UTC(2000,0,1)+Number(o/BigInt(1000)))}function V0(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=U0(y.readBigInt64BE(9)),n.lsn=y.subarray(1,9)},I:(y)=>{let A=1,M=n[y.readUInt32BE(A)],{row:F}=PS(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?PS(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?PS(y,M.columns,A+=3,S):null;$&&(A=$.i);let{row:W}=PS(y,M.columns,A+3,S);t(W,{command:"update",relation:M,key:F,old:$&&$.row})},T:()=>{},C:()=>{}}).reduce(f,{})[o[0]](o)}function PS(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 B0(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 KJ from"stream";function Qy(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`
20
+ `],[],TS,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 fR(k){C&&(C.cursorFn||C.describeFirst)&&vo(yT);let _=Io.postgres(GA(k));C&&C.retried?In(C.retried):C&&C.prepared&&m0.has(_.routine)?tR(C,_):In(_)}function tR(k,_){delete fn[k.signature],k.retried=_,TS(k)}function AR(k){if(!Q)return;let _=9;while(k[_++]!==0);Q(k.toString("utf8",9,_-1),k.toString("utf8",_,k.length-1))}async function MR(){try{let k=await Promise.resolve(C.cursorFn(r));Lo=0,k===eT?vo(ER(C.portal)):(r=new YT,vo(oM("",C.cursorRows)))}catch(k){vo(yT),C.reject(k)}}function FR(){r.count&&C.cursorFn(r),C.resolve(r)}function yR(){No=new YA.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()),No=null},final(k){w.write(P().c().end()),nS=k}}),C.resolve(No)}function $R(){No=new YA.Readable({read(){w.resume()}}),C.resolve(No)}function kR(){No=new YA.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()),No=null},final(k){w.write(P().c().end()),nS=k}}),C.resolve(No)}function RR(k){No&&(No.push(k.subarray(5))||w.pause())}function JR(){No&&No.push(null),No=null}function WR(k){E?E(GA(k)):console.log(GA(k))}function OR(){}function _R(){In(Io.notSupported("FunctionCallResponse"))}function wR(){In(Io.notSupported("NegotiateProtocolVersion"))}function KR(k){console.error("Postgres.js : Unknown Message:",k[0])}function XR(k,_){console.error("Postgres.js : Unknown Auth:",_)}function YR(k,_,g="",$o=""){let Uo,go;return P().B().str($o+P.N).str(g+P.N).i16(0).i16(k.length),k.forEach((so,un)=>{if(so===null)return P.i32(4294967295);go=_[un],k[un]=so=go in o.serializers?o.serializers[go](so):""+so,Uo=P.i,P.inc(4).str(so).i32(P.i-Uo-4,Uo)}),P.i16(0),P.end()}function sA(k,_,g,$o=""){return P().P().str($o+P.N).str(k+P.N).i16(_.length),_.forEach((Uo,go)=>P.i32(g[go]||0)),P.end()}function GR(k,_=""){return P().D().str(k).str(_+P.N).end()}function oM(k="",_=0){return Buffer.concat([P().E().str(k+P.N).i32(_).end(),Jk])}function ER(k=""){return Buffer.concat([P().C().str("P").str(k+P.N).end(),P().S().end()])}function HR(){return q||P().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:M,database:$,client_encoding:"UTF8"},o.connection)).filter(([,k])=>k).map(([k,_])=>k+P.N+_).join(P.N)).z(2).end(0)}}function GA(o){let n={},T=5;for(let S=5;S<o.length-1;S++)if(o[S]===0)n[Q0[o[T]]]=o.toString("utf8",T+1,S),T=S+1;return n}function Wk(o){return xS.createHash("md5").update(o).digest("hex")}function Zf(o,n){return xS.createHmac("sha256",o).update(n).digest()}function D0(o){return xS.createHash("sha256").update(o).digest()}function U0(o,n){let T=Math.max(o.length,n.length),S=Buffer.allocUnsafe(T);for(let f=0;f<T;f++)S[f]=o[f]^n[f];return S}function EA(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(S,n*1000,arguments)}};function S(f){o.apply(null,f),T=null}}var _k=()=>{};function zA(o,n){let T=new Map,S="postgresjs_"+Math.random().toString(36).slice(2),f={},t,A,M=!1,F=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(M)return;A=null,f.pid=f.secret=void 0,O(await E(F,S,n.publications)),T.forEach((H)=>H.forEach(({onsubscribe:Y})=>Y()))},no_subscribe:!0}),y=F.end,$=F.close;return F.end=async()=>{return M=!0,A&&await new Promise((H)=>(A.once("close",H),A.end())),y()},F.close=async()=>{return A&&await new Promise((H)=>(A.once("close",H),A.end())),$()},W;async function W(H,Y,B=_k,j=_k){if(H=C0(H),!t)t=E(F,S,n.publications);let b={fn:Y,onsubscribe:B},a=T.has(H)?T.get(H).add(b):T.set(H,new Set([b])).get(H),X=()=>{a.delete(b),a.size===0&&T.delete(H)};return t.then((G)=>{return O(G),B(),A&&A.on("error",j),{unsubscribe:X,state:f,sql:F}})}function O(H){A=H.stream,f.pid=H.state.pid,f.secret=H.state.secret}async function E(H,Y,B){if(!B)throw new Error("Missing publication names");let j=await H.unsafe(`CREATE_REPLICATION_SLOT ${Y} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[b]=j,a=await H.unsafe(`START_REPLICATION SLOT ${Y} LOGICAL ${b.consistent_point} (proto_version '1', publication_names '${B}')`).writable(),X={lsn:Buffer.concat(b.consistent_point.split("/").map((w)=>Buffer.from(("00000000"+w).slice(-8),"hex")))};return a.on("data",U),a.on("error",G),a.on("close",H.close),{stream:a,state:j.state};function G(w){console.error("Unexpected error during logical streaming - reconnecting",w)}function U(w){if(w[0]===119)B0(w.subarray(25),X,H.options.parsers,v,n.transform);else if(w[0]===107&&w[17])X.lsn=w.subarray(1,9),c()}function v(w,q){let r=q.relation.schema+"."+q.relation.table;Q("*",w,q),Q("*:"+r,w,q),q.relation.keys.length&&Q("*:"+r+"="+q.relation.keys.map((p)=>w[p.name]),w,q),Q(q.command,w,q),Q(q.command+":"+r,w,q),q.relation.keys.length&&Q(q.command+":"+r+"="+q.relation.keys.map((p)=>w[p.name]),w,q)}function c(){let w=Buffer.alloc(34);w[0]=114,w.fill(X.lsn,1),w.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),a.write(w)}}function Q(H,Y,B){T.has(H)&&T.get(H).forEach(({fn:j})=>j(Y,B,H))}}function V0(o){return new Date(Date.UTC(2000,0,1)+Number(o/BigInt(1000)))}function B0(o,n,T,S,f){let t=(A,[M,F])=>(A[M.charCodeAt(0)]=F,A);Object.entries({R:(A)=>{let M=1,F=n[A.readUInt32BE(M)]={schema:A.toString("utf8",M+=4,M=A.indexOf(0,M))||"pg_catalog",table:A.toString("utf8",M+1,M=A.indexOf(0,M+1)),columns:Array(A.readUInt16BE(M+=2)),keys:[]};M+=2;let y=0,$;while(M<A.length)$=F.columns[y++]={key:A[M++],name:f.column.from?f.column.from(A.toString("utf8",M,M=A.indexOf(0,M))):A.toString("utf8",M,M=A.indexOf(0,M)),type:A.readUInt32BE(M+=1),parser:T[A.readUInt32BE(M)],atttypmod:A.readUInt32BE(M+=4)},$.key&&F.keys.push($),M+=4},Y:()=>{},O:()=>{},B:(A)=>{n.date=V0(A.readBigInt64BE(9)),n.lsn=A.subarray(1,9)},I:(A)=>{let M=1,F=n[A.readUInt32BE(M)],{row:y}=Pf(A,F.columns,M+=7,f);S(y,{command:"insert",relation:F})},D:(A)=>{let M=1,F=n[A.readUInt32BE(M)];M+=4;let y=A[M]===75;S(y||A[M]===79?Pf(A,F.columns,M+=3,f).row:null,{command:"delete",relation:F,key:y})},U:(A)=>{let M=1,F=n[A.readUInt32BE(M)];M+=4;let y=A[M]===75,$=y||A[M]===79?Pf(A,F.columns,M+=3,f):null;$&&(M=$.i);let{row:W}=Pf(A,F.columns,M+3,f);S(W,{command:"update",relation:F,key:y,old:$&&$.row})},T:()=>{},C:()=>{}}).reduce(t,{})[o[0]](o)}function Pf(o,n,T,S){let f,t,A,M=S.raw?new Array(n.length):{};for(let F=0;F<n.length;F++)f=o[T++],t=n[F],A=f===110?null:f===117?void 0:t.parser===void 0?o.toString("utf8",T+4,T+=4+o.readUInt32BE(T)):t.parser.array===!0?t.parser(o.toString("utf8",T+5,T+=4+o.readUInt32BE(T))):t.parser(o.toString("utf8",T+4,T+=4+o.readUInt32BE(T))),S.raw?M[F]=S.raw===!0?A:S.value.from?S.value.from(A,t):A:M[t.name]=S.value.from?S.value.from(A,t):A;return{i:T,row:S.row.from?S.row.from(M):M}}function C0(o){let n=o.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!n)throw new Error("Malformed subscribe pattern: "+o);let[,T,S,f]=n;return(T||"*")+(S?":"+(S.indexOf(".")===-1?"public."+S:S):"")+(f?"="+f:"")}import wk from"stream";function mA(o,n,T=393216){return new Promise(async(S,f)=>{await o.begin(async(t)=>{let A;!n&&([{oid:n}]=await t`select lo_creat(-1) as oid`);let[{fd:M}]=await t`select lo_open(${n}, ${T}) as fd`,F={writable:$,readable:y,close:()=>t`select lo_close(${M})`.then(A),tell:()=>t`select lo_tell64(${M})`,read:(W)=>t`select loread(${M}, ${W}) as data`,write:(W)=>t`select lowrite(${M}, ${W})`,truncate:(W)=>t`select lo_truncate64(${M}, ${W})`,seek:(W,O=0)=>t`select lo_lseek64(${M}, ${W}, ${O})`,size:()=>t`
21
21
  select
22
- lo_lseek64(${A}, location, 0) as position,
22
+ lo_lseek64(${M}, location, 0) as position,
23
23
  seek.size
24
24
  from (
25
25
  select
@@ -27,10 +27,10 @@ ${y.trace}`:"No previous disposal trace was found.");return}switch(T.type){case"
27
27
  tell.location
28
28
  from (select lo_tell64($1) as location) tell
29
29
  ) seek
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 KJ.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 KJ.Writable({highWaterMark:W,write(G,D,z){M.write(G).then(()=>z(),z)}})}}).catch(S)})}Object.assign(gS,{PostgresError:dT,toPascal:KT,pascal:Xy,toCamel:wT,camel:Ky,toKebab:XT,kebab:Ey,fromPascal:Nt,fromCamel:rt,fromKebab:bt,BigInt:{to:20,from:[20],parse:(o)=>BigInt(o),serialize:(o)=>o.toString()}});var aT=gS;function gS(o,n){let T=I0(o,n),t=T.no_subscribe||my(gS,{...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(()=>Hy(T,G,{onopen:tn,onend:Oo,onclose:xn})),z=Y(x);return Object.assign(z,{get parameters(){return T.parameters},largeObject:Qy.bind(null,z),subscribe:t,CLOSE:eT,END:eT,PostgresError:dT,options:T,reserve:c,listen:B,begin:a,close:N,end:v}),z;function Y(H){return H.debug=T.debug,Object.entries(T.types).reduce((To,[_o,Co])=>{return To[_o]=(mo)=>new hn(mo,Co.to),To},Z),Object.assign(Fo,{types:Z,typed:Z,unsafe:zo,notify:p,array:Q,json:K,file:Io}),Fo;function Z(To,_o){return new hn(To,_o)}function Fo(To,..._o){return To&&Array.isArray(To.raw)?new Xn(To,_o,H,w):typeof To==="string"&&!_o.length?new ht(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)=>{L0.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=gS({...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 p(H,Z){return await z`select pg_notify(${H}, ${""+Z})`}async function c(){let H=Rn(),Z=$.length?$.shift():await new Promise((Io)=>{f.push({reserve:Io}),M.length&&Jo(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,tn(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(jo);wo.savepoint=dn,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 dn(Xo,Yn){if(Xo&&Array.isArray(Xo.raw))return dn((Ln)=>Ln.apply(Ln,arguments));return arguments.length===1&&(Yn=Xo,Xo=null),_o(mo,Yn,"s"+zo+++(Xo?"_"+Xo:""))}function jo(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 hn(H,3802)}function Q(H,Z){if(!Array.isArray(H))return Q(Array.from(arguments));return new hn(H,Z||(H.length?xS(H)||25:0),T.shared.typeArrayMap)}function x(H){if(S)return H.reject(Lo.connection("CONNECTION_ENDED",T,T));if($.length)return h($.shift(),H);if(M.length)return Jo(M.shift(),H);W.length?h(W.shift(),H):f.push(H)}function h(H,Z){return H.execute(Z)?E(H,W):E(H,O)}function w(H){return new Promise((Z,Fo)=>{H.state?H.active?Hy(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 v({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 Jo(H,Z){return E(H,y),H.connect(Z),H}function Oo(H){E(H,F)}function tn(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 xn(H,Z){E(H,M),H.reserved=null,H.onclose&&(H.onclose(Z),H.onclose=null),T.onclose&&T.onclose(H.id),f.length&&Jo(H,f.shift())}}function I0(o,n){if(o&&o.shared)return o;let T=process.env,t=(!o||typeof o==="string"?n:o)||{},{url:S,multihost:f}=h0(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||x0();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:N0,max_pipeline:100,backoff:r0,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:j0(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:{}},...AJ(t.types)}}function j0(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 r0(o){return(0.5+Math.random()/2)*Math.min(3**o/100,20)}function N0(){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 h0(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 x0(){try{return C0.userInfo().username}catch(o){return process.env.USERNAME||"runner"}}class lS extends nn{constructor(o,n,T,t){super();this.session=n,this.dialect=T,this.config={table:o,withList:t}}static[k]="PgDelete";config;where(o){return this.config.where=o,this}returning(o=this.config.table[I.Symbol.Columns]){return this.config.returning=Kn(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 c0(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((T)=>T.toLowerCase()).join("_")}function v0(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 i0(o){return o}class Dy{static[k]="CasingCache";cache={};cachedTables={};convert;constructor(o){this.convert=o==="snake_case"?c0:o==="camelCase"?v0:i0}getColumnCasing(o){if(!o.keyAsName)return o.name;let n=o.table[I.Symbol.Schema]??"public",T=o.table[I.Symbol.OriginalName],t=`${n}.${T}.${o.name}`;if(!this.cache[t])this.cacheTable(o.table);return this.cache[t]}cacheTable(o){let n=o[I.Symbol.Schema]??"public",T=o[I.Symbol.OriginalName],t=`${n}.${T}`;if(!this.cachedTables[t]){for(let S of Object.values(o[I.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 yn{static[k]="PgViewBase"}class YT{static[k]="PgDialect";casing;constructor(o){this.casing=new Dy(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)} (
30
+ `};return S(F),new Promise(async(W)=>A=W);async function y({highWaterMark:W=16384,start:O=0,end:E=1/0}={}){let Q=E-O;return O&&await F.seek(O),new wk.Readable({highWaterMark:W,async read(H){let Y=H>Q?H-Q:H;Q-=H;let[{data:B}]=await F.read(Y);if(this.push(B),B.length<H)this.push(null)}})}async function $({highWaterMark:W=16384,start:O=0}={}){return O&&await F.seek(O),new wk.Writable({highWaterMark:W,write(E,Q,H){F.write(E).then(()=>H(),H)}})}}).catch(f)})}Object.assign(gf,{PostgresError:dT,toPascal:KT,pascal:KA,toCamel:wT,camel:wA,toKebab:XT,kebab:XA,fromPascal:hS,fromCamel:NS,fromKebab:bS,BigInt:{to:20,from:[20],parse:(o)=>BigInt(o),serialize:(o)=>o.toString()}});var aT=gf;function gf(o,n){let T=j0(o,n),S=T.no_subscribe||zA(gf,{...T}),f=!1,t=Wn(),A=Wn(),M=Wn(),F=Wn(),y=Wn(),$=Wn(),W=Wn(),O=Wn(),E={connecting:A,reserved:M,closed:F,ended:y,open:$,busy:W,full:O},Q=[...Array(T.max)].map(()=>HA(T,E,{onopen:fn,onend:Oo,onclose:xn})),H=Y(v);return Object.assign(H,{get parameters(){return T.parameters},largeObject:mA.bind(null,H),subscribe:S,CLOSE:eT,END:eT,PostgresError:dT,options:T,reserve:b,listen:B,begin:a,close:r,end:q}),H;function Y(z){return z.debug=T.debug,Object.entries(T.types).reduce((To,[_o,Lo])=>{return To[_o]=(mo)=>new rn(mo,Lo.to),To},Z),Object.assign(yo,{types:Z,typed:Z,unsafe:Ho,notify:j,array:U,json:G,file:jo}),yo;function Z(To,_o){return new rn(To,_o)}function yo(To,..._o){return To&&Array.isArray(To.raw)?new Xn(To,_o,z,w):typeof To==="string"&&!_o.length?new rS(T.transform.column.to?T.transform.column.to(To):To):new cf(To,_o)}function Ho(To,_o=[],Lo={}){return arguments.length===2&&!Array.isArray(_o)&&(Lo=_o,_o=[]),new Xn([To],_o,z,w,{prepare:!1,...Lo,simple:"simple"in Lo?Lo.simple:_o.length===0})}function jo(To,_o=[],Lo={}){return arguments.length===2&&!Array.isArray(_o)&&(Lo=_o,_o=[]),new Xn([],_o,(Xo)=>{I0.readFile(To,"utf8",(po,wo)=>{if(po)return Xo.reject(po);Xo.strings=[wo],z(Xo)})},w,{...Lo,simple:"simple"in Lo?Lo.simple:_o.length===0})}}async function B(z,Z,yo){let Ho={fn:Z,onlisten:yo},jo=B.sql||(B.sql=gf({...T,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(B.channels).forEach(([Xo,{listeners:po}])=>{delete B.channels[Xo],Promise.all(po.map((wo)=>B(Xo,wo.fn,wo.onlisten).catch(()=>{})))})},onnotify(Xo,po){Xo in B.channels&&B.channels[Xo].listeners.forEach((wo)=>wo.fn(po))}})),To=B.channels||(B.channels={});if(z in To){To[z].listeners.push(Ho);let Xo=await To[z].result;return Ho.onlisten&&Ho.onlisten(),{state:Xo.state,unlisten:mo}}To[z]={result:jo`listen ${jo.unsafe('"'+z.replace(/"/g,'""')+'"')}`,listeners:[Ho]};let Lo=await To[z].result;return Ho.onlisten&&Ho.onlisten(),{state:Lo.state,unlisten:mo};async function mo(){if(z in To===!1)return;if(To[z].listeners=To[z].listeners.filter((Xo)=>Xo!==Ho),To[z].listeners.length)return;return delete To[z],jo`unlisten ${jo.unsafe('"'+z.replace(/"/g,'""')+'"')}`}}async function j(z,Z){return await H`select pg_notify(${z}, ${""+Z})`}async function b(){let z=Wn(),Z=$.length?$.shift():await new Promise((jo)=>{t.push({reserve:jo}),F.length&&ko(F.shift())});X(Z,M),Z.reserved=()=>z.length?Z.execute(z.shift()):X(Z,M),Z.reserved.release=!0;let yo=Y(Ho);return yo.release=()=>{Z.reserved=null,fn(Z)},yo;function Ho(jo){Z.queue===O?z.push(jo):Z.execute(jo)||X(Z,O)}}async function a(z,Z){!Z&&(Z=z,z="");let yo=Wn(),Ho=0,jo,To=null;try{return await H.unsafe("begin "+z.replace(/[^a-z ]/ig,""),[],{onexecute:Lo}).execute(),await Promise.race([_o(jo,Z),new Promise((mo,Xo)=>jo.onclose=Xo)])}catch(mo){throw mo}async function _o(mo,Xo,po){let wo=Y(No);wo.savepoint=dn,wo.prepare=(Yo)=>To=Yo.replace(/[^a-z0-9$-_. ]/gi);let Yn,Zo;po&&await wo`savepoint ${wo(po)}`;try{if(Zo=await new Promise((Yo,Gn)=>{let Ln=Xo(wo);Promise.resolve(Array.isArray(Ln)?Promise.all(Ln):Ln).then(Yo,Gn)}),Yn)throw Yn}catch(Yo){throw await(po?wo`rollback to ${wo(po)}`:wo`rollback`),Yo instanceof dT&&Yo.code==="25P02"&&Yn||Yo}if(!po)To?await wo`prepare transaction '${wo.unsafe(To)}'`:await wo`commit`;return Zo;function dn(Yo,Gn){if(Yo&&Array.isArray(Yo.raw))return dn((Ln)=>Ln.apply(Ln,arguments));return arguments.length===1&&(Gn=Yo,Yo=null),_o(mo,Gn,"s"+Ho+++(Yo?"_"+Yo:""))}function No(Yo){Yo.catch((Gn)=>Yn||(Yn=Gn)),mo.queue===O?yo.push(Yo):mo.execute(Yo)||X(mo,O)}}function Lo(mo){jo=mo,X(mo,M),mo.reserved=()=>yo.length?mo.execute(yo.shift()):X(mo,M)}}function X(z,Z){return z.queue.remove(z),Z.push(z),z.queue=Z,Z===$?z.idleTimer.start():z.idleTimer.cancel(),z}function G(z){return new rn(z,3802)}function U(z,Z){if(!Array.isArray(z))return U(Array.from(arguments));return new rn(z,Z||(z.length?rf(z)||25:0),T.shared.typeArrayMap)}function v(z){if(f)return z.reject(Io.connection("CONNECTION_ENDED",T,T));if($.length)return c($.shift(),z);if(F.length)return ko(F.shift(),z);W.length?c(W.shift(),z):t.push(z)}function c(z,Z){return z.execute(Z)?X(z,W):X(z,O)}function w(z){return new Promise((Z,yo)=>{z.state?z.active?HA(T).cancel(z.state,Z,yo):z.cancelled={resolve:Z,reject:yo}:(t.remove(z),z.cancelled=!0,z.reject(Io.generic("57014","canceling statement due to user request")),Z())})}async function q({timeout:z=null}={}){if(f)return f;await 1;let Z;return f=Promise.race([new Promise((yo)=>z!==null&&(Z=setTimeout(p,z*1000,yo))),Promise.all(Q.map((yo)=>yo.end()).concat(B.sql?B.sql.end({timeout:0}):[],S.sql?S.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(Z))}async function r(){await Promise.all(Q.map((z)=>z.end()))}async function p(z){await Promise.all(Q.map((Z)=>Z.terminate()));while(t.length)t.shift().reject(Io.connection("CONNECTION_DESTROYED",T));z()}function ko(z,Z){return X(z,A),z.connect(Z),z}function Oo(z){X(z,y)}function fn(z){if(t.length===0)return X(z,$);let Z=Math.ceil(t.length/(A.length+1)),yo=!0;while(yo&&t.length&&Z-- >0){let Ho=t.shift();if(Ho.reserve)return Ho.reserve(z);yo=z.execute(Ho)}yo?X(z,W):X(z,O)}function xn(z,Z){X(z,F),z.reserved=null,z.onclose&&(z.onclose(Z),z.onclose=null),T.onclose&&T.onclose(z.id),t.length&&ko(z,t.shift())}}function j0(o,n){if(o&&o.shared)return o;let T=process.env,S=(!o||typeof o==="string"?n:o)||{},{url:f,multihost:t}=x0(o),A=[...f.searchParams].reduce((O,[E,Q])=>(O[E]=Q,O),{}),M=S.hostname||S.host||t||f.hostname||T.PGHOST||"localhost",F=S.port||f.port||T.PGPORT||5432,y=S.user||S.username||f.username||T.PGUSERNAME||T.PGUSER||c0();S.no_prepare&&(S.prepare=!1),A.sslmode&&(A.ssl=A.sslmode,delete A.sslmode),"timeout"in S&&(console.log("The timeout option is deprecated, use idle_timeout instead"),S.idle_timeout=S.timeout),A.sslrootcert==="system"&&(A.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:h0,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(M)?M:M.split(",").map((O)=>O.split(":")[0]),port:Array.isArray(F)?F:M.split(",").map((O)=>parseInt(O.split(":")[1]||F)),path:S.path||M.indexOf("/")>-1&&M+"/.s.PGSQL."+F,database:S.database||S.db||(f.pathname||"").slice(1)||T.PGDATABASE||y,user:y,pass:S.pass||S.password||f.password||T.PGPASSWORD||"",...Object.entries(W).reduce((O,[E,Q])=>{let H=E in S?S[E]:(E in A)?A[E]==="disable"||A[E]==="false"?!1:A[E]:T["PG"+E.toUpperCase()]||Q;return O[E]=typeof H==="string"&&$.includes(E)?+H:H,O},{}),connection:{application_name:"postgres.js",...S.connection,...Object.entries(A).reduce((O,[E,Q])=>((E in W)||(O[E]=Q),O),{})},types:S.types||{},target_session_attrs:N0(S,f,T),onnotice:S.onnotice,onnotify:S.onnotify,onclose:S.onclose,onparameter:S.onparameter,socket:S.socket,transform:r0(S.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...Ak(S.types)}}function N0(o,n,T){let S=o.target_session_attrs||n.searchParams.get("target_session_attrs")||T.PGTARGETSESSIONATTRS;if(!S||["read-write","read-only","primary","standby","prefer-standby"].includes(S))return S;throw new Error("target_session_attrs "+S+" is not supported")}function h0(o){return(0.5+Math.random()/2)*Math.min(3**o/100,20)}function b0(){return 60*(30+Math.random()*30)}function r0(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 x0(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 c0(){try{return L0.userInfo().username}catch(o){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class Vo{static[R]="SelectionProxyHandler";config;constructor(o){this.config={...o}}get(o,n){if(n==="_")return{...o._,selectedFields:new Proxy(o._.selectedFields,this)};if(n===Ko)return{...o[Ko],selectedFields:new Proxy(o[Ko].selectedFields,this)};if(typeof n==="symbol")return o[n];let S=(K(o,ro)?o._.selectedFields:K(o,Mn)?o[Ko].selectedFields:o)[n];if(K(S,N.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!S.isSelectionField)return S.sql;let f=S.clone();return f.isSelectionField=!0,f}if(K(S,N)){if(this.config.sqlBehavior==="sql")return S;throw new Error(`You tried to reference "${n}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(K(S,Jo)){if(this.config.alias)return new Proxy(S,new lT(new Proxy(S.table,new US(this.config.alias,this.config.replaceOriginalName??!1))));return S}if(typeof S!=="object"||S===null)return S;return new Proxy(S,new Vo(this.config))}}class lf extends Tn{constructor(o,n,T,S){super();this.session=n,this.dialect=T,this.config={table:o,withList:S}}static[R]="PgDelete";config;where(o){return this.config.where=o,this}returning(o=this.config.table[I.Symbol.Columns]){return this.config.returningFields=o,this.config.returning=Kn(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)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new Vo({alias:co(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}function v0(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((T)=>T.toLowerCase()).join("_")}function q0(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((T,S,f)=>{let t=f===0?S.toLowerCase():`${S[0].toUpperCase()}${S.slice(1)}`;return T+t},"")}function i0(o){return o}class QA{static[R]="CasingCache";cache={};cachedTables={};convert;constructor(o){this.convert=o==="snake_case"?v0:o==="camelCase"?q0:i0}getColumnCasing(o){if(!o.keyAsName)return o.name;let n=o.table[I.Symbol.Schema]??"public",T=o.table[I.Symbol.OriginalName],S=`${n}.${T}.${o.name}`;if(!this.cache[S])this.cacheTable(o.table);return this.cache[S]}cacheTable(o){let n=o[I.Symbol.Schema]??"public",T=o[I.Symbol.OriginalName],S=`${n}.${T}`;if(!this.cachedTables[S]){for(let f of Object.values(o[I.Symbol.Columns])){let t=`${S}.${f.name}`;this.cache[t]=this.convert(f.name)}this.cachedTables[S]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class cS extends Mn{static[R]="PgViewBase"}class GT{static[R]="PgDialect";casing;constructor(o){this.casing=new QA(o?.casing)}async migrate(o,n,T){let S=typeof T==="string"?"__drizzle_migrations":T.migrationsTable??"__drizzle_migrations",f=typeof T==="string"?"drizzle":T.migrationsSchema??"drizzle",t=J`
31
+ CREATE TABLE IF NOT EXISTS ${J.identifier(f)}.${J.identifier(S)} (
32
32
  id SERIAL PRIMARY KEY,
33
33
  hash text NOT NULL,
34
34
  created_at bigint
35
35
  )
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[I.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[vo.Symbol.Name],F=o[vo.Symbol.Schema],$=o[vo.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,j.Aliased)&&S.isSelectionField)y.push(R.identifier(S.fieldAlias));else if(X(S,j.Aliased)||X(S,j)){let A=X(S,j.Aliased)?S.sql:S;if(n)y.push(new j(A.queryChunks.map((M)=>{if(X(M,V))return R.identifier(this.casing.getColumnCasing(M));return M})));else y.push(A);if(X(S,j.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,vo)){let y=S[vo.Symbol.Name],A=S[vo.Symbol.Schema],M=S[vo.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,yn)){let y=S[Go].name,A=S[Go].schema,M=S[Go].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,I)&&o[I.Symbol.OriginalName]!==o[I.Symbol.Name]){let n=R`${R.identifier(o[I.Symbol.OriginalName])}`;if(o[I.Symbol.Schema])n=R`${R.identifier(o[I.Symbol.Schema])}.${n}`;return R`${n} ${R.identifier(o[I.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??Kn(n);for(let q of D)if(X(q.field,Ro)&&wn(q.field.table)!==(X(f,bo)?f._.alias:X(f,ct)?f[Go].name:X(f,j)?void 0:wn(f))&&!((Jo)=>y?.some(({alias:Oo})=>Oo===(Jo[I.Symbol.IsAlias]?wn(Jo):Jo[I.Symbol.BaseName])))(q.field.table)){let Jo=wn(q.field.table);throw new Error(`Your "${q.path.join("->")}" field references a column "${Jo}"."${q.field.name}", but the table "${Jo}" 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 p=this.buildSelection(D,{isSingleTable:z}),c=this.buildFromTable(f),a=this.buildJoins(y),E=t?R` where ${t}`:void 0,K=S?R` having ${S}`:void 0,Q;if(A&&A.length>0)Q=R` order by ${R.join(A,R`, `)}`;let x;if(M&&M.length>0)x=R` group by ${R.join(M,R`, `)}`;let h=typeof F==="object"||typeof F==="number"&&F>=0?R` limit ${F}`:void 0,w=$?R` offset ${$}`:void 0,v=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`);v.append(q)}let N=R`${Y}select${B} ${p} from ${c}${a}${E}${x}${K}${Q}${h}${w}${v}`;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,j)){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[I.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,j))A.push(Y);else A.push(Y.getSQL())}else{let Y=n;A.push(R.raw("values "));for(let[B,p]of Y.entries()){let c=[];for(let[a,E]of F){let K=p[a];if(K===void 0||X(K,Jn)&&K.value===void 0)if(E.defaultFn!==void 0){let Q=E.defaultFn(),x=X(Q,j)?Q:R.param(Q,E);c.push(x)}else if(!E.default&&E.onUpdateFn!==void 0){let Q=E.onUpdateFn(),x=X(Q,j)?Q:R.param(Q,E);c.push(x)}else c.push(R`default`);else c.push(K)}if(A.push(c),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,BS)||X(o,VS))return"json";else if(X(o,CS))return"decimal";else if(X(o,LS))return"time";else if(X(o,IS)||X(o,jS))return"timestamp";else if(X(o,QS)||X(o,DS))return"date";else if(X(o,rS))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,p])=>({dbKey:p.name,tsKey:B,field:bn(p,y),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let Y=Object.fromEntries(Object.entries(S.columns).map(([K,Q])=>[K,bn(Q,y)]));if(f.where){let K=typeof f.where==="function"?f.where(Y,l$()):f.where;G=K&&Vt(K,y)}let B=[],p=[];if(f.columns){let K=!1;for(let[Q,x]of Object.entries(f.columns)){if(x===void 0)continue;if(Q in S.columns){if(!K&&x===!0)K=!0;p.push(Q)}}if(p.length>0)p=K?p.filter((Q)=>f.columns?.[Q]===!0):Object.keys(S.columns).filter((Q)=>!p.includes(Q))}else p=Object.keys(S.columns);for(let K of p){let Q=S.columns[K];B.push({tsKey:K,value:Q})}let c=[];if(f.with)c=Object.entries(f.with).filter((K)=>!!K[1]).map(([K,Q])=>({tsKey:K,queryConfig:Q,relation:S.relations[K]}));let a;if(f.extras){a=typeof f.extras==="function"?f.extras(Y,{sql:R}):f.extras;for(let[K,Q]of Object.entries(a))B.push({tsKey:K,value:Ty(Q,y)})}for(let{tsKey:K,value:Q}of B)F.push({dbKey:X(Q,j.Aliased)?Q.fieldAlias:S.columns[K].name,tsKey:K,field:X(Q,Ro)?bn(Q,y):Q,relationTableTsKey:void 0,isJson:!1,selection:[]});let E=typeof f.orderBy==="function"?f.orderBy(Y,e$()):f.orderBy??[];if(!Array.isArray(E))E=[E];O=E.map((K)=>{if(X(K,Ro))return bn(K,y);return Vt(K,y)}),$=f.limit,W=f.offset;for(let{tsKey:K,queryConfig:Q,relation:x}of c){let h=u$(n,T,x),w=_T(x.referencedTable),v=T[w],N=`${y}_${K}`,q=Bt(...h.fields.map((tn,xn)=>HS(bn(h.references[xn],N),bn(tn,y)))),Jo=this.buildRelationalQueryWithoutPK({fullSchema:o,schema:n,tableNamesMap:T,table:o[v],tableConfig:n[v],queryConfig:X(x,MT)?Q===!0?{limit:1}:{...Q,limit:1}:Q,tableAlias:N,joinOn:q,nestedQueryRelation:x}),Oo=R`${R.identifier(N)}.${R.identifier("data")}`.as(K);D.push({on:R`true`,table:new bo(Jo.sql,{},N),alias:N,joinType:"left",lateral:!0}),F.push({dbKey:K,tsKey:K,field:Oo,relationTableTsKey:v,isJson:!0,selection:Jo.selection})}}if(F.length===0)throw new zS({message:`No fields selected for table "${S.tsName}" ("${y}")`});let z;if(G=Bt(M,G),A){let Y=R`json_build_array(${R.join(F.map(({field:c,tsKey:a,isJson:E})=>E?R`${R.identifier(`${y}_${a}`)}.${R.identifier("data")}`:X(c,j.Aliased)?c.sql:c),R`, `)})`;if(X(A,jt))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:GS(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=GS(t,y);z=this.buildSelectQuery({table:X(z,vo)?z:new bo(z,{},y),fields:{},fieldsFlat:B.map(({field:c})=>({path:[],field:X(c,Ro)?bn(c,y):c})),joins:D,where:G,limit:$,offset:W,orderBy:O,setOperators:[]})}else z=this.buildSelectQuery({table:GS(t,y),fields:{},fieldsFlat:F.map(({field:Y})=>({path:[],field:X(Y,Ro)?bn(Y,y):Y})),joins:D,where:G,limit:$,offset:W,orderBy:O,setOperators:[]});return{tableTsKey:S.tsName,sql:z,selection:F}}}class io{static[k]="SelectionProxyHandler";config;constructor(o){this.config={...o}}get(o,n){if(n==="_")return{...o._,selectedFields:new Proxy(o._.selectedFields,this)};if(n===Go)return{...o[Go],selectedFields:new Proxy(o[Go].selectedFields,this)};if(typeof n==="symbol")return o[n];let t=(X(o,bo)?o._.selectedFields:X(o,yn)?o[Go].selectedFields:o)[n];if(X(t,j.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!t.isSelectionField)return t.sql;let S=t.clone();return S.isSelectionField=!0,S}if(X(t,j)){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 Ut(this.config.alias,this.config.replaceOriginalName??!1))));return t}if(typeof t!=="object"||t===null)return t;return new Proxy(t,new io(this.config))}}class Uy{static[k]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class Tn{static[k]="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,bo))T=Object.fromEntries(Object.keys(o._.selectedFields).map((t)=>[t,o[t]]));else if(X(o,ct))T=o[Go].selectedFields;else if(X(o,j))T={};else T=aM(o);return new Vy({table:o,fields:T,isPartialSelect:n,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class XJ extends Uy{static[k]="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=ln(o),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(o){return(n,T)=>{let t=this.tableName,S=ln(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,j)){let f=X(n,bo)?n._.selectedFields:X(n,yn)?n[Go].selectedFields:n[I.Symbol.Columns];this.config.fields[S]=f}}if(typeof T==="function")T=T(new Proxy(this.config.fields,new io({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(p0()):T;if(!Ct(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 io({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=o,this}having(o){if(typeof o==="function")o=o(new Proxy(this.config.fields,new io({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 io({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 io({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 bo(this.getSQL(),this.config.fields,o),new io({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new io({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class Vy extends XJ{static[k]="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=Kn(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)})}}uM(Vy,[nn]);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(!Ct(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 p0=()=>({union:q0,unionAll:Z0,intersect:P0,intersectAll:g0,except:l0,exceptAll:e0}),q0=sT("union",!1),Z0=sT("union",!0),P0=sT("intersect",!1),g0=sT("intersect",!0),l0=sT("except",!1),e0=sT("except",!0);class vt{static[k]="PgQueryBuilder";dialect;dialectConfig;constructor(o){this.dialect=X(o,YT)?o:void 0,this.dialectConfig=X(o,YT)?void 0:o}$with(o){let n=this;return{as(T){if(typeof T==="function")T=T(n);return new Proxy(new Dt(T.getSQL(),T.getSelectedFields(),o,!0),new io({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 YT(this.dialectConfig);return this.dialect}}class eS{constructor(o,n,T,t,S){this.table=o,this.session=n,this.dialect=T,this.withList=t,this.overridingSystemValue_=S}static[k]="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[I.Symbol.Columns];for(let f of Object.keys(T)){let y=T[f];t[f]=X(y,j)?y:new Jn(y,S[f])}return t});return new By(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,j)&&!Ct(this.table[XS],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 By(this.table,n,this.session,this.dialect,this.withList,!0)}}class By extends nn{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[k]="PgInsert";config;returning(o=this.config.table[I.Symbol.Columns]){return this.config.returning=Kn(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,mS(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 Cy extends nn{constructor(o,n,T){super();this.session=n,this.dialect=T,this.config={view:o}}static[k]="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 dS{constructor(o,n,T,t){this.table=o,this.session=n,this.dialect=T,this.withList=t}static[k]="PgUpdateBuilder";authToken;setToken(o){return this.authToken=o,this}set(o){return new EJ(this.table,mS(this.table,o),this.session,this.dialect,this.withList).setToken(this.authToken)}}class EJ extends nn{constructor(o,n,T,t,S){super();this.session=T,this.dialect=t,this.config={set:n,table:o,withList:S,joins:[]},this.tableName=ln(o),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[k]="PgUpdate";config;tableName;joinsNotNullableMap;from(o){let n=ln(o);if(typeof n==="string")this.joinsNotNullableMap[n]=!0;return this.config.from=o,this}getTableLikeFields(o){if(X(o,vo))return o[I.Symbol.Columns];else if(X(o,bo))return o._.selectedFields;return o[Go].selectedFields}createJoin(o){return(n,T)=>{let t=ln(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,j)?this.getTableLikeFields(this.config.from):void 0;T=T(new Proxy(this.config.table[I.Symbol.Columns],new io({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),S&&new Proxy(S,new io({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[I.Symbol.Columns]),this.config.from){let n=ln(this.config.from);if(typeof n==="string"&&this.config.from&&!X(this.config.from,j)){let T=this.getTableLikeFields(this.config.from);o[n]=T}for(let T of this.config.joins){let t=ln(T.table);if(typeof t==="string"&&!X(T.table,j)){let S=this.getTableLikeFields(T.table);o[t]=S}}}}return this.config.returning=Kn(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 it extends j{constructor(o){super(it.buildEmbeddedCount(o.source,o.filters).queryChunks);this.params=o,this.mapWith(Number),this.session=o.session,this.sql=it.buildCount(o.source,o.filters)}sql;token;static[k]="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 Iy{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[k]="PgRelationalQueryBuilder";findMany(o){return new Ly(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?o:{},"many")}findFirst(o){return new Ly(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?{...o,limit:1}:{limit:1},"first")}}class Ly extends nn{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[k]="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)=>NS(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 nn{constructor(o,n,T,t){super();this.execute=o,this.sql=n,this.query=T,this.mapBatchResult=t}static[k]="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 pt{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 Iy(T.fullSchema,this._.schema,this._.tableNamesMap,T.fullSchema[t],S,o,n)}static[k]="PgDatabase";query;$with(o){let n=this;return{as(T){if(typeof T==="function")T=T(new vt(n.dialect));return new Proxy(new Dt(T.getSQL(),T.getSelectedFields(),o,!0),new io({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}$count(o,n){return new it({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 dS(M,n.session,n.dialect,o)}function y(M){return new eS(M,n.session,n.dialect,o)}function A(M){return new lS(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 dS(o,this.session,this.dialect)}insert(o){return new eS(o,this.session,this.dialect)}delete(o){return new lS(o,this.session,this.dialect)}refreshMaterializedView(o){return new Cy(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 YJ{constructor(o,n){this.unique=o,this.name=n}static[k]="PgIndexBuilderOn";on(...o){return new uS(o.map((n)=>{if(X(n,j))return n;n=n;let T=new Qt(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 uS(o.map((n)=>{if(X(n,j))return n;n=n;let T=new Qt(n.name,!!n.keyAsName,n.columnType,n.indexConfig);return n.indexConfig=n.defaultConfig,T}),this.unique,!0,this.name)}using(o,...n){return new uS(n.map((T)=>{if(X(T,j))return T;T=T;let t=new Qt(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 uS{static[k]="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 GJ(this.config,o)}}class GJ{static[k]="PgIndex";config;constructor(o,n){this.config={...o,table:n}}}function ry(o){return new YJ(!0,o)}class Ny{constructor(o){this.query=o}authToken;getQuery(){return this.query}mapResult(o,n){return o}setToken(o){return this.authToken=o,this}static[k]="PgPreparedQuery";joinsNotNullableMap}class by{constructor(o){this.dialect=o}static[k]="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 hy extends pt{constructor(o,n,T,t=0){super(o,n,T);this.schema=T,this.nestedIndex=t}static[k]="PgTransaction";rollback(){throw new ty}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 zJ extends Ny{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[k]="PostgresJsPreparedQuery";async execute(o={}){return Wo.startActiveSpan("drizzle.execute",async(n)=>{let T=ny(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)=>dM(t,F,y))})})}all(o={}){return Wo.startActiveSpan("drizzle.execute",async(n)=>{let T=ny(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 qt extends by{constructor(o,n,T,t={}){super(n);this.client=o,this.schema=T,this.options=t,this.logger=t.logger??new fy}static[k]="PostgresJsSession";logger;prepareQuery(o,n,T,t,S){return new zJ(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 qt(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 hy{constructor(o,n,T,t=0){super(o,n,T,t);this.session=n}static[k]="PostgresJsTransaction";transaction(o){return this.session.client.savepoint((n)=>{let T=new qt(n,this.dialect,this.schema,this.session.options),t=new xy(this.dialect,T,this.schema);return o(t)})}}class HJ extends pt{static[k]="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 YT({casing:n.casing}),S;if(n.logger===!0)S=new Sy;else if(n.logger!==!1)S=n.logger;let f;if(n.schema){let M=d$(n.schema,a$);f={fullSchema:n.schema,schema:M.tables,tableNamesMap:M.tableNamesMap}}let y=new qt(o,t,f,{logger:S}),A=new HJ(t,y,f);return A.$client=o,A}function aS(...o){if(typeof o[0]==="string"){let n=aT(o[0]);return ot(n,o[1])}if(sM(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({options:{parsers:{},serializers:{}}},T)}o.mock=n})(aS||(aS={}));var vy={};Vk(vy,{users:()=>GT,userChanges:()=>u0,untrackedUserColumnNames:()=>d0,twoFactorMethod:()=>VJ,trackedUserColumnName:()=>UJ,trackableUserColumnNames:()=>DJ,role:()=>QJ,players:()=>cy,passwordResetAttempts:()=>s0,loginHistory:()=>a0,games:()=>sS,banishedIps:()=>oW});function mJ(o){return R`lower(${o})`}var QJ=wS("role",["admin","user"]),GT=AT("users",{id:kn().primaryKey().defaultRandom(),username:co({length:16}).notNull(),email:co({length:254}).notNull(),hash:co({length:64}).notNull(),salt:co({length:36}).notNull(),createdAt:Cn({withTimezone:!0}).notNull().defaultNow(),createdIp:co({length:45}).notNull(),isActive:Lt().notNull().default(!1),verifiedAt:Cn({withTimezone:!0}),userRole:QJ().default("user")},(o)=>[ry("usernameUniqueIndex").on(mJ(o.username)),ry("emailUniqueIndex").on(mJ(o.email))]),d0=["id","createdAt","createdIp","isActive","salt","verifiedAt"],DJ=["username","email","hash","userRole"],UJ=wS("trackedUserColumnName",DJ),u0=AT("userChanges",{id:kn().primaryKey().defaultRandom(),userId:kn().notNull().references(()=>GT.id),changedAt:Cn({withTimezone:!0}).notNull().defaultNow(),changedIp:co({length:45}).notNull(),changedColumn:UJ().notNull(),oldValue:co({length:255}),newValue:co({length:255})}),sS=AT("games",{id:kn().primaryKey().defaultRandom()}),cy=AT("players",{userId:kn().notNull().references(()=>GT.id),gameId:kn().notNull().references(()=>sS.id),score:US().notNull()},(o)=>[Z$({name:"players_userId_gameId_pk",columns:[o.userId,o.gameId]})]),a0=AT("loginHistory",{id:kn().primaryKey().defaultRandom(),userId:kn().references(()=>GT.id),loginTime:Cn({withTimezone:!0}).notNull().defaultNow(),ipAddress:co({length:45}).notNull(),userAgent:co({length:1024}),successful:Lt().notNull().default(!1)}),VJ=wS("twoFactorMethod",["email","phone"]),s0=AT("passwordResetAttempts",{id:kn().primaryKey().defaultRandom(),userId:kn().notNull().references(()=>GT.id),requestedIp:co({length:45}).notNull(),requestedAt:Cn({withTimezone:!0}).notNull().defaultNow(),succeededIp:co({length:45}),succeededAt:Cn({withTimezone:!0}),verificationMethod:VJ().notNull()}),oW=AT("banishedIps",{ip:co({length:45}).primaryKey(),reason:co({length:2048}).notNull(),banishedAt:Cn({withTimezone:!0}).notNull().defaultNow(),banishedUntil:Cn({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class iy{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(nW.resolve(__dirname,"notify_update.sql"));let o=[wn(GT),wn(sS),wn(cy)];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:Vn.POSTGRES_HOST,port:Vn.POSTGRES_PORT,user:Vn.POSTGRES_USER,password:Vn.POSTGRES_PASSWORD,database:Vn.POSTGRES_DATABASE}){this.options=n,this.sql=aT(n),this.drizzle=aS(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 of={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"},py=TA(of).map(([o])=>Yo.literal(Number(o))),TW=Yo.union([py[0],py[1],...py]),BJ=Yo.tuple([TW,Yo.string()]);var Zy=new jf,{logger:Mn}=Zy;Object.assign(console,Mn,{log:Mn.info});Mn.info("ready");var qy=LJ(import.meta.dir,"..","app"),U3=new iy({logQuery(o,n){Mn.info("\uD83D\uDCDD query",o,n)}});fW({hostname:"0.0.0.0",port:Vn.FRONTEND_PORT??3333,...JM??void 0,async fetch(o){try{let n=new Date,T=new URL(o.url);if(Mn.info(o.method,T.pathname),T.pathname==="/")return new Response(Bun.file(LJ(qy,"index.html")));if(T.pathname==="/index.html")return Response.redirect("/");let t=tW(qy,T.pathname),S=SW(t);if(!S.startsWith(qy))throw[403,"Access Denied"];if(!await CJ(S).exists())return Response.redirect("/");return new Response(CJ(S))}catch(n){let T=BJ.safeParse(n);if(T.success){let[t,S]=T.data,y=`${of[t]}. ${S}`;return Mn.info(`\u274C ${t}: ${y}`),new Response(y,{status:t})}if(n instanceof Error)Mn.error(n.message);else{let t=BT(n);Mn.error("frontend server threw",t)}return new Response(of[500],{status:500})}}});function nf(){Mn.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{Mn.info("\u2757 received SIGINT; exiting gracefully"),nf()});process.on("SIGTERM",()=>{Mn.info("\u2757 received SIGTERM; exiting gracefully"),nf()});process.on("exit",()=>{Mn.info("\u2757 received exit; exiting gracefully"),nf()});Zy.on("timeToStop",()=>{Mn.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),nf()});Mn.info(`\uD83D\uDEEB frontend server running at http://localhost:${Vn.FRONTEND_PORT}/`);Zy.emit("alive");
36
+ `;await n.execute(J`CREATE SCHEMA IF NOT EXISTS ${J.identifier(f)}`),await n.execute(t);let M=(await n.all(J`select id, hash, created_at from ${J.identifier(f)}.${J.identifier(S)} order by created_at desc limit 1`))[0];await n.transaction(async(F)=>{for await(let y of o)if(!M||Number(M.created_at)<y.folderMillis){for(let $ of y.sql)await F.execute(J.raw($));await F.execute(J`insert into ${J.identifier(f)}.${J.identifier(S)} ("hash", "created_at") values(${y.hash}, ${y.folderMillis})`)}})}escapeName(o){return`"${o}"`}escapeParam(o){return`$${o+1}`}escapeString(o){return`'${o.replace(/'/g,"''")}'`}buildWithCTE(o){if(!o?.length)return;let n=[J`with `];for(let[T,S]of o.entries())if(n.push(J`${J.identifier(S._.alias)} as (${S._.sql})`),T<o.length-1)n.push(J`, `);return n.push(J` `),J.join(n)}buildDeleteQuery({table:o,where:n,returning:T,withList:S}){let f=this.buildWithCTE(S),t=T?J` returning ${this.buildSelection(T,{isSingleTable:!0})}`:void 0,A=n?J` where ${n}`:void 0;return J`${f}delete from ${o}${A}${t}`}buildUpdateSet(o,n){let T=o[I.Symbol.Columns],S=Object.keys(T).filter((t)=>n[t]!==void 0||T[t]?.onUpdateFn!==void 0),f=S.length;return J.join(S.flatMap((t,A)=>{let M=T[t],F=n[t]??J.param(M.onUpdateFn(),M),y=J`${J.identifier(this.casing.getColumnCasing(M))} = ${F}`;if(A<f-1)return[y,J.raw(", ")];return[y]}))}buildUpdateQuery({table:o,set:n,where:T,returning:S,withList:f,from:t,joins:A}){let M=this.buildWithCTE(f),F=o[io.Symbol.Name],y=o[io.Symbol.Schema],$=o[io.Symbol.OriginalName],W=F===$?void 0:F,O=J`${y?J`${J.identifier(y)}.`:void 0}${J.identifier($)}${W&&J` ${J.identifier(W)}`}`,E=this.buildUpdateSet(o,n),Q=t&&J.join([J.raw(" from "),this.buildFromTable(t)]),H=this.buildJoins(A),Y=S?J` returning ${this.buildSelection(S,{isSingleTable:!t})}`:void 0,B=T?J` where ${T}`:void 0;return J`${M}update ${O} set ${E}${Q}${H}${B}${Y}`}buildSelection(o,{isSingleTable:n=!1}={}){let T=o.length,S=o.flatMap(({field:f},t)=>{let A=[];if(K(f,N.Aliased)&&f.isSelectionField)A.push(J.identifier(f.fieldAlias));else if(K(f,N.Aliased)||K(f,N)){let M=K(f,N.Aliased)?f.sql:f;if(n)A.push(new N(M.queryChunks.map((F)=>{if(K(F,V))return J.identifier(this.casing.getColumnCasing(F));return F})));else A.push(M);if(K(f,N.Aliased))A.push(J` as ${J.identifier(f.fieldAlias)}`)}else if(K(f,Jo))if(n)A.push(J.identifier(this.casing.getColumnCasing(f)));else A.push(f);if(t<T-1)A.push(J`, `);return A});return J.join(S)}buildJoins(o){if(!o||o.length===0)return;let n=[];for(let[T,S]of o.entries()){if(T===0)n.push(J` `);let f=S.table,t=S.lateral?J` lateral`:void 0;if(K(f,io)){let A=f[io.Symbol.Name],M=f[io.Symbol.Schema],F=f[io.Symbol.OriginalName],y=A===F?void 0:S.alias;n.push(J`${J.raw(S.joinType)} join${t} ${M?J`${J.identifier(M)}.`:void 0}${J.identifier(F)}${y&&J` ${J.identifier(y)}`} on ${S.on}`)}else if(K(f,Mn)){let A=f[Ko].name,M=f[Ko].schema,F=f[Ko].originalName,y=A===F?void 0:S.alias;n.push(J`${J.raw(S.joinType)} join${t} ${M?J`${J.identifier(M)}.`:void 0}${J.identifier(F)}${y&&J` ${J.identifier(y)}`} on ${S.on}`)}else n.push(J`${J.raw(S.joinType)} join${t} ${f} on ${S.on}`);if(T<o.length-1)n.push(J` `)}return J.join(n)}buildFromTable(o){if(K(o,I)&&o[I.Symbol.OriginalName]!==o[I.Symbol.Name]){let n=J`${J.identifier(o[I.Symbol.OriginalName])}`;if(o[I.Symbol.Schema])n=J`${J.identifier(o[I.Symbol.Schema])}.${n}`;return J`${n} ${J.identifier(o[I.Symbol.Name])}`}return o}buildSelectQuery({withList:o,fields:n,fieldsFlat:T,where:S,having:f,table:t,joins:A,orderBy:M,groupBy:F,limit:y,offset:$,lockingClause:W,distinct:O,setOperators:E}){let Q=T??Kn(n);for(let p of Q)if(K(p.field,Jo)&&co(p.field.table)!==(K(t,ro)?t._.alias:K(t,cS)?t[Ko].name:K(t,N)?void 0:co(t))&&!((ko)=>A?.some(({alias:Oo})=>Oo===(ko[I.Symbol.IsAlias]?co(ko):ko[I.Symbol.BaseName])))(p.field.table)){let ko=co(p.field.table);throw new Error(`Your "${p.path.join("->")}" field references a column "${ko}"."${p.field.name}", but the table "${ko}" is not part of the query! Did you forget to join it?`)}let H=!A||A.length===0,Y=this.buildWithCTE(o),B;if(O)B=O===!0?J` distinct`:J` distinct on (${J.join(O.on,J`, `)})`;let j=this.buildSelection(Q,{isSingleTable:H}),b=this.buildFromTable(t),a=this.buildJoins(A),X=S?J` where ${S}`:void 0,G=f?J` having ${f}`:void 0,U;if(M&&M.length>0)U=J` order by ${J.join(M,J`, `)}`;let v;if(F&&F.length>0)v=J` group by ${J.join(F,J`, `)}`;let c=typeof y==="object"||typeof y==="number"&&y>=0?J` limit ${y}`:void 0,w=$?J` offset ${$}`:void 0,q=J.empty();if(W){let p=J` for ${J.raw(W.strength)}`;if(W.config.of)p.append(J` of ${J.join(Array.isArray(W.config.of)?W.config.of:[W.config.of],J`, `)}`);if(W.config.noWait)p.append(J` no wait`);else if(W.config.skipLocked)p.append(J` skip locked`);q.append(p)}let r=J`${Y}select${B} ${j} from ${b}${a}${X}${v}${G}${U}${c}${w}${q}`;if(E.length>0)return this.buildSetOperations(r,E);return r}buildSetOperations(o,n){let[T,...S]=n;if(!T)throw new Error("Cannot pass undefined values to any set operator");if(S.length===0)return this.buildSetOperationQuery({leftSelect:o,setOperator:T});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:o,setOperator:T}),S)}buildSetOperationQuery({leftSelect:o,setOperator:{type:n,isAll:T,rightSelect:S,limit:f,orderBy:t,offset:A}}){let M=J`(${o.getSQL()}) `,F=J`(${S.getSQL()})`,y;if(t&&t.length>0){let E=[];for(let Q of t)if(K(Q,V))E.push(J.identifier(Q.name));else if(K(Q,N)){for(let H=0;H<Q.queryChunks.length;H++){let Y=Q.queryChunks[H];if(K(Y,V))Q.queryChunks[H]=J.identifier(Y.name)}E.push(J`${Q}`)}else E.push(J`${Q}`);y=J` order by ${J.join(E,J`, `)} `}let $=typeof f==="object"||typeof f==="number"&&f>=0?J` limit ${f}`:void 0,W=J.raw(`${n} ${T?"all ":""}`),O=A?J` offset ${A}`:void 0;return J`${M}${W}${F}${y}${$}${O}`}buildInsertQuery({table:o,values:n,onConflict:T,returning:S,withList:f,select:t,overridingSystemValue_:A}){let M=[],F=o[I.Symbol.Columns],y=Object.entries(F).filter(([Y,B])=>!B.shouldDisableInsert()),$=y.map(([,Y])=>J.identifier(this.casing.getColumnCasing(Y)));if(t){let Y=n;if(K(Y,N))M.push(Y);else M.push(Y.getSQL())}else{let Y=n;M.push(J.raw("values "));for(let[B,j]of Y.entries()){let b=[];for(let[a,X]of y){let G=j[a];if(G===void 0||K(G,Rn)&&G.value===void 0)if(X.defaultFn!==void 0){let U=X.defaultFn(),v=K(U,N)?U:J.param(U,X);b.push(v)}else if(!X.default&&X.onUpdateFn!==void 0){let U=X.onUpdateFn(),v=K(U,N)?U:J.param(U,X);b.push(v)}else b.push(J`default`);else b.push(G)}if(M.push(b),B<Y.length-1)M.push(J`, `)}}let W=this.buildWithCTE(f),O=J.join(M),E=S?J` returning ${this.buildSelection(S,{isSingleTable:!0})}`:void 0,Q=T?J` on conflict ${T}`:void 0,H=A===!0?J`overriding system value `:void 0;return J`${W}insert into ${o} ${$} ${H}${O}${Q}${E}`}buildRefreshMaterializedViewQuery({view:o,concurrently:n,withNoData:T}){let S=n?J` concurrently`:void 0,f=T?J` with no data`:void 0;return J`refresh materialized view${S} ${o}${f}`}prepareTyping(o){if(K(o,Vf)||K(o,Uf))return"json";else if(K(o,Bf))return"decimal";else if(K(o,Cf))return"time";else if(K(o,Lf)||K(o,If))return"timestamp";else if(K(o,mf)||K(o,Qf))return"date";else if(K(o,jf))return"uuid";else return"none"}sqlToQuery(o,n){return o.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:n})}buildRelationalQueryWithoutPK({fullSchema:o,schema:n,tableNamesMap:T,table:S,tableConfig:f,queryConfig:t,tableAlias:A,nestedQueryRelation:M,joinOn:F}){let y=[],$,W,O=[],E,Q=[];if(t===!0)y=Object.entries(f.columns).map(([B,j])=>({dbKey:j.name,tsKey:B,field:bn(j,A),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let Y=Object.fromEntries(Object.entries(f.columns).map(([G,U])=>[G,bn(U,A)]));if(t.where){let G=typeof t.where==="function"?t.where(Y,g$()):t.where;E=G&&VS(G,A)}let B=[],j=[];if(t.columns){let G=!1;for(let[U,v]of Object.entries(t.columns)){if(v===void 0)continue;if(U in f.columns){if(!G&&v===!0)G=!0;j.push(U)}}if(j.length>0)j=G?j.filter((U)=>t.columns?.[U]===!0):Object.keys(f.columns).filter((U)=>!j.includes(U))}else j=Object.keys(f.columns);for(let G of j){let U=f.columns[G];B.push({tsKey:G,value:U})}let b=[];if(t.with)b=Object.entries(t.with).filter((G)=>!!G[1]).map(([G,U])=>({tsKey:G,queryConfig:U,relation:f.relations[G]}));let a;if(t.extras){a=typeof t.extras==="function"?t.extras(Y,{sql:J}):t.extras;for(let[G,U]of Object.entries(a))B.push({tsKey:G,value:nA(U,A)})}for(let{tsKey:G,value:U}of B)y.push({dbKey:K(U,N.Aliased)?U.fieldAlias:f.columns[G].name,tsKey:G,field:K(U,Jo)?bn(U,A):U,relationTableTsKey:void 0,isJson:!1,selection:[]});let X=typeof t.orderBy==="function"?t.orderBy(Y,l$()):t.orderBy??[];if(!Array.isArray(X))X=[X];O=X.map((G)=>{if(K(G,Jo))return bn(G,A);return VS(G,A)}),$=t.limit,W=t.offset;for(let{tsKey:G,queryConfig:U,relation:v}of b){let c=d$(n,T,v),w=_T(v.referencedTable),q=T[w],r=`${A}_${G}`,p=BS(...c.fields.map((fn,xn)=>Hf(bn(c.references[xn],r),bn(fn,A)))),ko=this.buildRelationalQueryWithoutPK({fullSchema:o,schema:n,tableNamesMap:T,table:o[q],tableConfig:n[q],queryConfig:K(v,FT)?U===!0?{limit:1}:{...U,limit:1}:U,tableAlias:r,joinOn:p,nestedQueryRelation:v}),Oo=J`${J.identifier(r)}.${J.identifier("data")}`.as(G);Q.push({on:J`true`,table:new ro(ko.sql,{},r),alias:r,joinType:"left",lateral:!0}),y.push({dbKey:G,tsKey:G,field:Oo,relationTableTsKey:q,isJson:!0,selection:ko.selection})}}if(y.length===0)throw new Ef({message:`No fields selected for table "${f.tsName}" ("${A}")`});let H;if(E=BS(F,E),M){let Y=J`json_build_array(${J.join(y.map(({field:b,tsKey:a,isJson:X})=>X?J`${J.identifier(`${A}_${a}`)}.${J.identifier("data")}`:K(b,N.Aliased)?b.sql:b),J`, `)})`;if(K(M,jS))Y=J`coalesce(json_agg(${Y}${O.length>0?J` order by ${J.join(O,J`, `)}`:void 0}), '[]'::json)`;let B=[{dbKey:"data",tsKey:"data",field:Y.as("data"),isJson:!0,relationTableTsKey:f.tsName,selection:y}];if($!==void 0||W!==void 0||O.length>0)H=this.buildSelectQuery({table:Gf(S,A),fields:{},fieldsFlat:[{path:[],field:J.raw("*")}],where:E,limit:$,offset:W,orderBy:O,setOperators:[]}),E=void 0,$=void 0,W=void 0,O=[];else H=Gf(S,A);H=this.buildSelectQuery({table:K(H,io)?H:new ro(H,{},A),fields:{},fieldsFlat:B.map(({field:b})=>({path:[],field:K(b,Jo)?bn(b,A):b})),joins:Q,where:E,limit:$,offset:W,orderBy:O,setOperators:[]})}else H=this.buildSelectQuery({table:Gf(S,A),fields:{},fieldsFlat:y.map(({field:Y})=>({path:[],field:K(Y,Jo)?bn(Y,A):Y})),joins:Q,where:E,limit:$,offset:W,orderBy:O,setOperators:[]});return{tableTsKey:f.tsName,sql:H,selection:y}}}class DA{static[R]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class Sn{static[R]="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=o,S;if(this.fields)S=this.fields;else if(K(T,ro))S=Object.fromEntries(Object.keys(T._.selectedFields).map((f)=>[f,T[f]]));else if(K(T,cS))S=T[Ko].selectedFields;else if(K(T,N))S={};else S=uF(T);return new UA({table:T,fields:S,isPartialSelect:n,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class Kk extends DA{static[R]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:o,fields:n,isPartialSelect:T,session:S,dialect:f,withList:t,distinct:A}){super();this.config={withList:t,table:o,fields:{...n},distinct:A,setOperators:[]},this.isPartialSelect=T,this.session=S,this.dialect=f,this._={selectedFields:n},this.tableName=ln(o),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(o){return(n,T)=>{let S=this.tableName,f=ln(n);if(typeof f==="string"&&this.config.joins?.some((t)=>t.alias===f))throw new Error(`Alias "${f}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof S==="string")this.config.fields={[S]:this.config.fields};if(typeof f==="string"&&!K(n,N)){let t=K(n,ro)?n._.selectedFields:K(n,Mn)?n[Ko].selectedFields:n[I.Symbol.Columns];this.config.fields[f]=t}}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:f}),typeof f==="string")switch(o){case"left":{this.joinsNotNullableMap[f]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([t])=>[t,!1])),this.joinsNotNullableMap[f]=!0;break}case"inner":{this.joinsNotNullableMap[f]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([t])=>[t,!1])),this.joinsNotNullableMap[f]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");createSetOperator(o,n){return(T)=>{let S=typeof T==="function"?T(p0()):T;if(!CS(this.getSelectedFields(),S.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:o,isAll:n,rightSelect:S}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);intersectAll=this.createSetOperator("intersect",!0);except=this.createSetOperator("except",!1);exceptAll=this.createSetOperator("except",!0);addSetOperators(o){return this.config.setOperators.push(...o),this}where(o){if(typeof o==="function")o=o(new Proxy(this.config.fields,new 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 ro(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 UA extends Kk{static[R]="PgSelect";_prepare(o){let{session:n,config:T,dialect:S,joinsNotNullableMap:f,authToken:t}=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 A=Kn(T.fields),M=n.prepareQuery(S.sqlToQuery(this.getSQL()),A,o,!0);return M.joinsNotNullableMap=f,M.setToken(t)})}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)})}}dF(UA,[Tn]);function sT(o,n){return(T,S,...f)=>{let t=[S,...f].map((A)=>({type:o,isAll:n,rightSelect:A}));for(let A of t)if(!CS(T.getSelectedFields(),A.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return T.addSetOperators(t)}}var p0=()=>({union:Z0,unionAll:P0,intersect:g0,intersectAll:l0,except:e0,exceptAll:d0}),Z0=sT("union",!1),P0=sT("union",!0),g0=sT("intersect",!1),l0=sT("intersect",!0),e0=sT("except",!1),d0=sT("except",!0);class vS{static[R]="PgQueryBuilder";dialect;dialectConfig;constructor(o){this.dialect=K(o,GT)?o:void 0,this.dialectConfig=K(o,GT)?void 0:o}$with=(o,n)=>{let T=this;return{as:(f)=>{if(typeof f==="function")f=f(T);return new Proxy(new QS(f.getSQL(),n??("getSelectedFields"in f?f.getSelectedFields()??{}:{}),o,!0),new Vo({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...o){let n=this;function T(t){return new Sn({fields:t??void 0,session:void 0,dialect:n.getDialect(),withList:o})}function S(t){return new Sn({fields:t??void 0,session:void 0,dialect:n.getDialect(),distinct:!0})}function f(t,A){return new Sn({fields:A??void 0,session:void 0,dialect:n.getDialect(),distinct:{on:t}})}return{select:T,selectDistinct:S,selectDistinctOn:f}}select(o){return new Sn({fields:o??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(o){return new Sn({fields:o??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(o,n){return new Sn({fields:n??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:o}})}getDialect(){if(!this.dialect)this.dialect=new GT(this.dialectConfig);return this.dialect}}class ef{constructor(o,n,T,S,f){this.table=o,this.session=n,this.dialect=T,this.withList=S,this.overridingSystemValue_=f}static[R]="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 S={},f=this.table[I.Symbol.Columns];for(let t of Object.keys(T)){let A=T[t];S[t]=K(A,N)?A:new Rn(A,f[t])}return S});return new VA(this.table,n,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(o){let n=typeof o==="function"?o(new vS):o;if(!K(n,N)&&!CS(this.table[Xf],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 VA(this.table,n,this.session,this.dialect,this.withList,!0)}}class VA extends Tn{constructor(o,n,T,S,f,t,A){super();this.session=T,this.dialect=S,this.config={table:o,values:n,withList:f,select:t,overridingSystemValue_:A}}static[R]="PgInsert";config;returning(o=this.config.table[I.Symbol.Columns]){return this.config.returningFields=o,this.config.returning=Kn(o),this}onConflictDoNothing(o={}){if(o.target===void 0)this.config.onConflict=J`do nothing`;else{let n="";n=Array.isArray(o.target)?o.target.map((S)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(S))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(o.target));let T=o.where?J` where ${o.where}`:void 0;this.config.onConflict=J`(${J.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?J` where ${o.where}`:void 0,T=o.targetWhere?J` where ${o.targetWhere}`:void 0,S=o.setWhere?J` where ${o.setWhere}`:void 0,f=this.dialect.buildUpdateSet(this.config.table,zf(this.config.table,o.set)),t="";return t=Array.isArray(o.target)?o.target.map((A)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(A))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(o.target)),this.config.onConflict=J`(${J.raw(t)})${T} do update set ${f}${n}${S}`,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)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new Vo({alias:co(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class BA extends Tn{constructor(o,n,T){super();this.session=n,this.dialect=T,this.config={view:o}}static[R]="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 df{constructor(o,n,T,S){this.table=o,this.session=n,this.dialect=T,this.withList=S}static[R]="PgUpdateBuilder";authToken;setToken(o){return this.authToken=o,this}set(o){return new Xk(this.table,zf(this.table,o),this.session,this.dialect,this.withList).setToken(this.authToken)}}class Xk extends Tn{constructor(o,n,T,S,f){super();this.session=T,this.dialect=S,this.config={set:n,table:o,withList:f,joins:[]},this.tableName=ln(o),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[R]="PgUpdate";config;tableName;joinsNotNullableMap;from(o){let n=o,T=ln(n);if(typeof T==="string")this.joinsNotNullableMap[T]=!0;return this.config.from=n,this}getTableLikeFields(o){if(K(o,io))return o[I.Symbol.Columns];else if(K(o,ro))return o._.selectedFields;return o[Ko].selectedFields}createJoin(o){return(n,T)=>{let S=ln(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(typeof T==="function"){let f=this.config.from&&!K(this.config.from,N)?this.getTableLikeFields(this.config.from):void 0;T=T(new Proxy(this.config.table[I.Symbol.Columns],new Vo({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),f&&new Proxy(f,new Vo({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}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");where(o){return this.config.where=o,this}returning(o){if(!o){if(o=Object.assign({},this.config.table[I.Symbol.Columns]),this.config.from){let n=ln(this.config.from);if(typeof n==="string"&&this.config.from&&!K(this.config.from,N)){let T=this.getTableLikeFields(this.config.from);o[n]=T}for(let T of this.config.joins){let S=ln(T.table);if(typeof S==="string"&&!K(T.table,N)){let f=this.getTableLikeFields(T.table);o[S]=f}}}}return this.config.returningFields=o,this.config.returning=Kn(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)};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new Vo({alias:co(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class qS extends N{constructor(o){super(qS.buildEmbeddedCount(o.source,o.filters).queryChunks);this.params=o,this.mapWith(Number),this.session=o.session,this.sql=qS.buildCount(o.source,o.filters)}sql;token;static[R]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(o,n){return J`(select count(*) from ${o}${J.raw(" where ").if(n)}${n})`}static buildCount(o,n){return J`select count(*) as count from ${o}${J.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 LA{constructor(o,n,T,S,f,t,A){this.fullSchema=o,this.schema=n,this.tableNamesMap=T,this.table=S,this.tableConfig=f,this.dialect=t,this.session=A}static[R]="PgRelationalQueryBuilder";findMany(o){return new CA(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?o:{},"many")}findFirst(o){return new CA(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?{...o,limit:1}:{limit:1},"first")}}class CA extends Tn{constructor(o,n,T,S,f,t,A,M,F){super();this.fullSchema=o,this.schema=n,this.tableNamesMap=T,this.table=S,this.tableConfig=f,this.dialect=t,this.session=A,this.config=M,this.mode=F}static[R]="PgRelationalQuery";_prepare(o){return Wo.startActiveSpan("drizzle.prepareQuery",()=>{let{query:n,builtQuery:T}=this._toSQL();return this.session.prepareQuery(T,void 0,o,!0,(S,f)=>{let t=S.map((A)=>Nf(this.schema,this.tableConfig,A,n.selection,f));if(this.mode==="first")return t[0];return t})})}prepare(o){return this._prepare(o)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){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 IA extends Tn{constructor(o,n,T,S){super();this.execute=o,this.sql=n,this.query=T,this.mapBatchResult=S}static[R]="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 iS{constructor(o,n,T){if(this.dialect=o,this.session=n,this._=T?{schema:T.schema,fullSchema:T.fullSchema,tableNamesMap:T.tableNamesMap,session:n}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:n},this.query={},this._.schema)for(let[S,f]of Object.entries(this._.schema))this.query[S]=new LA(T.fullSchema,this._.schema,this._.tableNamesMap,T.fullSchema[S],f,o,n)}static[R]="PgDatabase";query;$with=(o,n)=>{let T=this;return{as:(f)=>{if(typeof f==="function")f=f(new vS(T.dialect));return new Proxy(new QS(f.getSQL(),n??("getSelectedFields"in f?f.getSelectedFields()??{}:{}),o,!0),new Vo({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(o,n){return new qS({source:o,filters:n,session:this.session})}with(...o){let n=this;function T(F){return new Sn({fields:F??void 0,session:n.session,dialect:n.dialect,withList:o})}function S(F){return new Sn({fields:F??void 0,session:n.session,dialect:n.dialect,withList:o,distinct:!0})}function f(F,y){return new Sn({fields:y??void 0,session:n.session,dialect:n.dialect,withList:o,distinct:{on:F}})}function t(F){return new df(F,n.session,n.dialect,o)}function A(F){return new ef(F,n.session,n.dialect,o)}function M(F){return new lf(F,n.session,n.dialect,o)}return{select:T,selectDistinct:S,selectDistinctOn:f,update:t,insert:A,delete:M}}select(o){return new Sn({fields:o??void 0,session:this.session,dialect:this.dialect})}selectDistinct(o){return new Sn({fields:o??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(o,n){return new Sn({fields:n??void 0,session:this.session,dialect:this.dialect,distinct:{on:o}})}update(o){return new df(o,this.session,this.dialect)}insert(o){return new ef(o,this.session,this.dialect)}delete(o){return new lf(o,this.session,this.dialect)}refreshMaterializedView(o){return new BA(o,this.session,this.dialect)}authToken;execute(o){let n=typeof o==="string"?J.raw(o):o.getSQL(),T=this.dialect.sqlToQuery(n),S=this.session.prepareQuery(T,void 0,void 0,!1);return new IA(()=>S.execute(void 0,this.authToken),n,T,(f)=>S.mapResult(f,!0))}transaction(o,n){return this.session.transaction(o,n)}}class Yk{constructor(o,n){this.unique=o,this.name=n}static[R]="PgIndexBuilderOn";on(...o){return new uf(o.map((n)=>{if(K(n,N))return n;n=n;let T=new mS(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 uf(o.map((n)=>{if(K(n,N))return n;n=n;let T=new mS(n.name,!!n.keyAsName,n.columnType,n.indexConfig);return n.indexConfig=n.defaultConfig,T}),this.unique,!0,this.name)}using(o,...n){return new uf(n.map((T)=>{if(K(T,N))return T;T=T;let S=new mS(T.name,!!T.keyAsName,T.columnType,T.indexConfig);return T.indexConfig=JSON.parse(JSON.stringify(T.defaultConfig)),S}),this.unique,!0,this.name,o)}}class uf{static[R]="PgIndexBuilder";config;constructor(o,n,T,S,f="btree"){this.config={name:S,columns:o,unique:n,only:T,method:f}}concurrently(){return this.config.concurrently=!0,this}with(o){return this.config.with=o,this}where(o){return this.config.where=o,this}build(o){return new Gk(this.config,o)}}class Gk{static[R]="PgIndex";config;constructor(o,n){this.config={...o,table:n}}}function jA(o){return new Yk(!0,o)}class NA{constructor(o){this.query=o}authToken;getQuery(){return this.query}mapResult(o,n){return o}setToken(o){return this.authToken=o,this}static[R]="PgPreparedQuery";joinsNotNullableMap}class hA{constructor(o){this.dialect=o}static[R]="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 bA extends iS{constructor(o,n,T,S=0){super(o,n,T);this.schema=T,this.nestedIndex=S}static[R]="PgTransaction";rollback(){throw new TA}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 J.raw(n.join(" "))}setTransaction(o){return this.session.execute(J`set transaction ${this.getTransactionConfigSQL(o)}`)}}class Ek extends NA{constructor(o,n,T,S,f,t,A){super({sql:n,params:T});this.client=o,this.queryString=n,this.params=T,this.logger=S,this.fields=f,this._isResponseInArrayMode=t,this.customResultMapper=A}static[R]="PostgresJsPreparedQuery";async execute(o={}){return Wo.startActiveSpan("drizzle.execute",async(n)=>{let T=oA(this.params,o);n?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(T)}),this.logger.logQuery(this.queryString,T);let{fields:S,queryString:f,client:t,joinsNotNullableMap:A,customResultMapper:M}=this;if(!S&&!M)return Wo.startActiveSpan("drizzle.driver.execute",()=>{return t.unsafe(f,T)});let F=await Wo.startActiveSpan("drizzle.driver.execute",()=>{return n?.setAttributes({"drizzle.query.text":f,"drizzle.query.params":JSON.stringify(T)}),t.unsafe(f,T).values()});return Wo.startActiveSpan("drizzle.mapResponse",()=>{return M?M(F):F.map((y)=>eF(S,y,A))})})}all(o={}){return Wo.startActiveSpan("drizzle.execute",async(n)=>{let T=oA(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 pS extends hA{constructor(o,n,T,S={}){super(n);this.client=o,this.schema=T,this.options=S,this.logger=S.logger??new fA}static[R]="PostgresJsSession";logger;prepareQuery(o,n,T,S,f){return new Ek(this.client,o.sql,o.params,this.logger,n,S,f)}query(o,n){return this.logger.logQuery(o,n),this.client.unsafe(o,n).values()}queryObjects(o,n){return this.client.unsafe(o,n)}transaction(o,n){return this.client.begin(async(T)=>{let S=new pS(T,this.dialect,this.schema,this.options),f=new rA(this.dialect,S,this.schema);if(n)await f.setTransaction(n);return o(f)})}}class rA extends bA{constructor(o,n,T,S=0){super(o,n,T,S);this.session=n}static[R]="PostgresJsTransaction";transaction(o){return this.session.client.savepoint((n)=>{let T=new pS(n,this.dialect,this.schema,this.session.options),S=new rA(this.dialect,T,this.schema);return o(S)})}}class Hk extends iS{static[R]="PostgresJsDatabase"}function oS(o,n={}){let T=(F)=>F;for(let F of["1184","1082","1083","1114"])o.options.parsers[F]=T,o.options.serializers[F]=T;o.options.serializers["114"]=T,o.options.serializers["3802"]=T;let S=new GT({casing:n.casing}),f;if(n.logger===!0)f=new SA;else if(n.logger!==!1)f=n.logger;let t;if(n.schema){let F=e$(n.schema,u$);t={fullSchema:n.schema,schema:F.tables,tableNamesMap:F.tableNamesMap}}let A=new pS(o,S,t,{logger:f}),M=new Hk(S,A,t);return M.$client=o,M}function af(...o){if(typeof o[0]==="string"){let n=aT(o[0]);return oS(n,o[1])}if(aF(o[0])){let{connection:n,client:T,...S}=o[0];if(T)return oS(T,S);if(typeof n==="object"&&n.url!==void 0){let{url:t,...A}=n,M=aT(t,A);return oS(M,S)}let f=aT(n);return oS(f,S)}return oS(o[0],o[1])}((o)=>{function n(T){return oS({options:{parsers:{},serializers:{}}},T)}o.mock=n})(af||(af={}));var cA={};UR(cA,{users:()=>ET,userChanges:()=>a0,untrackedUserColumnNames:()=>u0,twoFactorMethod:()=>Uk,trackedUserColumnName:()=>Dk,trackableUserColumnNames:()=>Qk,role:()=>mk,players:()=>xA,passwordResetAttempts:()=>oW,loginHistory:()=>s0,games:()=>sf,banishedIps:()=>nW});function zk(o){return J`lower(${o})`}var mk=wf("role",["admin","user"]),ET=MT("users",{id:Jn().primaryKey().defaultRandom(),username:qo({length:16}).notNull(),email:qo({length:254}).notNull(),hash:qo({length:64}).notNull(),salt:qo({length:36}).notNull(),createdAt:Cn({withTimezone:!0}).notNull().defaultNow(),createdIp:qo({length:45}).notNull(),isActive:LS().notNull().default(!1),verifiedAt:Cn({withTimezone:!0}),userRole:mk().default("user")},(o)=>[jA("usernameUniqueIndex").on(zk(o.username)),jA("emailUniqueIndex").on(zk(o.email))]),u0=["id","createdAt","createdIp","isActive","salt","verifiedAt"],Qk=["username","email","hash","userRole"],Dk=wf("trackedUserColumnName",Qk),a0=MT("userChanges",{id:Jn().primaryKey().defaultRandom(),userId:Jn().notNull().references(()=>ET.id),changedAt:Cn({withTimezone:!0}).notNull().defaultNow(),changedIp:qo({length:45}).notNull(),changedColumn:Dk().notNull(),oldValue:qo({length:255}),newValue:qo({length:255})}),sf=MT("games",{id:Jn().primaryKey().defaultRandom()}),xA=MT("players",{userId:Jn().notNull().references(()=>ET.id),gameId:Jn().notNull().references(()=>sf.id),score:Df().notNull()},(o)=>[p$({name:"players_userId_gameId_pk",columns:[o.userId,o.gameId]})]),s0=MT("loginHistory",{id:Jn().primaryKey().defaultRandom(),userId:Jn().references(()=>ET.id),loginTime:Cn({withTimezone:!0}).notNull().defaultNow(),ipAddress:qo({length:45}).notNull(),userAgent:qo({length:1024}),successful:LS().notNull().default(!1)}),Uk=wf("twoFactorMethod",["email","phone"]),oW=MT("passwordResetAttempts",{id:Jn().primaryKey().defaultRandom(),userId:Jn().notNull().references(()=>ET.id),requestedIp:qo({length:45}).notNull(),requestedAt:Cn({withTimezone:!0}).notNull().defaultNow(),succeededIp:qo({length:45}),succeededAt:Cn({withTimezone:!0}),verificationMethod:Uk().notNull()}),nW=MT("banishedIps",{ip:qo({length:45}).primaryKey(),reason:qo({length:2048}).notNull(),banishedAt:Cn({withTimezone:!0}).notNull().defaultNow(),banishedUntil:Cn({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class vA{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(TW.resolve(__dirname,"notify_update.sql"));let o=[co(ET),co(sf),co(xA)];await this.sql`SELECT create_notify_triggers(${this.sql.array(o)})`,await this.sql.listen("table_update",(n)=>{let T=n.split(","),S=T[0],f=T[1],t=`${S}("${f}")`;if(this.observers.has(t))this.observers.get(t).next(t)})}constructor(o=!1,n={host:Vn.POSTGRES_HOST,port:Vn.POSTGRES_PORT,user:Vn.POSTGRES_USER,password:Vn.POSTGRES_PASSWORD,database:Vn.POSTGRES_DATABASE}){this.options=n,this.sql=aT(n),this.drizzle=af(this.sql,{schema:cA,logger:o})}observe(o,n){if(!this.observers.has(o))this.observers.set(o,new s);this.observers.get(o).subscribe("SINGLETON",n)}}var ot={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"},qA=nM(ot).map(([o])=>Eo.literal(Number(o))),SW=Eo.union([qA[0],qA[1],...qA]),Vk=Eo.tuple([SW,Eo.string()]);var pA=new jt,{logger:yn}=pA;Object.assign(console,yn,{log:yn.info});yn.info("ready");var iA=Ck(import.meta.dir,"..","app"),B3=new vA({logQuery(o,n){yn.info("\uD83D\uDCDD query",o,n)}});AW({hostname:"0.0.0.0",port:Vn.FRONTEND_PORT??3333,...$F??void 0,async fetch(o){try{let n=new Date,T=new URL(o.url);if(yn.info(o.method,T.pathname),T.pathname==="/")return new Response(Bun.file(Ck(iA,"index.html")));if(T.pathname==="/index.html")return Response.redirect("/");let S=fW(iA,T.pathname),f=tW(S);if(!f.startsWith(iA))throw[403,"Access Denied"];if(!await Bk(f).exists())return Response.redirect("/");return new Response(Bk(f))}catch(n){let T=Vk.safeParse(n);if(T.success){let[S,f]=T.data,A=`${ot[S]}. ${f}`;return yn.info(`\u274C ${S}: ${A}`),new Response(A,{status:S})}if(n instanceof Error)yn.error(n.message);else{let S=BT(n);yn.error("frontend server threw",S)}return new Response(ot[500],{status:500})}}});function nt(){yn.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{yn.info("\u2757 received SIGINT; exiting gracefully"),nt()});process.on("SIGTERM",()=>{yn.info("\u2757 received SIGTERM; exiting gracefully"),nt()});process.on("exit",()=>{yn.info("\u2757 received exit; exiting gracefully"),nt()});pA.on("timeToStop",()=>{yn.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),nt()});yn.info(`\uD83D\uDEEB frontend server running at http://localhost:${Vn.FRONTEND_PORT}/`);pA.emit("alive");