tempest.games 0.1.2 → 0.1.4

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.
@@ -0,0 +1,38 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+ var H4=Object.create;var{getPrototypeOf:_4,defineProperty:mW,getOwnPropertyNames:E4}=Object;var D4=Object.prototype.hasOwnProperty;var X7=(T,S,$)=>{$=T!=null?H4(_4(T)):{};const f=S||!T||!T.__esModule?mW($,"default",{value:T,enumerable:!0}):$;for(let M of E4(T))if(!D4.call(f,M))mW(f,M,{get:()=>T[M],enumerable:!0});return f};var w7=(T,S)=>()=>(S||T((S={exports:{}}).exports,S),S.exports);var y4=(T,S)=>{for(var $ in S)mW(T,$,{get:S[$],enumerable:!0,configurable:!0,set:(f)=>S[$]=()=>f})};function A7(T){return Object.entries(T)}function bf(T=Math.random){return T().toString(36).slice(2)}class gM extends Promise{fate;resolve;reject;done=!1;constructor(T){let S,$;super((f,M)=>{S=f,$=M});this.resolve=S,this.reject=$,this.use(T instanceof Promise?T:new Promise(T))}pass(T,S){if(T===this.fate)this.resolve(S),this.done=!0}fail(T,S){if(T===this.fate)this.reject(S),this.done=!0}use(T){if(T instanceof Promise){const S=T;this.fate=S,S.then(($)=>{this.pass(S,$)},($)=>{this.fail(S,$)})}else this.resolve(T),this.fate=void 0}}function Z(T){while(T.child!==null)T=T.child;return T}function Gk(T){while(T.parent!==null)T=T.parent;return T}function qf(T,S){const $=e(S),f=`${T.key}(${$})`,M=Q4[T.type],J={key:f,type:M};if(M==="molecule")Object.assign(J,{key:S,family:T});else Object.assign(J,{family:{key:T.key,subKey:$}});return Object.assign(J,{counterfeit:!0}),J}var Q4={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function XS(T){const S={key:T.key,type:T.type};if("family"in T)S.family=T.family;return S}function Zf(T){return Hk(wT.STORE,T)}function i$(T){return zk(wT.STORE,T)}function hW(...T){if(T.length===2)return RT(wT.STORE,...T);return RT(wT.STORE,...T)}var vW=(T)=>(S,$,f,M,...J)=>{console[T](`${S} ${$} "${f}" ${M}`,...J)},U4={error:vW("error"),info:vW("info"),warn:vW("warn")};class PW{T;S;$;constructor(T,S,$=U4){this.logLevel=T;this.filter=S;this.logger=$}error=(...T)=>{if((this.filter?.(...T)??!0)&&this.logLevel!==null)this.logger.error(...T)};info=(...T)=>{if((this.filter?.(...T)??!0)&&this.logLevel==="info")this.logger.info(...T)};warn=(...T)=>{if((this.filter?.(...T)??!0)&&this.logLevel!=="error"&&this.logLevel!==null)this.logger.warn(...T)}}function pJ(T){return oM(wT.STORE,T)}function tM(T){return nW(T,wT.STORE)}class LS{a;b;cardinality;relations=new Map;contents=new Map;isContent;makeContentKey=(T,S)=>`${T}:${S}`;warn;getRelatedKeys(T){return this.relations.get(T)}addRelation(T,S){let $=this.relations.get(T),f=this.relations.get(S);if($)$.add(S);else $=new Set([S]),this.relations.set(T,$);if(f)f.add(T);else f=new Set([T]),this.relations.set(S,f)}deleteRelation(T,S){const $=this.relations.get(T);if($){if($.delete(S),$.size===0)this.relations.delete(T);const f=this.relations.get(S);if(f){if(f.delete(T),f.size===0)this.relations.delete(S)}}}replaceRelationsUnsafely(T,S){this.relations.set(T,new Set(S));for(let $ of S){const f=new Set([T]);this.relations.set($,f)}}replaceRelationsSafely(T,S){const $=this.relations.get(T);if($)for(let f of $){const M=this.relations.get(f);if(M){if(M.size===1)this.relations.delete(f);else M.delete(T);this.contents.delete(this.makeContentKey(T,f))}}this.relations.set(T,new Set(S));for(let f of S){let M=this.relations.get(f);if(M)M.add(T);else M=new Set([T]),this.relations.set(f,M)}}getContentInternal(T){return this.contents.get(T)}setContent(T,S){this.contents.set(T,S)}deleteContent(T){this.contents.delete(T)}constructor(T,S){if(this.a=T.between[0],this.b=T.between[1],this.cardinality=T.cardinality,!S?.externalStore)this.relations=new Map(T.relations?.map(([$,f])=>[$,new Set(f)])),this.contents=new Map(T.contents);if(this.isContent=S?.isContent??null,S?.makeContentKey)this.makeContentKey=S.makeContentKey;if(S?.externalStore){const $=S.externalStore;if(this.has=(f,M)=>$.has(f,M),this.addRelation=(f,M)=>{$.addRelation(f,M)},this.deleteRelation=(f,M)=>{$.deleteRelation(f,M)},this.replaceRelationsSafely=(f,M)=>{$.replaceRelationsSafely(f,M)},this.replaceRelationsUnsafely=(f,M)=>{$.replaceRelationsUnsafely(f,M)},this.getRelatedKeys=(f)=>$.getRelatedKeys(f),$.getContent)this.getContentInternal=(f)=>{return $.getContent(f)},this.setContent=(f,M)=>{$.setContent(f,M)},this.deleteContent=(f)=>{$.deleteContent(f)};for(let[f,M]of T.relations??[])for(let J of M)this.addRelation(f,J);for(let[f,M]of T.contents??[])this.setContent(f,M)}if(S?.warn)this.warn=S.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([T,S])=>[T,[...S]]),contents:[...this.contents.entries()]}}set(T,...S){const $=typeof S[0]==="string"?S[0]:T[this.b],f=S[1]??typeof S[0]==="string"?void 0:S[0];switch(T=typeof T==="string"?T:T[this.a],this.cardinality){case"1:1":{const M=this.getRelatedKey(T);if(M&&M!==$)this.delete(M,T)}case"1:n":{const M=this.getRelatedKey($);if(M&&M!==T)this.delete(M,$)}}if(f){const M=this.makeContentKey(T,$);this.setContent(M,f)}return this.addRelation(T,$),this}delete(T,S){S=typeof S==="string"?S:T[this.b];const $=typeof T==="string"?T:T[this.a];if($===void 0&&typeof S==="string"){const f=this.getRelatedKeys(S);if(f)for(let M of f)this.delete(M,S)}if(typeof $==="string"&&S===void 0){const f=this.getRelatedKeys($);if(f)for(let M of f)this.delete($,M)}if(typeof $==="string"&&typeof S==="string"){this.deleteRelation($,S);const f=this.makeContentKey($,S);this.deleteContent(f)}return this}getRelatedKey(T){const S=this.getRelatedKeys(T);if(S){if(S.size>1)this.warn?.(`${S.size} related keys were found for key "${T}": (${[...S].map(($)=>`"${$}"`).join(", ")}). Only one related key was expected.`);for(let $ of S)return $}}replaceRelations(T,S,$){const f=!Array.isArray(S),M=f?Object.keys(S):S;if($?.reckless)this.replaceRelationsUnsafely(T,M);else this.replaceRelationsSafely(T,M);if(f)for(let J of M){const F=this.makeContentKey(T,J),W=S[J];this.setContent(F,W)}return this}getContent(T,S){const $=this.makeContentKey(T,S);return this.getContentInternal($)}getRelationEntries(T){const S=T[this.a],$=T[this.b];if(S!==void 0&&$===void 0){const f=this.getRelatedKeys(S);if(f)return[...f].map((M)=>{return[M,this.getContent(S,M)??null]})}if(S===void 0&&$!==void 0){const f=this.getRelatedKeys($);if(f)return[...f].map((M)=>{return[M,this.getContent(M,$)??null]})}return[]}has(T,S){if(S)return this.getRelatedKeys(T)?.has(S)??!1;return this.relations.has(T)}}class fT{Subscriber;subscribers=new Map;subscribe(T,S){return this.subscribers.set(T,S),()=>{this.unsubscribe(T)}}unsubscribe(T){this.subscribers.delete(T)}next(T){const S=this.subscribers.values();for(let $ of S)$(T)}}class cW extends fT{state;constructor(T){super();this.state=T}next(T){this.state=T,super.next(T)}}function nT(T){return"epoch"in T.transactionMeta}function AT(T){return"phase"in T.transactionMeta}var Ek=(T)=>{const S=Z(T);if(!AT(S)){T.logger.warn("\uD83D\uDC1E","transaction","???","abortTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}T.logger.info("\uD83E\uDE82","transaction",S.transactionMeta.update.key,"Aborting transaction"),S.parent.child=null};function iS(T){return T.type.split("_").map(V4).join(" ")}var V4=(T)=>T[0].toUpperCase()+T.slice(1);class _S extends Error{constructor(...T){const S=T[0],$=T.length===2?T[1]:T[2];if(T.length===2)super(`${iS(S)} ${e(S.key)} not found in store "${$.config.name}".`);else{const f=T[1];super(`${iS(S)} "${S.key}" member ${e(f)} not found in store "${$.config.name}".`)}}}function N$(T,S,$){return(...f)=>{const M=TT(T,$);if(M)return M.run(f,S);throw new _S(T,$)}}var uJ=(T)=>(S)=>T instanceof Function?T(S):T;var C$=(T,S)=>{if(S.valueMap.has(T.key))return S.logger.info("\uD83D\uDCD6",T.type,T.key,"reading cached value"),Dk(T,S);if(T.type==="selector"||T.type==="readonly_selector")return S.logger.info("\uD83E\uDDEE",T.type,T.key,"computing value"),T.get();const $=T.default instanceof Function?T.default():T.default;return S.logger.info("\uD83D\uDC81","atom",T.key,"could not find cached value; using default",$),T.default instanceof Function?T.default():T.default};var yk=(T,S)=>{if(T.operation.open){const $=performance.now();return T.logger.info("\u2757",S.type,S.key,`deferring setState at T-${$} until setState for "${T.operation.token.key}" is done`),$}T.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:S},T.logger.info("\u2B55",S.type,S.key,`operation start in store "${T.config.name}"${!AT(T)?"":` ${T.transactionMeta.phase} "${T.transactionMeta.update.key}"`}`)},Qk=(T)=>{if(T.operation.open)T.logger.info("\uD83D\uDD34",T.operation.token.type,T.operation.token.key,`operation done in store "${T.config.name}"`);T.operation={open:!1},T.on.operationClose.next(T.operation)},Uk=(T,S)=>{if(!T.operation.open)return T.logger.error("\uD83D\uDC1E","unknown",S,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return T.operation.done.has(S)},mf=(T,S)=>{if(!T.operation.open){T.logger.error("\uD83D\uDC1E","unknown",S,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}T.operation.done.add(S)};var Vk=(T,S,$)=>{switch(T.type){case"mutable_atom":$.logger.info("\uD83D\uDCE2",T.type,T.key,"is now (",S.newValue,") subscribers:",T.subject.subscribers);break;default:$.logger.info("\uD83D\uDCE2",T.type,T.key,"went (",S.oldValue,"->",S.newValue,") subscribers:",T.subject.subscribers)}T.subject.next(S)};var gW=(T,S)=>{const $=Z(S),f=$.selectorAtoms.getRelatedKeys(T.key);if($.logger.info("\uD83E\uDDF9",T.type,T.key,f?`evicting ${f.size} states downstream:`:"no downstream states",f??"to evict"),f){if($.operation.open)$.logger.info("\uD83E\uDDF9",T.type,T.key,`[ ${[...$.operation.done].join(", ")} ] already done`);for(let M of f){if(Uk($,M))continue;Lk(M,$),mf($,M)}}};function L4(T,S){if(Nk(S.newValue))return!1;if(T.includes("\uD83D\uDD0D"))return!1;return!0}var Bk=(T,S,$)=>{const{key:f}=T,M=Z($);if(!AT(M)||M.transactionMeta.phase!=="building"){$.logger.error("\uD83D\uDC1E","atom",f,"stowUpdate called outside of a transaction. This is probably a bug.");return}if(!L4(f,S))return;const F={type:"atom_update",key:f,...S};if(T.family)F.family=T.family;M.transactionMeta.update.updates.push(F),$.logger.info("\uD83D\uDCC1","atom",f,"stowed (",S.oldValue,"->",S.newValue,")")};var Ck=(T,S,$)=>{const f=C$(T,$);let M=f;if(T.type==="mutable_atom"&&AT($)){const{parent:F}=$;M=iM(T,F,$)}if(M=uJ(S)(M),$.logger.info("\uD83D\uDCDD","atom",T.key,"set to",M),M=ZS(T.key,M,T.subject,$),xk(T.key,$))jk(T.key,$);mf($,T.key),gW(T,$);const J={oldValue:f,newValue:M};if(nT($))Vk(T,J,$);else if($.parent){if($.on.transactionApplying.state===null)Bk(T,J,$);else if(T.key.startsWith("*")){const F=T.key.slice(1),W=$.atoms.get(F);let k=$.valueMap.get(F);if(W.type==="mutable_atom"&&AT($)){const{parent:w}=$;k=iM(W,w,$)}if(k.do(J.newValue)===null)gW(W,$)}}};var lJ=(T,S,$)=>{switch(T.type){case"atom":case"mutable_atom":Ck(T,S,$);break;case"selector":T.set(S);break}};function F$(T,S,$){const f={key:S.key,type:"atom_family"},M=T.families.get(S.key);if(M)T.logger.error("\u2757","atom_family",S.key,`Overwriting an existing ${iS(M)} "${M.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const J=new fT,W=Object.assign((k)=>{const X=e(k),w={key:S.key,subKey:X},K=`${S.key}(${X})`,O=Z(T),H=S.default,_={key:K,default:H instanceof Function?H(k):H};if(S.effects)_.effects=S.effects(k);const Q=ES(O,_,w);return J.next({type:"state_creation",token:Q}),Q},f,{subject:J,install:(k)=>F$(k,S),internalRoles:$});return T.families.set(S.key,W),T.defaults.set(S.key,S.default),f}function zk(T,S){if("mutable"in S)return pM(T,S);return F$(T,S)}function dJ(T,S){if(S.family){const $=T.families.get(S.family.key);if($)return $}}function RT(T,...S){let $,f,M;if(S.length===1){if($=S[0],$.type!=="molecule"){if(f=dJ(T,$)??null,f)M=$.family?uT($.family.subKey):null,$=GT(T,f,M)}}else{f=S[0],M=S[1];let J;if(f.type==="molecule_family")J=xT(T,f,M)??qf(f,M);else J=GT(T,f,M);$=J}if("counterfeit"in $&&"family"in $){f=$.type==="molecule"?TT($.family,T):T.families.get($.family.key);const J=$.type==="molecule"?$.key:$.family.subKey,F=T.disposalTraces.buffer.find((W)=>W?.key===$.key);switch(T.logger.error("\u274C",$.type,$.key,`could not be retrieved because it was not found in the store "${T.config.name}".`,F?`This state was previously disposed:\n${F.trace}`:"No previous disposal trace was found."),f.type){case"atom_family":case"mutable_atom_family":return T.defaults.get(f.key);case"selector_family":case"readonly_selector_family":{if(T.defaults.has(f.key))return T.defaults.get($.family.key);const W=TT(f,T).default(J);return T.defaults.set(f.key,W),W}case"molecule_family":throw new _S(f,J,T)}}switch($.type){case"atom":case"mutable_atom":case"selector":case"readonly_selector":return C$(TT($,T),T);case"molecule":return TT($,T).instance}}var rJ=(T,S)=>Z(S).atoms.has(T),B4=(T,S)=>Z(S).selectors.has(T),N4=(T,S)=>Z(S).readonlySelectors.has(T),Ik=(T,S)=>rJ(T,S)||B4(T,S)||N4(T,S);var aJ=(T,S)=>{return Z(S).selectorGraph.getRelationEntries({downstreamSelectorKey:T}).filter(([f,{source:M}])=>M!==T).map(([f,{source:M}])=>M).filter((f)=>Ik(f,S))};var oW=(T,S,$)=>{const f=[],M=aJ(T,$);while(M.length>0){const J=M.shift();if(S.has(J))continue;if(S.add(J),!rJ(J,$))M.push(...aJ(J,$));else if(!f.includes(J))f.push(J)}return f},bk=(T,S)=>{const $=T.key,f=aJ($,S),M=new Set;return f.flatMap((J)=>rJ(J,S)?J:oW(J,M,S))};var qk=(T,S,$,f)=>{const M=Z(f);if(S.type==="atom"||S.type==="mutable_atom")M.selectorAtoms.set({selectorKey:T,atomKey:S.key}),f.logger.info("\uD83D\uDD0D","selector",T,`discovers root atom "${S.key}"`);else{const J=oW(S.key,$,f);f.logger.info("\uD83D\uDD0D","selector",T,`discovers root atoms: [ ${J.map((F)=>`"${F}"`).join(", ")} ]`);for(let F of J)M.selectorAtoms=M.selectorAtoms.set({selectorKey:T,atomKey:F})}$.add(S.key)};var eJ=(T,S,$)=>({get:(...f)=>{const M=Z($);let J;if(f.length===2){const[k,X]=f;switch(k.type){case"molecule_family":return RT($,k,X);default:if($.config.lifespan==="ephemeral")J=GT($,k,X);else{const w=xT($,k,X);if(w)J=w;else throw new _S(k,X,$)}}}else[J]=f;if(J.type==="molecule")return RT($,J);const F=TT(J,$),W=C$(F,$);return $.logger.info("\uD83D\uDD0C","selector",T,`registers dependency ( "${J.key}" =`,W,")"),M.selectorGraph.set({upstreamSelectorKey:J.key,downstreamSelectorKey:T},{source:J.key}),qk(T,J,S,$),W},set:(...f)=>{let M,J;if(f.length===2)M=f[0],J=f[1];else{const k=f[0],X=f[1];J=f[2];const w=$.config.lifespan==="ephemeral"?GT($,k,X):xT($,k,X);if(!w)throw new _S(k,X,$);M=w}const F=Z($),W=TT(M,F);lJ(W,J,F)},find:(f,M)=>GT($,f,M),seek:(f,M)=>xT($,f,M),json:(f)=>gT($,f)});var uM=(T,S,$)=>{const f=Z(T),M=new fT,J=new Set,{get:F,find:W,seek:k,json:X}=eJ(S.key,J,f),w=()=>{const _=S.get({get:F,find:W,seek:k,json:X});return ZS(S.key,_,M,Z(T)),J.clear(),_},K={...S,subject:M,install:(_)=>uM(_,S,$),get:w,type:"readonly_selector",...$&&{family:$}};f.readonlySelectors.set(S.key,K);const O=w();T.logger.info("\u2728",K.type,K.key,"=",O);const H={key:S.key,type:"readonly_selector"};if($)H.family=$;return H};var lM=(T,S,$)=>{const f=Z(T),M=new fT,J=new Set,F=eJ(S.key,J,f),{find:W,get:k,seek:X,json:w}=F,K={find:W,get:k,seek:X,json:w},O=(V=S.get,U=Z(T))=>{const C=V(K);return ZS(S.key,C,M,U),J.clear(),C},_={...S,subject:M,install:(V)=>lM(V,S,$),get:O,set:(V)=>{const U=Z(T),C=O(S.get,U),B=uJ(V)(C);if(T.logger.info("\uD83D\uDCDD","selector",S.key,"set (",C,"->",B,")"),ZS(S.key,B,M,U),mf(U,S.key),nT(U))M.next({newValue:B,oldValue:C});S.set(F,B)},type:"selector",...$&&{family:$}};f.selectors.set(S.key,_);const Q=O();T.logger.info("\u2728",_.type,_.key,"=",Q);const N={key:S.key,type:"selector"};if($)N.family=$;return N};function tS(T,S){if("set"in S){const M=lM(T,S,void 0);return T.on.selectorCreation.next(M),M}const f=uM(T,S,void 0);return T.on.selectorCreation.next(f),f}function Zk(T,S){const $=Z(S),{key:f}=T,M=TT(T,$);if(!M.family)S.logger.error("\u274C","selector",f,"Standalone selectors cannot be disposed.");else{const J=$.molecules.get(M.family.subKey);if(J)J.tokens.delete(f);switch(T.type){case"selector":$.selectors.delete(f),TT({key:M.family.key,type:"selector_family"},S).subject.next({type:"state_disposal",token:T});break;case"readonly_selector":$.readonlySelectors.delete(f),TT({key:M.family.key,type:"readonly_selector_family"},S).subject.next({type:"state_disposal",token:T});break}if($.valueMap.delete(f),$.selectorAtoms.delete(f),$.selectorGraph.delete(f),S.logger.info("\uD83D\uDD25",T.type,f,"deleted"),AT($)&&$.transactionMeta.phase==="building")$.transactionMeta.update.updates.push({type:"state_disposal",token:T});else S.on.selectorDisposal.next(T)}}function O$(T,S,$){const f={key:S.key,type:"readonly_selector_family"},M=T.families.get(S.key);if(M)T.logger.error("\u2757","readonly_selector_family",S.key,`Overwriting an existing ${iS(M)} "${M.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const J=new fT,W=Object.assign((k)=>{const X=e(k),w={key:S.key,subKey:X},K=`${S.key}(${X})`,O=Z(T),H=uM(O,{key:K,get:S.get(k)},w);return J.next({type:"state_creation",token:H}),H},f,{internalRoles:$,subject:J,install:(k)=>O$(k,S),default:(k)=>{return S.get(k)({get:(...w)=>RT(T,...w),find:(w,K)=>GT(T,w,K),seek:(w,K)=>xT(T,w,K),json:(w)=>gT(T,w)})}});return T.families.set(S.key,W),f}function dM(T,S,$){const f={key:S.key,type:"selector_family"},M=T.families.get(S.key);if(M)T.logger.error("\u2757","selector_family",S.key,`Overwriting an existing ${iS(M)} "${M.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const J=new fT,W=Object.assign((k)=>{const X=e(k),w={key:S.key,subKey:X},K=`${S.key}(${X})`,O=Z(T),H=lM(O,{key:K,get:S.get(k),set:S.set(k)},w);return J.next({type:"state_creation",token:H}),H},f,{internalRoles:$,subject:J,install:(k)=>dM(k,S),default:(k)=>{return S.get(k)({get:(...w)=>RT(T,...w),find:(w,K)=>GT(T,w,K),seek:(w,K)=>xT(T,w,K),json:(w)=>gT(T,w)})}});return T.families.set(S.key,W),f}function oM(T,S){if("set"in S)return dM(T,S);return O$(T,S)}function sJ(T,S){let $;$=TT(T,S);const{family:f}=T;for(let F of $.joins.values())F.relations.delete($.key),F.molecules.delete($.stringKey);const M=[];for(let F of $.above.values())M.push(XS(F));const J=[];for(let F of $.tokens.values()){const W=F.family;J.push([W.key,S.valueMap.get(F.key)])}if(f){const F=TT(f,S),W={type:"molecule_disposal",subType:"classic",token:T,family:f,context:M,values:J};if(T.family)W.family=T.family;for(let X of $.tokens.values())OS(S,X);for(let X of $.below.values())if(X.dependsOn==="all")sJ(X,S);else if(X.above.delete($.stringKey),X.above.size===0)sJ(X,S);if($.below.clear(),AT(S)&&S.transactionMeta.phase==="building")S.transactionMeta.update.updates.push(W);else F.subject.next(W);S.molecules.delete($.stringKey)}for(let F of $.above.values())F.below.delete($.stringKey)}function mk(T,S){const $=new fT,f={type:"molecule_family",key:S.key,dependsOn:S.dependsOn??"all"},M={...f,subject:$,new:S.new};return T.moleculeFamilies.set(S.key,M),f}function pS(T,S,$){const f=R$($,S,T.key);T.tokens.set(f.key,f);const M=AT($)&&$.transactionMeta.phase==="building",J=$.moleculeInProgress===T.key;if(!M&&!J)T.subject.next({type:"state_creation",token:f});return f}class lT extends Set{mode="record";subject=new fT;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(T,S=0){super(T);if(T instanceof lT)this.parent=T,this.cacheUpdateNumber=T.cacheUpdateNumber;if(S)this.cacheLimit=S,this.cache=new Array(S),this.subscribe("auto cache",($)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=$})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(T){const S=new lT(T.members,T.cacheLimit);return S.cache=T.cache,S.cacheIdx=T.cacheIdx,S.cacheUpdateNumber=T.cacheUpdateNumber,S}add(T){const S=super.add(T);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${e(T)}`);return S}clear(){const T=this.mode==="record"?[...this]:null;if(super.clear(),T)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(T)}`)}delete(T){const S=super.delete(T);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${e(T)}`);return S}parent;child=null;transactionUpdates=null;transaction(T){this.mode="transaction",this.transactionUpdates=[],this.child=new lT(this);const S=this.child._subscribe("transaction",($)=>{this.transactionUpdates?.push($)});try{if(T(this.child)){for(let f of this.transactionUpdates)this.doStep(f);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch($){throw console.error("Failed to apply transaction to SetRTX:",$),$}finally{S(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(T,S){return this.subject.subscribe(T,S)}subscribe(T,S){return this.subject.subscribe(T,($)=>{S(`${this.cacheUpdateNumber}=${$}`)})}emit(T){this.subject.next(T)}doStep(T){const S=T.indexOf(":"),$=T.substring(0,S),f=T.substring(S+1);switch($){case"add":this.add(JSON.parse(f));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(f));break;case"tx":for(let M of f.split(";"))this.doStep(M)}}getUpdateNumber(T){const S=T.indexOf("=");return Number(T.substring(0,S))}do(T){const S=T.indexOf("="),$=Number(T.substring(0,S)),f=$-this.cacheUpdateNumber;if(f>0){if(f===1){this.mode="playback";const J=T.substring(S+1);return this.doStep(J),this.mode="record",this.cacheUpdateNumber=$,null}return this.cacheUpdateNumber+1}if(Math.abs(f)<this.cacheLimit){const J=this.cacheIdx+f;if(this.cache[J]===T)return null;this.mode="playback";let W=!1;while(!W){this.cacheIdx%=this.cacheLimit;const X=this.cache[this.cacheIdx];if(this.cacheIdx--,!X)return"OUT_OF_RANGE";this.undo(X),W=this.cacheIdx===J-1}const k=T.substring(S+1);return this.doStep(k),this.mode="record",this.cacheUpdateNumber=$,null}return"OUT_OF_RANGE"}undoStep(T){const S=T.indexOf(":"),$=T.substring(0,S),f=T.substring(S+1);switch($){case"add":this.delete(JSON.parse(f));break;case"del":this.add(JSON.parse(f));break;case"clear":{const M=JSON.parse(f);for(let J of M)this.add(J);break}case"tx":{const M=f.split(";");for(let J=M.length-1;J>=0;J--)this.undoStep(M[J])}}}undo(T){const S=T.indexOf("=");if(Number(T.substring(0,S))===this.cacheUpdateNumber){this.mode="playback";const f=T.substring(S+1);return this.undoStep(f),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function jT(T){return T[0].toUpperCase()+T.slice(1)}function TF(T,S,$=wT.STORE){return tW($).set(T.key,new pW(T,S,$)),{key:T.key,type:"join",a:T.between[0],b:T.between[1],cardinality:T.cardinality}}function tW(T){if("joins"in T&&T.joins instanceof Map)return T.joins;const S=new Map;return T.joins=S,S}function rM(T,S){const $=tW(S);let f=$.get(T.key);if(f===void 0){if(f=tW(wT.STORE).get(T.key)?.in(S),f===void 0)throw new Error(`Join "${T.key}" not found in store "${S.config.name}"`);$.set(T.key,f)}return f}function SF(T,S,$){const f=rM(T,$);let M;switch(T.cardinality){case"1:1":{const J=`${T.a}KeyOf${jT(T.b)}`,F=`${T.b}KeyOf${jT(T.a)}`;M={get[J](){const k=f.states[J];return f.retrieve(k,S)},get[F](){const k=f.states[F];return f.retrieve(k,S)}};const W=`${T.a}EntryOf${jT(T.b)}`;if(W in f.states){const k=`${T.b}EntryOf${jT(T.a)}`;Object.assign(M,{get[W](){const X=f.states[W];return f.retrieve(X,S)},get[k](){const X=f.states[k];return f.retrieve(X,S)}})}break}case"1:n":{const J=`${T.a}KeyOf${jT(T.b)}`,F=`${T.b}KeysOf${jT(T.a)}`;M={get[J](){const k=f.states[J];return f.retrieve(k,S)},get[F](){const k=f.states[F];return f.retrieve(k,S)}};const W=`${T.a}EntryOf${jT(T.b)}`;if(W in f.states){const k=`${T.b}EntriesOf${jT(T.a)}`;Object.assign(M,{get[W](){const X=f.states[W];return f.retrieve(X,S)},get[k](){const X=f.states[k];return f.retrieve(X,S)}})}break}case"n:n":{const J=`${T.a}KeysOf${jT(T.b)}`,F=`${T.b}KeysOf${jT(T.a)}`;M={get[J](){const k=f.states[J];return f.retrieve(k,S)},get[F](){const k=f.states[F];return f.retrieve(k,S)}};const W=`${T.a}EntriesOf${jT(T.b)}`;if(W in f.states){const k=`${T.b}EntriesOf${jT(T.a)}`;Object.assign(M,{get[W](){const X=f.states[W];return f.retrieve(X,S)},get[k](){const X=f.states[k];return f.retrieve(X,S)}})}}}return M}function hk(T,S){return SF(T,S,wT.STORE)}function $F(T,S,$){const f=rM(T,$),M=Z($);if(AT(M)){const{toolkit:J}=M.transactionMeta;f.transact(J,({relations:F})=>{S(F)})}else S(f.relations)}function C4(T,S){return rM(T,S).core.findRelatedKeysState}function vk(T){return C4(T,wT.STORE)}class pW{options;defaultContent;toolkit;retrieve;molecules=new Map;relations;states;core;transact(T,S){const $=this.toolkit;this.toolkit=T,S(this),this.toolkit=$}store;alternates;[Symbol.dispose](){this.alternates.delete(this.store.config.name)}in(T){const S=T.config.name,$=this.alternates.get(S);if($)return $;const f=new pW(this.options,this.defaultContent,T);return this.alternates.set(S,f),f.alternates=this.alternates,f}constructor(T,S,$=wT.STORE){this.store=$,this.options=T,this.defaultContent=S,this.alternates=new Map,this.alternates.set($.config.name,this),this.store.miscResources.set(`join:${T.key}`,this),this.retrieve=(D,z)=>{const y=this.toolkit.seek(D,z);if(y)return y;const j=this.molecules.get(e(z));if(j){const v=TT(D,$);return pS(j,v,$)}if($.config.lifespan==="immortal")throw new _S(D,z,$);return R$($,D,z)},this.toolkit={get:(...D)=>RT($,...D),set:(...D)=>{hT($,...D)},find:this.retrieve,seek:(...D)=>xT($,...D),json:(D)=>gT($,D),dispose:(...D)=>{OS($,...D)}};const f=T.between[0],M=T.between[1],J=pM($,{key:`${T.key}/relatedKeys`,default:()=>new lT,mutable:!0,fromJson:(D)=>lT.fromJSON(D),toJson:(D)=>D.toJSON()},["join","relations"]);this.core={findRelatedKeysState:J};const F=({get:D},z)=>D(this.retrieve(J,z)),W=(D,z,y)=>{const{set:j}=D,v=this.retrieve(J,z),G=this.retrieve(J,y);j(v,(m)=>m.add(y)),j(G,(m)=>m.add(z))},k=(D,z,y)=>{const{set:j}=D,v=this.retrieve(J,z),G=this.retrieve(J,y);let m,q;j(v,(d)=>{if(d.delete(y),d.size===0)m=`"${z}"`;return d}),j(G,(d)=>{if(d.delete(z),d.size===0)q=`"${y}"`;return d})},X=(D,z,y)=>{const{get:j,set:v}=D,G=this.retrieve(J,z),m=j(G);for(let q of m){if(y.includes(q))continue;const MT=this.retrieve(J,q);v(MT,(JT)=>{return JT.delete(z),JT})}v(G,(q)=>{return q.transaction((d)=>{d.clear();for(let MT of y){const JT=F(D,MT),yT=JT.has(z);if(this.relations.cardinality==="1:n"){const VS=[];for(let x of JT){if(x===z)continue;const i=F(D,x);if(i.delete(MT),i.size===0)VS.push(x)}if(!yT&&JT.size>0)JT.clear();for(let x of VS){const i=[MT,x].sort(),XT=`"${i[0]}:${i[1]}"`;this.molecules.delete(XT)}}if(!yT)JT.add(z);d.add(MT)}return!0}),q})},w=(D,z,y)=>{const{set:j}=D,v=this.retrieve(J,z);j(v,(G)=>{return G.transaction((m)=>{for(let q of y)m.add(q);return!0}),G});for(let G of y){const m=this.retrieve(J,G);j(m,(q)=>{return q.add(z),q})}return!0},K=(D,z,y)=>{const j=F(D,z);return y?j.has(y):j.size>0},O={getRelatedKeys:(D)=>F(this.toolkit,D),addRelation:(D,z)=>{W(this.toolkit,D,z)},deleteRelation:(D,z)=>{k(this.toolkit,D,z)},replaceRelationsSafely:(D,z)=>{X(this.toolkit,D,z)},replaceRelationsUnsafely:(D,z)=>{w(this.toolkit,D,z)},has:(D,z)=>K(this.toolkit,D,z)};let H,_,Q;if(S){_=F$($,{key:`${T.key}/content`,default:S},["join","content"]);const D={key:T.key,type:"join",a:T.between[0],b:T.between[1],cardinality:T.cardinality};Q=mk($,{key:`${T.key}/content-molecules`,new:class G{q;constructor(m,q){this.key=q}}});const z=({get:G},m)=>G(this.retrieve(_,m)),y=({set:G},m,q)=>{G(this.retrieve(_,m),q)},j=(G,m)=>{const q=$.molecules.get(`"${m}"`);if(q)this.toolkit.dispose(q),this.molecules.delete(`"${m}"`)};H=Object.assign(O,{getContent:(G)=>{return z(this.toolkit,G)},setContent:(G,m)=>{y(this.toolkit,G,m)},deleteContent:(G)=>{j(this.toolkit,G)}})}else H=O;const N=new LS(T,{externalStore:H,makeContentKey:(...D)=>{const z=D.sort(),y=`${z[0]}:${z[1]}`,[j,v]=z.map((G)=>this.molecules.get(e(G)));if($.config.lifespan==="immortal"&&j&&v){const G=Z($),m=G$(G,[j,v],Q,y);this.molecules.set(`"${y}"`,TT(m,G))}return y}}),V=()=>O$($,{key:`${T.key}/singleRelatedKey`,get:(D)=>({get:z})=>{const y=this.retrieve(J,D),j=z(y);for(let v of j)return v;return null}},["join","keys"]),U=()=>{return O$($,{key:`${T.key}/multipleRelatedKeys`,get:(D)=>({get:z})=>{const y=iW(J,$),j=this.retrieve(y,D);return z(j).members}},["join","keys"])},C=()=>O$($,{key:`${T.key}/singleRelatedEntry`,get:(D)=>({get:z})=>{const y=this.retrieve(J,D),j=z(y);for(let v of j){const G=N.makeContentKey(D,v),m=this.retrieve(_,G),q=z(m);return[v,q]}return null}},["join","entries"]),B=()=>O$($,{key:`${T.key}/multipleRelatedEntries`,get:(D)=>({get:z})=>{const y=iW(J,$),j=this.retrieve(y,D);return z(j).members.map((G)=>{const m=N.makeContentKey(D,G),q=this.retrieve(_,m),d=z(q);return[G,d]})}},["join","entries"]);switch(T.cardinality){case"1:1":{const D=V(),z=`${f}KeyOf${jT(M)}`,y=`${M}KeyOf${jT(f)}`,j={[z]:D,[y]:D};let v;if(S){const G=C(),m=`${f}EntryOf${jT(M)}`,q=`${M}EntryOf${jT(f)}`,d={[m]:G,[q]:G};v=Object.assign(j,d)}else v=j;this.relations=N,this.states=v;break}case"1:n":{const D=V(),z=U(),y=`${f}KeyOf${jT(M)}`,j=`${M}KeysOf${jT(f)}`,v={[y]:D,[j]:z};let G;if(S){const m=C(),q=B(),d=`${f}EntryOf${jT(M)}`,MT=`${M}EntriesOf${jT(f)}`,JT={[d]:m,[MT]:q};G=Object.assign(v,JT)}else G=v;this.relations=N,this.states=G;break}default:{const D=U(),z=`${f}KeysOf${jT(M)}`,y=`${M}KeysOf${jT(f)}`,j={[z]:D,[y]:D};let v;if(S){const G=B(),m=`${f}EntriesOf${jT(M)}`,q=`${M}EntriesOf${jT(f)}`,d={[m]:G,[q]:G};v=Object.assign(j,d)}else v=j;this.relations=N,this.states=v}}}}function fF(T){return{store:T}}class hf{S;type="molecule";stringKey;family;_dependsOn;get dependsOn(){if(this.family)return this.family.dependsOn;return this._dependsOn}subject=new fT;tokens=new Map;above=new Map;below=new Map;joins=new Map;instance;constructor(T,S,$){this.key=S;if(this.stringKey=e(S),$)this.family=$,this._dependsOn=$.dependsOn;if(T)for(let f of T)this.above.set(f.stringKey,f)}}function Pk(T){return T[0].toUpperCase()+T.slice(1)}function G$(T,S,$,f,...M){const J=Gk(T),F=Z(T),W=e(f);F.moleculeInProgress=W;const k=Array.isArray(S)?S:[S],X=k.map((N)=>{if(N instanceof hf)return N;const V=e(N.key),U=T.molecules.get(V);if(!U)throw new Error(`Molecule ${V} not found in store "${T.config.name}"`);return U}),w=new hf(X,f,$);F.molecules.set(W,w);for(let N of X)N.below.set(w.stringKey,w);const K={get:(...N)=>RT(Z(J),...N),set:(...N)=>{hT(Z(J),...N)},seek:(N,V)=>xT(Z(J),N,V),json:(N)=>gT(Z(J),N),run:(N,V=bf())=>N$(N,V,Z(T)),make:(N,V,U,...C)=>G$(Z(J),N,V,U,...C),dispose:(N)=>{OS(Z(J),N)},env:()=>fF(Z(J)),bond:(N,V)=>{if(N.type==="join"){const{as:U}=V,C=rM(N,J);C.molecules.set(W,w),w.joins.set(N.key,C);const B=O.subject.subscribe(`join:${N.key}-${W}`,(G)=>{if(G.type==="molecule_disposal"){if(e(G.token.key)===W)B(),C.molecules.delete(W)}});if(U===null)return;const D=N.a===U?N.b:N.a,z=hk(N,f),y=z[`${D}KeysOf${Pk(U)}`],j=z[`${D}EntriesOf${Pk(U)}`];let v={relatedKeys:y};if(j)v=Object.assign(v,{relatedEntries:j});return v}return pS(w,TT(N,J),Z(J))},claim:(N,V)=>{const{exclusive:U}=V,C=Z(T).molecules.get(e(N.key));if(C)if(U){for(let B of C.above.values())B.below.delete(C.stringKey);C.above.clear(),C.above.set(w.stringKey,w),w.below.set(C.stringKey,C)}else C.above.set(w.stringKey,w),w.below.set(C.stringKey,C)},spawn:(N,V,...U)=>G$(Z(T),[w],TT(N,T),V,...U)},O=TT($,T),H=O.new;w.instance=new H(K,f,...M);const _={type:"molecule",key:f,family:$},Q={type:"molecule_creation",subType:"classic",token:_,family:$,context:k,params:M};if(nT(F))O.subject.next(Q);else if(AT(F)&&F.on.transactionApplying.state===null)F.transactionMeta.update.updates.push(Q);return F.moleculeInProgress=null,_}function R$(T,S,$){const f=T.families.get(S.key);if(f===void 0)throw new _S(S,T);const M=f($),J=Z(T);if(M.family&&J.moleculeInProgress===null){if(nT(J))switch(M.type){case"atom":case"mutable_atom":T.on.atomCreation.next(M);break;case"selector":case"readonly_selector":T.on.selectorCreation.next(M);break}else if(AT(J)&&J.on.transactionApplying.state===null)J.transactionMeta.update.updates.push({type:"state_creation",token:M})}return M}function xT(T,S,$){const f=e($),M=`${S.key}(${f})`,J=Z(T);let F;switch(S.type){case"atom_family":case"mutable_atom_family":F=J.atoms.get(M);break;case"selector_family":F=J.selectors.get(M);break;case"readonly_selector_family":F=J.readonlySelectors.get(M);break;case"molecule_family":F=J.molecules.get(e($))}if(F)return XS(F);return F}function GT(T,S,$){let f=xT(T,S,$);if(f)return f;const M=T.molecules.get(e($));if(M)return pS(M,S,T);if(T.config.lifespan==="immortal"){const J=qf(S,$);return T.logger.error("\u274C",J.type,J.key,`was not found in store "${T.config.name}"; returned a counterfeit token.`),J}return f=R$(T,S,$),f}function OS(T,...S){let $,f;if(S.length===1)$=S[0],f=$.key;else{const J=S[0],F=S[1];$=J.type==="molecule_family"?xT(T,J,F)??qf(J,F):GT(T,J,F)}try{TT($,T)}catch(J){const F=T.disposalTraces.buffer.find((W)=>W?.key===$.key);T.logger.error("\u274C",$.type,$.key,`could not be disposed because it was not found in the store "${T.config.name}".`,F?`\n This state was most recently disposed\n${F.trace}`:"No previous disposal trace was found.");return}switch($.type){case"atom":case"mutable_atom":uW($,T);break;case"selector":case"readonly_selector":Zk($,T);break;case"molecule":sJ($,T);break}const{stack:M}=new Error;if(M){const J=M?.split("\n")?.slice(3)?.join("\n");T.disposalTraces.add({key:$.key,trace:J})}}function hT(T,...S){let $,f,M,J;if(S.length===2){if($=S[0],J=S[1],f=dJ(T,$)??null,f)M=$.family?uT($.family.subKey):null,$=GT(T,f,M)}else f=S[0],M=S[1],J=S[2],$=GT(T,f,M);if("counterfeit"in $){const k=T.disposalTraces.buffer.find((X)=>X?.key===$.key);T.logger.error("\u274C",$.type,$.key,`could not be set because it was not found in the store "${T.config.name}".`,k?`This state was previously disposed:\n${k.trace}`:"No previous disposal trace was found.");return}const F=yk(T,$);if(F){const k=T.on.operationClose.subscribe(`waiting to set "${$.key}" at T-${F}`,()=>{k(),T.logger.info("\uD83D\uDFE2",$.type,$.key,`resuming deferred setState from T-${F}`),hT(T,$,J)});return}const W=TT($,T);lJ(W,J,T),Qk(T)}function MF(T,S,$){const{key:f,newValue:M,oldValue:J}=S,F=T==="newValue"?M:J,W={key:f,type:"atom"};if(S.family)Object.assign(W,{family:S.family});hT($,W,F)}function lW(T,S,$){const f=e($);try{const M=[];let J;if(S==="root")M.push(T.molecules.get('"root"')),J="all";else if(S[0][0]===nk){J="any";const w=e(S),K=T.molecules.get(w);if(!K)throw new Error(`Molecule ${w} not found in store "${T.config.name}"`);M.push(K)}else if($[0][0]===nk){J="all";for(let K of S){const O=e(K),H=T.molecules.get(O);if(!H)throw new Error(`Molecule ${O} not found in store "${T.config.name}"`);M.push(H)}}else{J="any";const K=e(S),O=T.molecules.get(K);if(!O)throw new Error(`Molecule ${K} not found in store "${T.config.name}"`);M.push(O)}const F=new hf(M,$);F._dependsOn=J,T.molecules.set(f,F);for(let w of M)w.below.set(F.stringKey,F);const W={type:"molecule_creation",subType:"modern",key:F.key,provenance:S},k=Z(T);if(AT(k)&&k.transactionMeta.phase==="building")k.transactionMeta.update.updates.push(W);else k.on.moleculeCreationStart.next(W)}catch(M){if(M instanceof Error)T.logger.error("\u274C","molecule",f,"allocation failed:",M.message)}return $}function aM(T,S){const $=e(S),f=T.molecules.get($);if(!f)throw new Error(`Molecule ${$} not found in store "${T.config.name}"`);for(let X of f.joins.values())X.relations.delete(f.key),X.molecules.delete(f.stringKey);let M;if(f.above.size===1)M=f.above.values().next().value.key;else M=[...f.above.values()].map(({key:X})=>X);const J=[];for(let X of f.tokens.values()){const w=X.family;J.push([w.key,T.valueMap.get(X.key)])}for(let X of f.tokens.values())OS(T,X);for(let X of f.below.values())if(X.dependsOn==="all")aM(T,X.key);else if(X.above.delete(f.stringKey),X.above.size===0)aM(T,X.key);f.below.clear();const F={type:"molecule_disposal",subType:"modern",key:f.key,values:J,provenance:M},W=Z(T);if(AT(W)&&W.transactionMeta.phase==="building")W.transactionMeta.update.updates.push(F);else W.on.moleculeDisposal.next(F);W.molecules.delete(f.stringKey);for(let X of f.above.values())X.below.delete(f.stringKey)}var mG=Symbol("provenance"),nk="T$";function dW(T,S,$){switch(S){case"newValue":{ck(T,$);break}case"oldValue":{OS($,T.token);break}}}function rW(T,S,$){switch(S){case"newValue":{OS($,T.token);break}case"oldValue":{ck(T,$),$.valueMap.set(T.token.key,T.value);break}}}function ck(T,S){const{family:$}=T.token;if($){const f=S.families.get($.key);if(f)GT(S,f,uT($.subKey))}}function aW(T,S,$){switch(S){case"newValue":switch(T.subType){case"classic":G$($,T.context,T.family,T.token.key,...T.params);break;case"modern":lW($,T.provenance,T.key);break}break;case"oldValue":switch(T.subType){case"classic":OS($,T.token);break;case"modern":aM($,T.key);break}break}}function eW(T,S,$){switch(S){case"newValue":switch(T.subType){case"classic":OS($,T.token);break;case"modern":aM($,T.key);break}break;case"oldValue":switch(T.subType){case"classic":{const f=G$($,T.context,T.family,T.token.key);for(let[M,J]of T.values){const F=`${M}(${e(f.key)})`,W=TT(f,$),k=W.tokens.has(F),X=$.families.get(M);if(X&&!k)pS(W,X,$);$.valueMap.set(F,J)}}break;case"modern":{lW($,T.provenance,T.key);for(let[f,M]of T.values){const J=$.families.get(f);if(J){GT($,J,T.key);const F=`${f}(${e(T.key)})`;$.valueMap.set(F,M)}}}}break}}function JF(T,S,$){const f=T==="newValue"?S.updates:[...S.updates].reverse();for(let M of f)switch(M.type){case"atom_update":case"selector_update":MF(T,M,$);break;case"state_creation":dW(M,T,$);break;case"state_disposal":rW(M,T,$);break;case"molecule_creation":aW(M,T,$);break;case"molecule_disposal":eW(M,T,$);break;case"transaction_update":JF(T,M,$);break}}function gk(T,S,$){if(nT($)&&T)$.transactionMeta.epoch.set(T,S)}function ok(T,S,$){if(!nT($))return;const M=$.transactionMeta.actionContinuities.getRelatedKey(T);if(M!==void 0)$.transactionMeta.epoch.set(M,S)}var tk=(T,S)=>{const $=Z(S),{parent:f}=$;if(f===null||!AT($)||$.transactionMeta?.phase!=="building"){S.logger.warn("\uD83D\uDC1E","transaction","???","applyTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}$.transactionMeta.phase="applying",$.transactionMeta.update.output=T,f.child=null,f.on.transactionApplying.next($.transactionMeta);const{updates:M}=$.transactionMeta.update;if(S.logger.info("\uD83D\uDEC4","transaction",$.transactionMeta.update.key,`Applying transaction with ${M.length} updates:`,M),JF("newValue",$.transactionMeta.update,f),nT(f))ok($.transactionMeta.update.key,$.transactionMeta.update.epoch,f),TT({key:$.transactionMeta.update.key,type:"transaction"},S)?.subject.next($.transactionMeta.update),S.logger.info("\uD83D\uDEEC","transaction",$.transactionMeta.update.key,"Finished applying transaction.");else if(AT(f))f.transactionMeta.update.updates.push($.transactionMeta.update);f.on.transactionApplying.next(null)};function ik(T,S,$){if(!nT($))return;const{epoch:M,actionContinuities:J}=$.transactionMeta;if(J.set(T,S),!M.has(T))M.set(T,-1)}class mS extends Map{T;deleted=new Set;constructor(T){super();this.source=T}get(T){if(super.has(T))return super.get(T);if(!this.deleted.has(T)&&this.source.has(T))return this.source.get(T);return}set(T,S){return this.deleted.delete(T),super.set(T,S)}hasOwn(T){return super.has(T)}has(T){return!this.deleted.has(T)&&(super.has(T)||this.source.has(T))}delete(T){return this.deleted.add(T),super.delete(T)}}var pk=(T,S,$,f)=>{const M=Z($),J={parent:M,child:null,on:M.on,loggers:M.loggers,logger:M.logger,config:M.config,atoms:new mS(M.atoms),atomsThatAreDefault:new Set(M.atomsThatAreDefault),families:new mS(M.families),operation:{open:!1},readonlySelectors:new mS(M.readonlySelectors),timelines:new mS(M.timelines),timelineTopics:new LS(M.timelineTopics.toJSON()),trackers:new Map,transactions:new mS(M.transactions),selectorAtoms:new LS(M.selectorAtoms.toJSON()),selectorGraph:new LS(M.selectorGraph.toJSON(),{makeContentKey:(...X)=>X.sort().join(":")}),selectors:new mS(M.selectors),valueMap:new mS(M.valueMap),defaults:M.defaults,disposalTraces:$.disposalTraces.copy(),molecules:new mS(M.molecules),moleculeFamilies:new mS(M.moleculeFamilies),moleculeInProgress:M.moleculeInProgress,miscResources:new mS(M.miscResources)},F=uk(T,$),W={phase:"building",update:{type:"transaction_update",key:T,id:f,epoch:F===void 0?Number.NaN:F+1,updates:[],params:S,output:void 0},toolkit:{get:(...X)=>RT(k,...X),set:(...X)=>{hT(k,...X)},run:(X,w=bf())=>N$(X,w,k),find:(X,w)=>GT(k,X,w),seek:(X,w)=>xT(k,X,w),json:(X)=>gT(k,X),make:(X,w,K,...O)=>G$(k,X,w,K,...O),dispose:(...X)=>{OS(k,...X)},env:()=>fF(k)}},k=Object.assign(J,{transactionMeta:W});return M.child=k,$.logger.info("\uD83D\uDEEB","transaction",T,"Building transaction with params:",S),k};function nW(T,S){const $={key:T.key,type:"transaction",run:(J,F)=>{const W=pk(T.key,J,S,F);try{const k=Z(S),{toolkit:X}=W.transactionMeta,w=T.do(X,...J);return tk(w,k),w}catch(k){throw Ek(f),S.logger.warn("\uD83D\uDCA5","transaction",T.key,"caught:",k),k}},install:(J)=>nW(T,J),subject:new fT},f=Z(S);f.transactions.set($.key,$);const M=XS($);return S.on.transactionCreation.next(M),M}function uk(T,S){const $=nT(S),f=$?S.transactionMeta.actionContinuities.getRelatedKey(T):void 0;return $&&f!==void 0?S.transactionMeta.epoch.get(f):void 0}class FF{_buffer;_index=0;constructor(T){let S;if(typeof T==="number")S=T;else S=T.length;this._buffer=Array.from({length:S})}get buffer(){return this._buffer}get index(){return this._index}add(T){this._buffer[this._index]=T,this._index=(this._index+1)%this._buffer.length}copy(){const T=new FF([...this._buffer]);return T._index=this._index,T}}class lk{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;selectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new LS({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new LS({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});trackers=new Map;families=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new LS({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new LS({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new FF(100);molecules=new Map;moleculeFamilies=new Map;moleculeInProgress=null;miscResources=new Map;on={atomCreation:new fT,atomDisposal:new fT,selectorCreation:new fT,selectorDisposal:new fT,timelineCreation:new fT,transactionCreation:new fT,transactionApplying:new cW(null),operationClose:new fT,moleculeCreationStart:new fT,moleculeCreationDone:new fT,moleculeDisposal:new fT};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new PW("warn",(T,S,$)=>!$.includes("\uD83D\uDD0D"))];logger={error:(...T)=>{for(let S of this.loggers)S.error(...T)},info:(...T)=>{for(let S of this.loggers)S.info(...T)},warn:(...T)=>{for(let S of this.loggers)S.warn(...T)}};constructor(T,S=null){if(this.config={...S?.config,...T},S!==null){if(this.valueMap=new Map(S?.valueMap),this.operation={...S?.operation},nT(S))this.transactionMeta={epoch:new Map(S?.transactionMeta.epoch),actionContinuities:new LS(S?.transactionMeta.actionContinuities.toJSON())};for(let[,f]of S.families){if(f.internalRoles?.includes("mutable")||f.internalRoles?.includes("join"))continue;f.install(this)}const $=new Set;for(let[,f]of S.atoms){if($.has(f.key))continue;if(f.install(this),f.type==="mutable_atom"){const M=gT(S,f),J=z$(f);$.add(M.key),$.add(J.key)}}for(let[,f]of S.readonlySelectors)f.install(this);for(let[,f]of S.selectors){if($.has(f.key))continue;f.install(this)}for(let[,f]of S.transactions)f.install(this);for(let[,f]of S.timelines)f.install(this)}}}var wT={get STORE(){if(!globalThis.ATOM_IO_IMPLICIT_STORE)globalThis.ATOM_IO_IMPLICIT_STORE=new lk({name:"IMPLICIT_STORE",lifespan:"ephemeral"});return globalThis.ATOM_IO_IMPLICIT_STORE}};function TT(T,S){let $,f=S;while(f!==null){switch(T.type){case"atom":case"mutable_atom":$=f.atoms.get(T.key);break;case"selector":$=f.selectors.get(T.key);break;case"readonly_selector":$=f.readonlySelectors.get(T.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":$=f.families.get(T.key);break;case"timeline":$=f.timelines.get(T.key);break;case"transaction":$=f.transactions.get(T.key);break;case"molecule":$=f.molecules.get(e(T.key));break;case"molecule_family":$=f.moleculeFamilies.get(T.key);break}if($)return $;f=f.child}throw new _S(T,S)}var dk=(T,S)=>{const $=Z(S);if($.operation.open)return $.operation.prev.get(T.key);return $.valueMap.get(T.key)};var S0=(T,S)=>{const $=Z(S);return bk(T,S).map((M)=>{const J=$.atoms.get(M);if(J===void 0)throw new Error(`Atom "${M}", a dependency of selector "${T.key}", not found in store "${S.config.name}".`);return J.subject.subscribe(`${T.type}:${T.key}`,(F)=>{S.logger.info("\uD83D\uDCE2",T.type,T.key,"root",M,"went",F.oldValue,"->",F.newValue);const W=dk(T,$),k=C$(T,$);S.logger.info("\u2728",T.type,T.key,"went",W,"->",k),T.subject.next({newValue:k,oldValue:W})})})};function RS(T,S,$,f){function M(K){if(f.operation.open){const O=f.on.operationClose.subscribe(`state subscription ${$}`,()=>{O(),S(K)})}else S(K)}const J=TT(T,f);f.logger.info("\uD83D\uDC40",J.type,J.key,`Adding subscription "${$}"`);const F=J.type==="selector"||J.type==="readonly_selector";let W=null,k=M;if(F)W=S0(J,f),k=(K)=>{if(W)W.length=0,W.push(...S0(J,f));M(K)};const X=J.subject.subscribe($,k);return()=>{if(f.logger.info("\uD83D\uDE48",J.type,J.key,`Removing subscription "${$}"`),X(),W)for(let K of W)K()}}var sW=(T,S,$,f)=>{const M=TT(T,f);f.logger.info("\uD83D\uDC40","timeline",T.key,`Adding subscription "${$}"`);const J=M.subject.subscribe($,S);return()=>{f.logger.info("\uD83D\uDE48","timeline",T.key,`Removing subscription "${$}" from timeline`),J()}};var T0=(T,S,$,f)=>{const M=TT(T,f);f.logger.info("\uD83D\uDC40","transaction",T.key,`Adding subscription "${$}"`);const J=M.subject.subscribe($,S);return()=>{f.logger.info("\uD83D\uDE48","transaction",T.key,`Removing subscription "${$}"`),J()}};class x${Update;initializeState(T,S){const $=`*${T.key}`;S.atoms.delete($),S.valueMap.delete($);const f=T.family?{key:`*${T.family.key}`,subKey:T.family.subKey}:void 0,M=ES(S,{key:$,default:null},f);if(S.parent?.valueMap.has($)){const J=S.parent.valueMap.get($);S.valueMap.set($,J)}return M}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(T,S,$){const f=`tracker:${$.config.name}:${AT($)?$.transactionMeta.update.key:"main"}:${T.key}`,M=RT($,T);this.unsubscribeFromInnerValue=M.subscribe(f,(J)=>{hT($,S,J)}),this.unsubscribeFromState=RS(T,(J)=>{if(J.newValue!==J.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=J.newValue.subscribe(f,(F)=>{hT($,S,F)})},f,$)}updateCore(T,S,$){const f=`tracker:${$.config.name}:${AT($)?$.transactionMeta.update.key:"main"}:${T.key}`;RS(S,({newValue:M,oldValue:J})=>{const F=$.timelineTopics.getRelatedKey(S.key);if(F){if($.timelines.get(F)?.timeTraveling){const X=sW({key:F,type:"timeline"},(w)=>{X(),hT($,T,(K)=>{if(w==="redo"&&M)K.do(M);else if(w==="undo"&&J)K.undo(J);return K})},f,$);return}}const W=$.on.operationClose.subscribe(f,()=>{W();const k=RT($,T),X=M===null?-1:k.getUpdateNumber(M),w=X-k.cacheUpdateNumber;if(M&&w===1)hT($,T,(K)=>(K.do(M),K));else $.logger.info("\u274C","mutable_atom",T.key,`could not be updated. Expected update number ${k.cacheUpdateNumber+1}, but got ${X}`)})},f,$)}mutableState;latestUpdateState;dispose;constructor(T,S){this.mutableState=T;const $=Z(S);this.latestUpdateState=this.initializeState(T,$),this.observeCore(T,this.latestUpdateState,$),this.updateCore(T,this.latestUpdateState,$),$.trackers.set(T.key,this),this.dispose=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),$.trackers.delete(T.key)}}}function eM(T,S,$){T.logger.info("\uD83D\uDD28","atom",S.key,`creating in store "${T.config.name}"`);const f=Z(T),M=f.atoms.get(S.key);if(M&&M.type==="mutable_atom")return T.logger.error("\u274C","atom",S.key,"Tried to create atom, but it already exists in the store."),XS(M);const J=new fT,F={...S,type:"mutable_atom",install:(X)=>{return X.logger.info("\uD83D\uDEE0\uFE0F","atom",S.key,`installing in store "${X.config.name}"`),eM(X,S,$)},subject:J};if($)F.family=$;const W=S.default();f.atoms.set(F.key,F),WF(S.key,T),ZS(S.key,W,J,f);const k=XS(F);if(S.effects){let X=0;const w=[];for(let K of S.effects){const O=K({setSelf:(H)=>{hT(T,k,H)},onSet:(H)=>RS(k,H,`effect[${X}]`,T)});if(O)w.push(O);++X}F.cleanup=()=>{for(let K of w)K()}}if(new x$(k,T),!$)rk(k,S,T);return k}class $0{Update;latestUpdateAtoms;mutableAtoms;constructor(T,S){const $=F$(S,{key:`*${T.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=TT($,S),this.mutableAtoms=T,this.mutableAtoms.subject.subscribe(`store=${S.config.name}::tracker-atom-family`,(f)=>{if(f.token.family){const M=uT(f.token.family.subKey);xT(S,this.latestUpdateAtoms,M),new x$(f.token,S)}}),this.latestUpdateAtoms.subject.subscribe(`store=${S.config.name}::tracker-atom-family`,(f)=>{if(f.token.family){const M=uT(f.token.family.subKey),J=xT(S,this.mutableAtoms,M);if(J)new x$(J,S)}})}}function pM(T,S,$){const f={key:S.key,type:"mutable_atom_family"},M=T.families.get(S.key);if(M)T.logger.error("\u2757","mutable_atom_family",S.key,`Overwriting an existing ${iS(M)} "${M.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const J=new fT,W=Object.assign((k)=>{const X=e(k),w={key:S.key,subKey:X},K=`${S.key}(${X})`,O=Z(T),H={key:K,default:()=>S.default(k),toJson:S.toJson,fromJson:S.fromJson,mutable:!0};if(S.effects)H.effects=S.effects(k);const _=eM(O,H,w);return J.next({type:"state_creation",token:_}),_},f,{subject:J,install:(k)=>pM(k,S),toJson:S.toJson,fromJson:S.fromJson,internalRoles:$});return T.families.set(S.key,W),ak(W,S,T),new $0(W,T),f}var iW=(T,S)=>{const $=Z(S),f=`${T.key}:JSON`;return $.families.get(f)};var gT=(T,S)=>{if(S.family){const f=Z(T),J={key:`${S.family.key}:JSON`,type:"selector_family"},F=TT(J,f),W=JSON.parse(S.family.subKey);return GT(T,F,W)}return{type:"selector",key:`${S.key}:JSON`}};var z$=(T)=>{const $={type:"atom",key:`*${T.key}`};if(T.family)$.family={key:`*${T.family.key}`,subKey:T.family.subKey};return $};function Nk(T){return typeof T==="object"&&T!==null&&"do"in T&&"undo"in T&&"subscribe"in T}function iM(T,S,$){const f=S.valueMap.get(T.key),M=$.valueMap.get(T.key);if(f===M){if(f===void 0)return typeof T.default==="function"?T.default():T.default;S.logger.info("\uD83D\uDCC3","atom",T.key,"copying");const J=T.toJson(f),F=T.fromJson(J);return $.valueMap.set(T.key,F),new x$(T,S),F}return M}function ZS(T,S,$,f){const M=f.valueMap.get(T);if(M instanceof gM)M.use(S);if(S instanceof Promise){const J=new gM(S);return f.valueMap.set(T,J),J.then((F)=>{ZS(T,F,$,f),$.next({newValue:F,oldValue:J})}).catch((F)=>{f.logger.error("\uD83D\uDCA5","state",T,"rejected:",F)}),J}return f.valueMap.set(T,S),S}var Dk=(T,S)=>{let $=S.valueMap.get(T.key);if(T.type==="mutable_atom"&&AT(S)){const{parent:f}=S;$=iM(T,f,S)}return $},Lk=(T,S)=>{const $=S.valueMap.get(T);if($ instanceof gM){const f=$,M=S.selectors.get(T)??S.readonlySelectors.get(T);if(M)f.use(M.get());return}if(S.operation.open)S.operation.prev.set(T,$);S.valueMap.delete(T),S.logger.info("\uD83D\uDDD1","state",T,"evicted")};var xk=(T,S)=>{return Z(S).atomsThatAreDefault.has(T)},WF=(T,S)=>{const $=Z(S);$.atomsThatAreDefault=new Set($.atomsThatAreDefault).add(T)},jk=(T,S)=>{const $=Z(S);$.atomsThatAreDefault=new Set(Z(S).atomsThatAreDefault),$.atomsThatAreDefault.delete(T)};function ES(T,S,$){T.logger.info("\uD83D\uDD28","atom",S.key,`creating in store "${T.config.name}"`);const f=Z(T),M=f.atoms.get(S.key);if(M&&M.type==="atom")return T.logger.error("\u274C","atom",S.key,"Tried to create atom, but it already exists in the store."),XS(M);const J=new fT,F={...S,type:"atom",install:(X)=>{return X.logger.info("\uD83D\uDEE0\uFE0F","atom",S.key,`installing in store "${X.config.name}"`),ES(X,S,$)},subject:J};if($)F.family=$;let W=S.default;if(S.default instanceof Function)W=S.default();f.atoms.set(F.key,F),WF(S.key,T),ZS(S.key,W,J,f);const k=XS(F);if(S.effects){let X=0;const w=[];for(let K of S.effects){const O=K({setSelf:(H)=>{hT(T,k,H)},onSet:(H)=>RS(k,H,`effect[${X}]`,T)});if(O)w.push(O);++X}F.cleanup=()=>{for(let K of w)K()}}return k}function Hk(T,S){if("mutable"in S){const M=eM(T,S,void 0);return T.on.atomCreation.next(M),M}const f=ES(T,S,void 0);return T.on.atomCreation.next(f),f}function uW(T,S){const $=Z(S),{key:f}=T,M=TT(T,$);if(!M.family)S.logger.error("\u274C","atom",f,"Standalone atoms cannot be disposed.");else{M.cleanup?.();const J=S.valueMap.get(M.key);TT({key:M.family.key,type:"atom_family"},S).subject.next({type:"state_disposal",token:T,value:J});const W=$.molecules.get(M.family.subKey);if(W)W.tokens.delete(f);if($.atoms.delete(f),$.valueMap.delete(f),$.selectorAtoms.delete(f),$.atomsThatAreDefault.delete(f),S.timelineTopics.delete(f),T.type==="mutable_atom"){const k=z$(T);uW(k,S),S.trackers.delete(f)}if(S.logger.info("\uD83D\uDD25","atom",f,"deleted"),AT($)&&$.transactionMeta.phase==="building")$.transactionMeta.update.updates.push({type:"state_disposal",token:T});else S.on.atomDisposal.next(T)}}var rk=(T,S,$=wT.STORE)=>{return tS($,{key:`${T.key}:JSON`,get:({get:f})=>S.toJson(f(T)),set:({set:f},M)=>{f(T,S.fromJson(M))}})};function ak(T,S,$=wT.STORE){const f=dM($,{key:`${T.key}:JSON`,get:(J)=>({seek:F,get:W})=>{const k=F(T,J);if(k)return S.toJson(W(k));const X=e(J),w=$.molecules.get(X);if(w){const O=pS(w,T,$);return S.toJson(W(O))}if($.config.lifespan==="immortal")throw new Error(`No molecule found for key "${X}"`);const K=R$($,T,J);return S.toJson(W(K))},set:(J)=>({seek:F,set:W},k)=>{const X=F(T,J);if(X)W(X,S.fromJson(k));else{const w=e(J),K=$.molecules.get(w);if(K){const O=pS(K,T,$);W(O,S.fromJson(k))}else{if($.config.lifespan==="immortal")throw new Error(`No molecule found for key "${w}"`);W(R$($,T,J),S.fromJson(k))}}}},["mutable","json"]);return TT(T,$).subject.subscribe(`store=${$.config.name}::json-selector-family`,(J)=>{if(J.token.family)xT($,f,uT(J.token.family.subKey))}),f}var uT=(T)=>JSON.parse(T),e=(T)=>JSON.stringify(T),b_=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];class vf{T;listeners;globalListeners;handleEvent(T,...S){for(let f of this.globalListeners)f(T,...S);const $=this.listeners.get(T);if($)for(let f of $)f(...S)}id="no_id_retrieved";constructor(T){this.emit=T;this.listeners=new Map,this.globalListeners=new Set}on(T,S){const $=this.listeners.get(T);if($)$.add(S);else this.listeners.set(T,new Set([S]));return this}onAny(T){return this.globalListeners.add(T),this}off(T,S){const $=this.listeners.get(T);if($)if(S)$.delete(S);else this.listeners.delete(T);return this}offAny(T){return this.globalListeners.delete(T),this}}class f0 extends vf{T;S;$;incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";handleLog(T){if(Array.isArray(T)){const[S,...$]=T;switch(S){case"i":this.logger.info(this.id,this.key,...$);break;case"w":this.logger.warn(this.id,this.key,...$);break;case"e":this.logger.error(this.id,this.key,...$);break}}}constructor(T,S,$=console){super((f,...M)=>{const J=JSON.stringify([f,...M])+"\x03",F=(W)=>{if(W.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",F)};return this.process.stdin.once("error",F),this.process.stdin.write(J),this});this.process=T;this.key=S;this.logger=$;if(this.process=T,this.process.stdout.on("data",(f)=>{const M=f.toString();if(M==="\u2728")return;this.unprocessedEvents.push(...M.split("\x03"));const J=this.unprocessedEvents.shift();this.incompleteData+=J??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let F=uT(this.incompleteData);this.handleEvent(...F);while(this.unprocessedEvents.length>0){const W=this.unprocessedEvents.shift();if(W){if(this.unprocessedEvents.length===0)this.incompleteData=W;F=uT(W),this.handleEvent(...F)}}this.incompleteData=""}catch(F){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error(F)}}),this.process.stderr.on("data",(f)=>{const M=f.toString();this.unprocessedLogs.push(...M.split("\x03"));const J=this.unprocessedLogs.shift();this.incompleteLog+=J??"";try{let F=uT(this.incompleteLog);this.handleLog(F);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)F=uT(this.incompleteLog),this.handleLog(F)}catch(F){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error(F),console.error("\u274C\u274C\u274C\uFE0F")}}),T.pid)this.id=T.pid.toString()}}class ek extends vf{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(T){super((...S)=>{return this.out.next(S),this});this.id=T,this.in=new fT,this.out=new fT,this.in.subscribe("socket",(S)=>{this.handleEvent(...S)})}dispose(){for(let T of this.disposalFunctions)T()}}class M0 extends vf{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...T){this.process.stderr.write(e(T.map((S)=>S instanceof lT?`{ ${S.toJSON().members.join(" | ")} }`:S))+"\x03")}logger={info:(...T)=>{this.log("i",...T)},warn:(...T)=>{this.log("w",...T)},error:(...T)=>{this.log("e",...T)}};constructor(){super((T,...S)=>{const $=JSON.stringify([T,...S]);return this.process.stdout.write($+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(T)=>{const S=T.toString();this.unprocessedEvents.push(...S.split("\x03"));const $=this.unprocessedEvents.shift();this.incompleteData+=$??"";try{const f=uT(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",f),this.handleEvent(...f);while(this.unprocessedEvents.length>0){const M=this.unprocessedEvents.shift();if(M){if(this.unprocessedEvents.length===0)this.incompleteData=M;const J=uT(M);this.handleEvent(...J)}}this.incompleteData=""}catch(f){if(f instanceof Error)this.logger.error("\u2757",f.message,f.cause,f.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(T)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${T}`)}),process.on("end",()=>{this.logger.info("\uD83D\uDD25",this.id,"ended"),process.exit(0)}),process.on("SIGTERM",()=>{this.logger.error("\uD83D\uDD25",this.id,"terminated"),process.exit(0)}),process.on("SIGINT",()=>{this.logger.error("\uD83D\uDD25",this.id,"interrupted"),process.exit(0)}),process.pid)this.id=process.pid?.toString();this.on("user-joins",(T)=>{this.logger.info("\uD83D\uDC64","user",T,"joined");const S=new ek(`user:${T}`);this.relays.set(T,S),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let $ of this.relayServices){const f=$(S);if(f)S.disposalFunctions.push(f)}this.on(`user:${T}`,(...$)=>{S.in.next($)}),S.out.subscribe("socket",($)=>{this.emit(...$)})}),this.on("user-leaves",(T)=>{const S=this.relays.get(T);if(this.off(`relay:${T}`),S)S.dispose(),this.relays.delete(T)}),process.stdout.write("\u2728")}relay(T){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(T)}}function SE(T){const{key:S,config:$}=T,f=kF.create(S,$),{actions:M}=f;for(let J of M)ik(S,J.key,wT.STORE);return gk(S,-1,wT.STORE),f}class sk extends Map{set(T,S){if(this.has(T))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:T,value:S}),this;return super.set(T,S)}clear(){throw new Error("Cannot clear an InvariantMap")}}class kF{T;type="continuity";globals=[];actions=[];perspectives=[];constructor(T){this.key=T}static existing=new sk;static create(T,S){const $=new kF(T),{type:f,globals:M,actions:J,perspectives:F}=S($),W={type:f,key:T,globals:M,actions:J,perspectives:F};return kF.existing.set(T,W),W}add(...T){switch(T[0].type){case"atom":case"mutable_atom":this.globals.push(...T);break;case"transaction":this.actions.push(...T);break;case"atom_family":{const[$,f]=T;this.perspectives.push({type:"realtime_perspective",resourceAtoms:$,viewAtoms:f})}break}return this}}var FE=Zf({key:"usersInRoomIndex",mutable:!0,default:()=>new lT,toJson:(T)=>T.toJSON(),fromJson:(T)=>lT.fromJSON(T)}),J0=Zf({key:"roomIndex",default:()=>new lT,mutable:!0,toJson:(T)=>T.toJSON(),fromJson:(T)=>lT.fromJSON(T)}),x4={enteredAtEpoch:0},sM=TF({key:"usersInRooms",between:["room","user"],cardinality:"1:n"},x4),WE=pJ({key:"usersInMyRoomView",get:(T)=>({find:S})=>{const $=vk(sM);return[S($,T)]}});import{spawn as j4}from"child_process";var F0=i$({key:"roomArguments",default:["echo",["Hello World!"]]}),TX=pJ({key:"room",get:(T)=>async({get:S,find:$})=>{const f=$(F0,T),M=S(f),[J,F]=M,W=await new Promise((k)=>{const X=j4(J,F,{env:process.env}),w=(K)=>{if(K.toString()==="\u2728")X.stdout.off("data",w),k(X)};X.stdout.on("data",w)});return new f0(W,T)}});var DE=tM({key:"createRoom",do:({get:T,set:S,find:$},f,M,J)=>{const F=J?[M,J]:[M],W=$(F0,f);S(W,F),S(J0,(w)=>w.add(f));const k=$(TX,f);return T(k)}}),yE=tM({key:"joinRoom",do:(T,S,$,f)=>{const M={enteredAtEpoch:f};return $F(sM,(J)=>{J.set({room:S,user:$},M)},T.env().store),M}}),QE=tM({key:"leaveRoom",do:(T,S,$)=>{$F(sM,(f)=>{f.delete({room:S,user:$})},T.env().store)}}),UE=tM({key:"destroyRoom",do:(T,S)=>{$F(sM,($)=>{$.delete({room:S})},T.env().store),T.set(J0,($)=>($.delete(S),$))}});function W0(T,S){return S.map(($)=>{switch($.type){case"transaction_update":{const f=W0(T,$.updates);return{...$,updates:f}}default:return $}}).filter(($)=>{switch($.type){case"atom_update":case"selector_update":return T.includes($.key);case"state_creation":return T.includes($.token.key);case"molecule_creation":return!0;case"transaction_update":return!0}})}var BE=i$({key:"transactionRedactor",default:{occlude:(T)=>T}}),SX=i$({key:"unacknowledgedUpdates",default:()=>[]});var $X=i$({key:"sockets",default:null}),IE=Zf({key:"socketsIndex",mutable:!0,default:()=>new lT,toJson:(T)=>T.toJSON(),fromJson:(T)=>lT.fromJSON(T)}),bE=Zf({key:"usersIndex",mutable:!0,default:()=>new lT,toJson:(T)=>T.toJSON(),fromJson:(T)=>lT.fromJSON(T)}),k0=TF({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1"});function tE({socket:T,store:S=wT.STORE}){return function $(f){let M=T;const J=f.key,F=SF(k0,M.id,S).userKeyOfSocket,W=RT(S,F);if(!W)return S.logger.error("\u274C","continuity",J,`Tried to create a synchronizer for a socket (${M.id}) that is not connected to a user.`),()=>{};const k=SF(k0,W,S).socketKeyOfUser;RS(k,({newValue:V})=>{if(S.logger.info("\uD83D\uDC4B","continuity",J,`seeing ${W} on new socket ${V}`),V===null){S.logger.warn("\u274C","continuity",J,`User (${W}) is not connected to a socket, waiting for them to reappear.`);return}const U=GT(S,$X,V);M=RT(S,U);for(let B of w)M?.emit(`tx-new:${J}`,B)},`sync-continuity:${J}:${W}`,S);const X=GT(S,SX,W),w=RT(S,X),K=[],H=(()=>{const V=[];for(let U of f.perspectives){const{viewAtoms:C}=U,B=GT(S,C,W),D=RS(B,({oldValue:z,newValue:y})=>{const j=z.map((q)=>q.key),v=y.map((q)=>q.key),G=z.filter((q)=>!v.includes(q.key)),m=y.filter((q)=>!j.includes(q.key)).flatMap((q)=>{const d=q.type==="mutable_atom"?gT(S,q):q,MT=RT(S,d);return[d,MT]});if(S.logger.info("\uD83D\uDC41","atom",U.resourceAtoms.key,`${W} has a new perspective`,{oldKeys:j,newKeys:v,revealed:m,concealed:G}),m.length>0)M?.emit(`reveal:${J}`,m);if(G.length>0)M?.emit(`conceal:${J}`,G)},`sync-continuity:${J}:${W}:perspective:${U.resourceAtoms.key}`,S);V.push(D)}return()=>{for(let U of V)U()}})(),_=()=>{const V=[];for(let C of f.globals){const B=C.type==="mutable_atom"?gT(S,C):C,D=RT(S,B);V.push(B,D)}for(let C of f.perspectives){const{viewAtoms:B,resourceAtoms:D}=C,z=GT(S,B,W),y=RT(S,z);S.logger.info("\uD83D\uDC41","atom",D.key,`${W} can see`,{viewAtoms:B,resourceAtoms:D,userView:y});for(let j of y){const v=j.type==="mutable_atom"?gT(S,j):j,G=RT(S,v);V.push(v,G)}}const U=nT(S)?S.transactionMeta.epoch.get(J)??null:null;M?.emit(`continuity-init:${J}`,U,V);for(let C of f.actions){const B=T0(C,(D)=>{try{const z=f.globals.map((v)=>{if(v.type==="atom")return v.key;return z$(v).key}).concat(f.perspectives.flatMap((v)=>{const{viewAtoms:G}=v,m=GT(S,G,W);return RT(S,m).map((d)=>{return d.type==="mutable_atom"?"*"+d.key:d.key})})),y=W0(z,D.updates),j={...D,updates:y};hT(S,X,(v)=>{if(j)v.push(j),v.sort((G,m)=>G.epoch-m.epoch);return v}),M?.emit(`tx-new:${J}`,j)}catch(z){if(z instanceof Error)S.logger.error("\u274C","continuity",J,`failed to send update from transaction ${C.key} to ${W}`,z.message)}},`sync-continuity:${J}:${W}`,S);K.push(B)}};M.off(`get:${J}`,_),M.on(`get:${J}`,_);const Q=(V)=>{S.logger.info("\uD83D\uDECE\uFE0F","continuity",J,"received",V);const{key:U,id:C}=V,B=`tx-run:${U}:${C}`,D=`${B}:start`,z=`${B}:end`;performance.mark(D);try{N$({type:"transaction",key:U},C,S)(...V.params)}catch(m){if(m instanceof Error)S.logger.error("\u274C","continuity",J,`failed to run transaction ${U} with update ${C}`,m.message)}performance.mark(z);const y=performance.measure(B,D,z);S?.logger.info("\uD83D\uDE80","transaction",U,C,y.duration);const j=`valuesOfCardsView("${W}")`,v=S.selectorAtoms.getRelatedKeys(j),G=S.valueMap.get(j);S.logger.info("\uD83D\uDC41","continuity",J,`seeing ${W} card values`,{valuesOfCardsViewKey:j,rootsOfCardValueView:v,myCardValueView:G})};M.off(`tx-run:${J}`,Q),M.on(`tx-run:${J}`,Q);const N=(V)=>{if(S.logger.info("\uD83D\uDC4D","continuity",J,`${W} acknowledged epoch ${V}`),w[0]?.epoch===V)hT(S,X,(C)=>{return C.shift(),C})};return M?.on(`ack:${J}`,N),()=>{for(let V of K)V();M?.off(`ack:${J}`,N),H(),M?.off(`get:${J}`,_),M?.off(`tx-run:${J}`,Q)}}}var MX=Symbol("Let zodToJsonSchema decide on which parser to use"),fX={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},JX=(T)=>typeof T==="string"?{...fX,name:T}:{...fX,...T};var FX=(T)=>{const S=JX(T),$=S.name!==void 0?[...S.basePath,S.definitionPath,S.name]:S.basePath;return{...S,currentPath:$,propertyPath:void 0,seen:new Map(Object.entries(S.definitions).map(([f,M])=>[M._def,{def:M._def,path:[...S.basePath,S.definitionPath,f],jsonSchema:void 0}]))}};function X0(T,S,$,f){if(!f?.errorMessages)return;if($)T.errorMessage={...T.errorMessage,[S]:$}}function YT(T,S,$,f,M){T[S]=$,X0(T,S,f,M)}function b4(T){XX=T}function XF(){return XX}function n(T,S){const $=XF(),f=wF({issueData:S,data:T.data,path:T.path,errorMaps:[T.common.contextualErrorMap,T.schemaErrorMap,$,$===gf?void 0:gf].filter((M)=>!!M)});T.common.issues.push(f)}function KF(T,S,$,f){if($==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof S==="function"?T!==S||!f:!S.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return $==="m"?f:$==="a"?f.call(T):f?f.value:S.get(T)}function wX(T,S,$,f,M){if(f==="m")throw new TypeError("Private method is not writable");if(f==="a"&&!M)throw new TypeError("Private accessor was defined without a setter");if(typeof S==="function"?T!==S||!M:!S.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return f==="a"?M.call(T,$):M?M.value=$:S.set(T,$),$}function FT(T){if(!T)return{};const{errorMap:S,invalid_type_error:$,required_error:f,description:M}=T;if(S&&($||f))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(S)return{errorMap:S,description:M};return{errorMap:(F,W)=>{var k,X;const{message:w}=T;if(F.code==="invalid_enum_value")return{message:w!==null&&w!==void 0?w:W.defaultError};if(typeof W.data==="undefined")return{message:(k=w!==null&&w!==void 0?w:f)!==null&&k!==void 0?k:W.defaultError};if(F.code!=="invalid_type")return{message:W.defaultError};return{message:(X=w!==null&&w!==void 0?w:$)!==null&&X!==void 0?X:W.defaultError}},description:M}}function AX(T){let S="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";if(T.precision)S=`${S}\\.\\d{${T.precision}}`;else if(T.precision==null)S=`${S}(\\.\\d+)?`;return S}function u4(T){return new RegExp(`^${AX(T)}\$`)}function YX(T){let S=`${KX}T${AX(T)}`;const $=[];if($.push(T.local?"Z?":"Z"),T.offset)$.push("([+-]\\d{2}:?\\d{2})");return S=`${S}(${$.join("|")})`,new RegExp(`^${S}\$`)}function l4(T,S){if((S==="v4"||!S)&&o4.test(T))return!0;if((S==="v6"||!S)&&t4.test(T))return!0;return!1}function d4(T,S){const $=(T.toString().split(".")[1]||"").length,f=(S.toString().split(".")[1]||"").length,M=$>f?$:f,J=parseInt(T.toFixed(M).replace(".","")),F=parseInt(S.toFixed(M).replace(".",""));return J%F/Math.pow(10,M)}function Pf(T){if(T instanceof bT){const S={};for(let $ in T.shape){const f=T.shape[$];S[$]=dS.create(Pf(f))}return new bT({...T._def,shape:()=>S})}else if(T instanceof lS)return new lS({...T._def,type:Pf(T.element)});else if(T instanceof dS)return dS.create(Pf(T.unwrap()));else if(T instanceof _$)return _$.create(Pf(T.unwrap()));else if(T instanceof k$)return k$.create(T.items.map((S)=>Pf(S)));else return T}function O0(T,S){const $=j$(T),f=j$(S);if(T===S)return{valid:!0,data:T};else if($===c.object&&f===c.object){const M=OT.objectKeys(S),J=OT.objectKeys(T).filter((W)=>M.indexOf(W)!==-1),F={...T,...S};for(let W of J){const k=O0(T[W],S[W]);if(!k.valid)return{valid:!1};F[W]=k.data}return{valid:!0,data:F}}else if($===c.array&&f===c.array){if(T.length!==S.length)return{valid:!1};const M=[];for(let J=0;J<T.length;J++){const F=T[J],W=S[J],k=O0(F,W);if(!k.valid)return{valid:!1};M.push(k.data)}return{valid:!0,data:M}}else if($===c.date&&f===c.date&&+T===+S)return{valid:!0,data:T};else return{valid:!1}}function OX(T,S){return new Z$({values:T,typeName:b.ZodEnum,...FT(S)})}function RX(T,S={},$){if(T)return u$.create().superRefine((f,M)=>{var J,F;if(!T(f)){const W=typeof S==="function"?S(f):typeof S==="string"?{message:S}:S,k=(F=(J=W.fatal)!==null&&J!==void 0?J:$)!==null&&F!==void 0?F:!0,X=typeof W==="string"?{message:W}:W;M.addIssue({code:"custom",...X,fatal:k})}});return u$.create()}var OT;(function(T){T.assertEqual=(M)=>M;function S(M){}T.assertIs=S;function $(M){throw new Error}T.assertNever=$,T.arrayToEnum=(M)=>{const J={};for(let F of M)J[F]=F;return J},T.getValidEnumValues=(M)=>{const J=T.objectKeys(M).filter((W)=>typeof M[M[W]]!=="number"),F={};for(let W of J)F[W]=M[W];return T.objectValues(F)},T.objectValues=(M)=>{return T.objectKeys(M).map(function(J){return M[J]})},T.objectKeys=typeof Object.keys==="function"?(M)=>Object.keys(M):(M)=>{const J=[];for(let F in M)if(Object.prototype.hasOwnProperty.call(M,F))J.push(F);return J},T.find=(M,J)=>{for(let F of M)if(J(F))return F;return},T.isInteger=typeof Number.isInteger==="function"?(M)=>Number.isInteger(M):(M)=>typeof M==="number"&&isFinite(M)&&Math.floor(M)===M;function f(M,J=" | "){return M.map((F)=>typeof F==="string"?`'${F}'`:F).join(J)}T.joinValues=f,T.jsonStringifyReplacer=(M,J)=>{if(typeof J==="bigint")return J.toString();return J}})(OT||(OT={}));var K0;(function(T){T.mergeShapes=(S,$)=>{return{...S,...$}}})(K0||(K0={}));var c=OT.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),j$=(T)=>{switch(typeof T){case"undefined":return c.undefined;case"string":return c.string;case"number":return isNaN(T)?c.nan:c.number;case"boolean":return c.boolean;case"function":return c.function;case"bigint":return c.bigint;case"symbol":return c.symbol;case"object":if(Array.isArray(T))return c.array;if(T===null)return c.null;if(T.then&&typeof T.then==="function"&&T.catch&&typeof T.catch==="function")return c.promise;if(typeof Map!=="undefined"&&T instanceof Map)return c.map;if(typeof Set!=="undefined"&&T instanceof Set)return c.set;if(typeof Date!=="undefined"&&T instanceof Date)return c.date;return c.object;default:return c.unknown}},I=OT.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"]),I4=(T)=>{return JSON.stringify(T,null,2).replace(/"([^"]+)":/g,"$1:")};class BS extends Error{constructor(T){super();this.issues=[],this.addIssue=($)=>{this.issues=[...this.issues,$]},this.addIssues=($=[])=>{this.issues=[...this.issues,...$]};const S=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,S);else this.__proto__=S;this.name="ZodError",this.issues=T}get errors(){return this.issues}format(T){const S=T||function(M){return M.message},$={_errors:[]},f=(M)=>{for(let J of M.issues)if(J.code==="invalid_union")J.unionErrors.map(f);else if(J.code==="invalid_return_type")f(J.returnTypeError);else if(J.code==="invalid_arguments")f(J.argumentsError);else if(J.path.length===0)$._errors.push(S(J));else{let F=$,W=0;while(W<J.path.length){const k=J.path[W];if(W!==J.path.length-1)F[k]=F[k]||{_errors:[]};else F[k]=F[k]||{_errors:[]},F[k]._errors.push(S(J));F=F[k],W++}}};return f(this),$}static assert(T){if(!(T instanceof BS))throw new Error(`Not a ZodError: ${T}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,OT.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(T=(S)=>S.message){const S={},$=[];for(let f of this.issues)if(f.path.length>0)S[f.path[0]]=S[f.path[0]]||[],S[f.path[0]].push(T(f));else $.push(T(f));return{formErrors:$,fieldErrors:S}}get formErrors(){return this.flatten()}}BS.create=(T)=>{return new BS(T)};var gf=(T,S)=>{let $;switch(T.code){case I.invalid_type:if(T.received===c.undefined)$="Required";else $=`Expected ${T.expected}, received ${T.received}`;break;case I.invalid_literal:$=`Invalid literal value, expected ${JSON.stringify(T.expected,OT.jsonStringifyReplacer)}`;break;case I.unrecognized_keys:$=`Unrecognized key(s) in object: ${OT.joinValues(T.keys,", ")}`;break;case I.invalid_union:$="Invalid input";break;case I.invalid_union_discriminator:$=`Invalid discriminator value. Expected ${OT.joinValues(T.options)}`;break;case I.invalid_enum_value:$=`Invalid enum value. Expected ${OT.joinValues(T.options)}, received '${T.received}'`;break;case I.invalid_arguments:$="Invalid function arguments";break;case I.invalid_return_type:$="Invalid function return type";break;case I.invalid_date:$="Invalid date";break;case I.invalid_string:if(typeof T.validation==="object")if("includes"in T.validation){if($=`Invalid input: must include "${T.validation.includes}"`,typeof T.validation.position==="number")$=`${$} at one or more positions greater than or equal to ${T.validation.position}`}else if("startsWith"in T.validation)$=`Invalid input: must start with "${T.validation.startsWith}"`;else if("endsWith"in T.validation)$=`Invalid input: must end with "${T.validation.endsWith}"`;else OT.assertNever(T.validation);else if(T.validation!=="regex")$=`Invalid ${T.validation}`;else $="Invalid";break;case I.too_small:if(T.type==="array")$=`Array must contain ${T.exact?"exactly":T.inclusive?"at least":"more than"} ${T.minimum} element(s)`;else if(T.type==="string")$=`String must contain ${T.exact?"exactly":T.inclusive?"at least":"over"} ${T.minimum} character(s)`;else if(T.type==="number")$=`Number must be ${T.exact?"exactly equal to ":T.inclusive?"greater than or equal to ":"greater than "}${T.minimum}`;else if(T.type==="date")$=`Date must be ${T.exact?"exactly equal to ":T.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(T.minimum))}`;else $="Invalid input";break;case I.too_big:if(T.type==="array")$=`Array must contain ${T.exact?"exactly":T.inclusive?"at most":"less than"} ${T.maximum} element(s)`;else if(T.type==="string")$=`String must contain ${T.exact?"exactly":T.inclusive?"at most":"under"} ${T.maximum} character(s)`;else if(T.type==="number")$=`Number must be ${T.exact?"exactly":T.inclusive?"less than or equal to":"less than"} ${T.maximum}`;else if(T.type==="bigint")$=`BigInt must be ${T.exact?"exactly":T.inclusive?"less than or equal to":"less than"} ${T.maximum}`;else if(T.type==="date")$=`Date must be ${T.exact?"exactly":T.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(T.maximum))}`;else $="Invalid input";break;case I.custom:$="Invalid input";break;case I.invalid_intersection_types:$="Intersection results could not be merged";break;case I.not_multiple_of:$=`Number must be a multiple of ${T.multipleOf}`;break;case I.not_finite:$="Number must be finite";break;default:$=S.defaultError,OT.assertNever(T)}return{message:$}},XX=gf,wF=(T)=>{const{data:S,path:$,errorMaps:f,issueData:M}=T,J=[...$,...M.path||[]],F={...M,path:J};if(M.message!==void 0)return{...M,path:J,message:M.message};let W="";const k=f.filter((X)=>!!X).slice().reverse();for(let X of k)W=X(F,{data:S,defaultError:W}).message;return{...M,path:J,message:W}},q4=[];class wS{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(T,S){const $=[];for(let f of S){if(f.status==="aborted")return ST;if(f.status==="dirty")T.dirty();$.push(f.value)}return{status:T.value,value:$}}static async mergeObjectAsync(T,S){const $=[];for(let f of S){const M=await f.key,J=await f.value;$.push({key:M,value:J})}return wS.mergeObjectSync(T,$)}static mergeObjectSync(T,S){const $={};for(let f of S){const{key:M,value:J}=f;if(M.status==="aborted")return ST;if(J.status==="aborted")return ST;if(M.status==="dirty")T.dirty();if(J.status==="dirty")T.dirty();if(M.value!=="__proto__"&&(typeof J.value!=="undefined"||f.alwaysSet))$[M.value]=J.value}return{status:T.value,value:$}}}var ST=Object.freeze({status:"aborted"}),nf=(T)=>({status:"dirty",value:T}),GS=(T)=>({status:"valid",value:T}),A0=(T)=>T.status==="aborted",Y0=(T)=>T.status==="dirty",$J=(T)=>T.status==="valid",fJ=(T)=>typeof Promise!=="undefined"&&T instanceof Promise;var u;(function(T){T.errToObj=(S)=>typeof S==="string"?{message:S}:S||{},T.toString=(S)=>typeof S==="string"?S:S===null||S===void 0?void 0:S.message})(u||(u={}));var TJ,SJ;class rS{constructor(T,S,$,f){this._cachedPath=[],this.parent=T,this.data=S,this._path=$,this._key=f}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 WX=(T,S)=>{if($J(S))return{success:!0,data:S.value};else{if(!T.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const $=new BS(T.common.issues);return this._error=$,this._error}}}};class WT{constructor(T){this.spa=this.safeParseAsync,this._def=T,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(T){return j$(T.data)}_getOrReturnCtx(T,S){return S||{common:T.parent.common,data:T.data,parsedType:j$(T.data),schemaErrorMap:this._def.errorMap,path:T.path,parent:T.parent}}_processInputParams(T){return{status:new wS,ctx:{common:T.parent.common,data:T.data,parsedType:j$(T.data),schemaErrorMap:this._def.errorMap,path:T.path,parent:T.parent}}}_parseSync(T){const S=this._parse(T);if(fJ(S))throw new Error("Synchronous parse encountered promise.");return S}_parseAsync(T){const S=this._parse(T);return Promise.resolve(S)}parse(T,S){const $=this.safeParse(T,S);if($.success)return $.data;throw $.error}safeParse(T,S){var $;const f={common:{issues:[],async:($=S===null||S===void 0?void 0:S.async)!==null&&$!==void 0?$:!1,contextualErrorMap:S===null||S===void 0?void 0:S.errorMap},path:(S===null||S===void 0?void 0:S.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:T,parsedType:j$(T)},M=this._parseSync({data:T,path:f.path,parent:f});return WX(f,M)}async parseAsync(T,S){const $=await this.safeParseAsync(T,S);if($.success)return $.data;throw $.error}async safeParseAsync(T,S){const $={common:{issues:[],contextualErrorMap:S===null||S===void 0?void 0:S.errorMap,async:!0},path:(S===null||S===void 0?void 0:S.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:T,parsedType:j$(T)},f=this._parse({data:T,path:$.path,parent:$}),M=await(fJ(f)?f:Promise.resolve(f));return WX($,M)}refine(T,S){const $=(f)=>{if(typeof S==="string"||typeof S==="undefined")return{message:S};else if(typeof S==="function")return S(f);else return S};return this._refinement((f,M)=>{const J=T(f),F=()=>M.addIssue({code:I.custom,...$(f)});if(typeof Promise!=="undefined"&&J instanceof Promise)return J.then((W)=>{if(!W)return F(),!1;else return!0});if(!J)return F(),!1;else return!0})}refinement(T,S){return this._refinement(($,f)=>{if(!T($))return f.addIssue(typeof S==="function"?S($,f):S),!1;else return!0})}_refinement(T){return new hS({schema:this,typeName:b.ZodEffects,effect:{type:"refinement",refinement:T}})}superRefine(T){return this._refinement(T)}optional(){return dS.create(this,this._def)}nullable(){return _$.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return lS.create(this,this._def)}promise(){return d$.create(this,this._def)}or(T){return uf.create([this,T],this._def)}and(T){return lf.create(this,T,this._def)}transform(T){return new hS({...FT(this._def),schema:this,typeName:b.ZodEffects,effect:{type:"transform",transform:T}})}default(T){const S=typeof T==="function"?T:()=>T;return new ef({...FT(this._def),innerType:this,defaultValue:S,typeName:b.ZodDefault})}brand(){return new YF({typeName:b.ZodBranded,type:this,...FT(this._def)})}catch(T){const S=typeof T==="function"?T:()=>T;return new sf({...FT(this._def),innerType:this,catchValue:S,typeName:b.ZodCatch})}describe(T){return new this.constructor({...this._def,description:T})}pipe(T){return XJ.create(this,T)}readonly(){return TM.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var Z4=/^c[^\s-]{8,}$/i,m4=/^[0-9a-z]+$/,h4=/^[0-9A-HJKMNP-TV-Z]{26}$/,v4=/^[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,P4=/^[a-z0-9_-]{21}$/i,n4=/^[-+]?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)?)??$/,c4=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,g4="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",w0,o4=/^(?:(?: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])$/,t4=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,i4=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,KX="((\\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])))",p4=new RegExp(`^${KX}\$`);class uS extends WT{_parse(T){if(this._def.coerce)T.data=String(T.data);if(this._getType(T)!==c.string){const M=this._getOrReturnCtx(T);return n(M,{code:I.invalid_type,expected:c.string,received:M.parsedType}),ST}const $=new wS;let f=void 0;for(let M of this._def.checks)if(M.kind==="min"){if(T.data.length<M.value)f=this._getOrReturnCtx(T,f),n(f,{code:I.too_small,minimum:M.value,type:"string",inclusive:!0,exact:!1,message:M.message}),$.dirty()}else if(M.kind==="max"){if(T.data.length>M.value)f=this._getOrReturnCtx(T,f),n(f,{code:I.too_big,maximum:M.value,type:"string",inclusive:!0,exact:!1,message:M.message}),$.dirty()}else if(M.kind==="length"){const J=T.data.length>M.value,F=T.data.length<M.value;if(J||F){if(f=this._getOrReturnCtx(T,f),J)n(f,{code:I.too_big,maximum:M.value,type:"string",inclusive:!0,exact:!0,message:M.message});else if(F)n(f,{code:I.too_small,minimum:M.value,type:"string",inclusive:!0,exact:!0,message:M.message});$.dirty()}}else if(M.kind==="email"){if(!c4.test(T.data))f=this._getOrReturnCtx(T,f),n(f,{validation:"email",code:I.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="emoji"){if(!w0)w0=new RegExp(g4,"u");if(!w0.test(T.data))f=this._getOrReturnCtx(T,f),n(f,{validation:"emoji",code:I.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="uuid"){if(!v4.test(T.data))f=this._getOrReturnCtx(T,f),n(f,{validation:"uuid",code:I.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="nanoid"){if(!P4.test(T.data))f=this._getOrReturnCtx(T,f),n(f,{validation:"nanoid",code:I.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="cuid"){if(!Z4.test(T.data))f=this._getOrReturnCtx(T,f),n(f,{validation:"cuid",code:I.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="cuid2"){if(!m4.test(T.data))f=this._getOrReturnCtx(T,f),n(f,{validation:"cuid2",code:I.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="ulid"){if(!h4.test(T.data))f=this._getOrReturnCtx(T,f),n(f,{validation:"ulid",code:I.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="url")try{new URL(T.data)}catch(J){f=this._getOrReturnCtx(T,f),n(f,{validation:"url",code:I.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="regex"){if(M.regex.lastIndex=0,!M.regex.test(T.data))f=this._getOrReturnCtx(T,f),n(f,{validation:"regex",code:I.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="trim")T.data=T.data.trim();else if(M.kind==="includes"){if(!T.data.includes(M.value,M.position))f=this._getOrReturnCtx(T,f),n(f,{code:I.invalid_string,validation:{includes:M.value,position:M.position},message:M.message}),$.dirty()}else if(M.kind==="toLowerCase")T.data=T.data.toLowerCase();else if(M.kind==="toUpperCase")T.data=T.data.toUpperCase();else if(M.kind==="startsWith"){if(!T.data.startsWith(M.value))f=this._getOrReturnCtx(T,f),n(f,{code:I.invalid_string,validation:{startsWith:M.value},message:M.message}),$.dirty()}else if(M.kind==="endsWith"){if(!T.data.endsWith(M.value))f=this._getOrReturnCtx(T,f),n(f,{code:I.invalid_string,validation:{endsWith:M.value},message:M.message}),$.dirty()}else if(M.kind==="datetime"){if(!YX(M).test(T.data))f=this._getOrReturnCtx(T,f),n(f,{code:I.invalid_string,validation:"datetime",message:M.message}),$.dirty()}else if(M.kind==="date"){if(!p4.test(T.data))f=this._getOrReturnCtx(T,f),n(f,{code:I.invalid_string,validation:"date",message:M.message}),$.dirty()}else if(M.kind==="time"){if(!u4(M).test(T.data))f=this._getOrReturnCtx(T,f),n(f,{code:I.invalid_string,validation:"time",message:M.message}),$.dirty()}else if(M.kind==="duration"){if(!n4.test(T.data))f=this._getOrReturnCtx(T,f),n(f,{validation:"duration",code:I.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="ip"){if(!l4(T.data,M.version))f=this._getOrReturnCtx(T,f),n(f,{validation:"ip",code:I.invalid_string,message:M.message}),$.dirty()}else if(M.kind==="base64"){if(!i4.test(T.data))f=this._getOrReturnCtx(T,f),n(f,{validation:"base64",code:I.invalid_string,message:M.message}),$.dirty()}else OT.assertNever(M);return{status:$.value,value:T.data}}_regex(T,S,$){return this.refinement((f)=>T.test(f),{validation:S,code:I.invalid_string,...u.errToObj($)})}_addCheck(T){return new uS({...this._def,checks:[...this._def.checks,T]})}email(T){return this._addCheck({kind:"email",...u.errToObj(T)})}url(T){return this._addCheck({kind:"url",...u.errToObj(T)})}emoji(T){return this._addCheck({kind:"emoji",...u.errToObj(T)})}uuid(T){return this._addCheck({kind:"uuid",...u.errToObj(T)})}nanoid(T){return this._addCheck({kind:"nanoid",...u.errToObj(T)})}cuid(T){return this._addCheck({kind:"cuid",...u.errToObj(T)})}cuid2(T){return this._addCheck({kind:"cuid2",...u.errToObj(T)})}ulid(T){return this._addCheck({kind:"ulid",...u.errToObj(T)})}base64(T){return this._addCheck({kind:"base64",...u.errToObj(T)})}ip(T){return this._addCheck({kind:"ip",...u.errToObj(T)})}datetime(T){var S,$;if(typeof T==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:T});return this._addCheck({kind:"datetime",precision:typeof(T===null||T===void 0?void 0:T.precision)==="undefined"?null:T===null||T===void 0?void 0:T.precision,offset:(S=T===null||T===void 0?void 0:T.offset)!==null&&S!==void 0?S:!1,local:($=T===null||T===void 0?void 0:T.local)!==null&&$!==void 0?$:!1,...u.errToObj(T===null||T===void 0?void 0:T.message)})}date(T){return this._addCheck({kind:"date",message:T})}time(T){if(typeof T==="string")return this._addCheck({kind:"time",precision:null,message:T});return this._addCheck({kind:"time",precision:typeof(T===null||T===void 0?void 0:T.precision)==="undefined"?null:T===null||T===void 0?void 0:T.precision,...u.errToObj(T===null||T===void 0?void 0:T.message)})}duration(T){return this._addCheck({kind:"duration",...u.errToObj(T)})}regex(T,S){return this._addCheck({kind:"regex",regex:T,...u.errToObj(S)})}includes(T,S){return this._addCheck({kind:"includes",value:T,position:S===null||S===void 0?void 0:S.position,...u.errToObj(S===null||S===void 0?void 0:S.message)})}startsWith(T,S){return this._addCheck({kind:"startsWith",value:T,...u.errToObj(S)})}endsWith(T,S){return this._addCheck({kind:"endsWith",value:T,...u.errToObj(S)})}min(T,S){return this._addCheck({kind:"min",value:T,...u.errToObj(S)})}max(T,S){return this._addCheck({kind:"max",value:T,...u.errToObj(S)})}length(T,S){return this._addCheck({kind:"length",value:T,...u.errToObj(S)})}nonempty(T){return this.min(1,u.errToObj(T))}trim(){return new uS({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new uS({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new uS({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((T)=>T.kind==="datetime")}get isDate(){return!!this._def.checks.find((T)=>T.kind==="date")}get isTime(){return!!this._def.checks.find((T)=>T.kind==="time")}get isDuration(){return!!this._def.checks.find((T)=>T.kind==="duration")}get isEmail(){return!!this._def.checks.find((T)=>T.kind==="email")}get isURL(){return!!this._def.checks.find((T)=>T.kind==="url")}get isEmoji(){return!!this._def.checks.find((T)=>T.kind==="emoji")}get isUUID(){return!!this._def.checks.find((T)=>T.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((T)=>T.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((T)=>T.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((T)=>T.kind==="cuid2")}get isULID(){return!!this._def.checks.find((T)=>T.kind==="ulid")}get isIP(){return!!this._def.checks.find((T)=>T.kind==="ip")}get isBase64(){return!!this._def.checks.find((T)=>T.kind==="base64")}get minLength(){let T=null;for(let S of this._def.checks)if(S.kind==="min"){if(T===null||S.value>T)T=S.value}return T}get maxLength(){let T=null;for(let S of this._def.checks)if(S.kind==="max"){if(T===null||S.value<T)T=S.value}return T}}uS.create=(T)=>{var S;return new uS({checks:[],typeName:b.ZodString,coerce:(S=T===null||T===void 0?void 0:T.coerce)!==null&&S!==void 0?S:!1,...FT(T)})};class b$ extends WT{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(T){if(this._def.coerce)T.data=Number(T.data);if(this._getType(T)!==c.number){const M=this._getOrReturnCtx(T);return n(M,{code:I.invalid_type,expected:c.number,received:M.parsedType}),ST}let $=void 0;const f=new wS;for(let M of this._def.checks)if(M.kind==="int"){if(!OT.isInteger(T.data))$=this._getOrReturnCtx(T,$),n($,{code:I.invalid_type,expected:"integer",received:"float",message:M.message}),f.dirty()}else if(M.kind==="min"){if(M.inclusive?T.data<M.value:T.data<=M.value)$=this._getOrReturnCtx(T,$),n($,{code:I.too_small,minimum:M.value,type:"number",inclusive:M.inclusive,exact:!1,message:M.message}),f.dirty()}else if(M.kind==="max"){if(M.inclusive?T.data>M.value:T.data>=M.value)$=this._getOrReturnCtx(T,$),n($,{code:I.too_big,maximum:M.value,type:"number",inclusive:M.inclusive,exact:!1,message:M.message}),f.dirty()}else if(M.kind==="multipleOf"){if(d4(T.data,M.value)!==0)$=this._getOrReturnCtx(T,$),n($,{code:I.not_multiple_of,multipleOf:M.value,message:M.message}),f.dirty()}else if(M.kind==="finite"){if(!Number.isFinite(T.data))$=this._getOrReturnCtx(T,$),n($,{code:I.not_finite,message:M.message}),f.dirty()}else OT.assertNever(M);return{status:f.value,value:T.data}}gte(T,S){return this.setLimit("min",T,!0,u.toString(S))}gt(T,S){return this.setLimit("min",T,!1,u.toString(S))}lte(T,S){return this.setLimit("max",T,!0,u.toString(S))}lt(T,S){return this.setLimit("max",T,!1,u.toString(S))}setLimit(T,S,$,f){return new b$({...this._def,checks:[...this._def.checks,{kind:T,value:S,inclusive:$,message:u.toString(f)}]})}_addCheck(T){return new b$({...this._def,checks:[...this._def.checks,T]})}int(T){return this._addCheck({kind:"int",message:u.toString(T)})}positive(T){return this._addCheck({kind:"min",value:0,inclusive:!1,message:u.toString(T)})}negative(T){return this._addCheck({kind:"max",value:0,inclusive:!1,message:u.toString(T)})}nonpositive(T){return this._addCheck({kind:"max",value:0,inclusive:!0,message:u.toString(T)})}nonnegative(T){return this._addCheck({kind:"min",value:0,inclusive:!0,message:u.toString(T)})}multipleOf(T,S){return this._addCheck({kind:"multipleOf",value:T,message:u.toString(S)})}finite(T){return this._addCheck({kind:"finite",message:u.toString(T)})}safe(T){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:u.toString(T)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:u.toString(T)})}get minValue(){let T=null;for(let S of this._def.checks)if(S.kind==="min"){if(T===null||S.value>T)T=S.value}return T}get maxValue(){let T=null;for(let S of this._def.checks)if(S.kind==="max"){if(T===null||S.value<T)T=S.value}return T}get isInt(){return!!this._def.checks.find((T)=>T.kind==="int"||T.kind==="multipleOf"&&OT.isInteger(T.value))}get isFinite(){let T=null,S=null;for(let $ of this._def.checks)if($.kind==="finite"||$.kind==="int"||$.kind==="multipleOf")return!0;else if($.kind==="min"){if(S===null||$.value>S)S=$.value}else if($.kind==="max"){if(T===null||$.value<T)T=$.value}return Number.isFinite(S)&&Number.isFinite(T)}}b$.create=(T)=>{return new b$({checks:[],typeName:b.ZodNumber,coerce:(T===null||T===void 0?void 0:T.coerce)||!1,...FT(T)})};class q$ extends WT{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(T){if(this._def.coerce)T.data=BigInt(T.data);if(this._getType(T)!==c.bigint){const M=this._getOrReturnCtx(T);return n(M,{code:I.invalid_type,expected:c.bigint,received:M.parsedType}),ST}let $=void 0;const f=new wS;for(let M of this._def.checks)if(M.kind==="min"){if(M.inclusive?T.data<M.value:T.data<=M.value)$=this._getOrReturnCtx(T,$),n($,{code:I.too_small,type:"bigint",minimum:M.value,inclusive:M.inclusive,message:M.message}),f.dirty()}else if(M.kind==="max"){if(M.inclusive?T.data>M.value:T.data>=M.value)$=this._getOrReturnCtx(T,$),n($,{code:I.too_big,type:"bigint",maximum:M.value,inclusive:M.inclusive,message:M.message}),f.dirty()}else if(M.kind==="multipleOf"){if(T.data%M.value!==BigInt(0))$=this._getOrReturnCtx(T,$),n($,{code:I.not_multiple_of,multipleOf:M.value,message:M.message}),f.dirty()}else OT.assertNever(M);return{status:f.value,value:T.data}}gte(T,S){return this.setLimit("min",T,!0,u.toString(S))}gt(T,S){return this.setLimit("min",T,!1,u.toString(S))}lte(T,S){return this.setLimit("max",T,!0,u.toString(S))}lt(T,S){return this.setLimit("max",T,!1,u.toString(S))}setLimit(T,S,$,f){return new q$({...this._def,checks:[...this._def.checks,{kind:T,value:S,inclusive:$,message:u.toString(f)}]})}_addCheck(T){return new q$({...this._def,checks:[...this._def.checks,T]})}positive(T){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:u.toString(T)})}negative(T){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:u.toString(T)})}nonpositive(T){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:u.toString(T)})}nonnegative(T){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:u.toString(T)})}multipleOf(T,S){return this._addCheck({kind:"multipleOf",value:T,message:u.toString(S)})}get minValue(){let T=null;for(let S of this._def.checks)if(S.kind==="min"){if(T===null||S.value>T)T=S.value}return T}get maxValue(){let T=null;for(let S of this._def.checks)if(S.kind==="max"){if(T===null||S.value<T)T=S.value}return T}}q$.create=(T)=>{var S;return new q$({checks:[],typeName:b.ZodBigInt,coerce:(S=T===null||T===void 0?void 0:T.coerce)!==null&&S!==void 0?S:!1,...FT(T)})};class of extends WT{_parse(T){if(this._def.coerce)T.data=Boolean(T.data);if(this._getType(T)!==c.boolean){const $=this._getOrReturnCtx(T);return n($,{code:I.invalid_type,expected:c.boolean,received:$.parsedType}),ST}return GS(T.data)}}of.create=(T)=>{return new of({typeName:b.ZodBoolean,coerce:(T===null||T===void 0?void 0:T.coerce)||!1,...FT(T)})};class p$ extends WT{_parse(T){if(this._def.coerce)T.data=new Date(T.data);if(this._getType(T)!==c.date){const M=this._getOrReturnCtx(T);return n(M,{code:I.invalid_type,expected:c.date,received:M.parsedType}),ST}if(isNaN(T.data.getTime())){const M=this._getOrReturnCtx(T);return n(M,{code:I.invalid_date}),ST}const $=new wS;let f=void 0;for(let M of this._def.checks)if(M.kind==="min"){if(T.data.getTime()<M.value)f=this._getOrReturnCtx(T,f),n(f,{code:I.too_small,message:M.message,inclusive:!0,exact:!1,minimum:M.value,type:"date"}),$.dirty()}else if(M.kind==="max"){if(T.data.getTime()>M.value)f=this._getOrReturnCtx(T,f),n(f,{code:I.too_big,message:M.message,inclusive:!0,exact:!1,maximum:M.value,type:"date"}),$.dirty()}else OT.assertNever(M);return{status:$.value,value:new Date(T.data.getTime())}}_addCheck(T){return new p$({...this._def,checks:[...this._def.checks,T]})}min(T,S){return this._addCheck({kind:"min",value:T.getTime(),message:u.toString(S)})}max(T,S){return this._addCheck({kind:"max",value:T.getTime(),message:u.toString(S)})}get minDate(){let T=null;for(let S of this._def.checks)if(S.kind==="min"){if(T===null||S.value>T)T=S.value}return T!=null?new Date(T):null}get maxDate(){let T=null;for(let S of this._def.checks)if(S.kind==="max"){if(T===null||S.value<T)T=S.value}return T!=null?new Date(T):null}}p$.create=(T)=>{return new p$({checks:[],coerce:(T===null||T===void 0?void 0:T.coerce)||!1,typeName:b.ZodDate,...FT(T)})};class MJ extends WT{_parse(T){if(this._getType(T)!==c.symbol){const $=this._getOrReturnCtx(T);return n($,{code:I.invalid_type,expected:c.symbol,received:$.parsedType}),ST}return GS(T.data)}}MJ.create=(T)=>{return new MJ({typeName:b.ZodSymbol,...FT(T)})};class tf extends WT{_parse(T){if(this._getType(T)!==c.undefined){const $=this._getOrReturnCtx(T);return n($,{code:I.invalid_type,expected:c.undefined,received:$.parsedType}),ST}return GS(T.data)}}tf.create=(T)=>{return new tf({typeName:b.ZodUndefined,...FT(T)})};class pf extends WT{_parse(T){if(this._getType(T)!==c.null){const $=this._getOrReturnCtx(T);return n($,{code:I.invalid_type,expected:c.null,received:$.parsedType}),ST}return GS(T.data)}}pf.create=(T)=>{return new pf({typeName:b.ZodNull,...FT(T)})};class u$ extends WT{constructor(){super(...arguments);this._any=!0}_parse(T){return GS(T.data)}}u$.create=(T)=>{return new u$({typeName:b.ZodAny,...FT(T)})};class I$ extends WT{constructor(){super(...arguments);this._unknown=!0}_parse(T){return GS(T.data)}}I$.create=(T)=>{return new I$({typeName:b.ZodUnknown,...FT(T)})};class W$ extends WT{_parse(T){const S=this._getOrReturnCtx(T);return n(S,{code:I.invalid_type,expected:c.never,received:S.parsedType}),ST}}W$.create=(T)=>{return new W$({typeName:b.ZodNever,...FT(T)})};class JJ extends WT{_parse(T){if(this._getType(T)!==c.undefined){const $=this._getOrReturnCtx(T);return n($,{code:I.invalid_type,expected:c.void,received:$.parsedType}),ST}return GS(T.data)}}JJ.create=(T)=>{return new JJ({typeName:b.ZodVoid,...FT(T)})};class lS extends WT{_parse(T){const{ctx:S,status:$}=this._processInputParams(T),f=this._def;if(S.parsedType!==c.array)return n(S,{code:I.invalid_type,expected:c.array,received:S.parsedType}),ST;if(f.exactLength!==null){const J=S.data.length>f.exactLength.value,F=S.data.length<f.exactLength.value;if(J||F)n(S,{code:J?I.too_big:I.too_small,minimum:F?f.exactLength.value:void 0,maximum:J?f.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:f.exactLength.message}),$.dirty()}if(f.minLength!==null){if(S.data.length<f.minLength.value)n(S,{code:I.too_small,minimum:f.minLength.value,type:"array",inclusive:!0,exact:!1,message:f.minLength.message}),$.dirty()}if(f.maxLength!==null){if(S.data.length>f.maxLength.value)n(S,{code:I.too_big,maximum:f.maxLength.value,type:"array",inclusive:!0,exact:!1,message:f.maxLength.message}),$.dirty()}if(S.common.async)return Promise.all([...S.data].map((J,F)=>{return f.type._parseAsync(new rS(S,J,S.path,F))})).then((J)=>{return wS.mergeArray($,J)});const M=[...S.data].map((J,F)=>{return f.type._parseSync(new rS(S,J,S.path,F))});return wS.mergeArray($,M)}get element(){return this._def.type}min(T,S){return new lS({...this._def,minLength:{value:T,message:u.toString(S)}})}max(T,S){return new lS({...this._def,maxLength:{value:T,message:u.toString(S)}})}length(T,S){return new lS({...this._def,exactLength:{value:T,message:u.toString(S)}})}nonempty(T){return this.min(1,T)}}lS.create=(T,S)=>{return new lS({type:T,minLength:null,maxLength:null,exactLength:null,typeName:b.ZodArray,...FT(S)})};class bT extends WT{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const T=this._def.shape(),S=OT.objectKeys(T);return this._cached={shape:T,keys:S}}_parse(T){if(this._getType(T)!==c.object){const k=this._getOrReturnCtx(T);return n(k,{code:I.invalid_type,expected:c.object,received:k.parsedType}),ST}const{status:$,ctx:f}=this._processInputParams(T),{shape:M,keys:J}=this._getCached(),F=[];if(!(this._def.catchall instanceof W$&&this._def.unknownKeys==="strip")){for(let k in f.data)if(!J.includes(k))F.push(k)}const W=[];for(let k of J){const X=M[k],w=f.data[k];W.push({key:{status:"valid",value:k},value:X._parse(new rS(f,w,f.path,k)),alwaysSet:k in f.data})}if(this._def.catchall instanceof W$){const k=this._def.unknownKeys;if(k==="passthrough")for(let X of F)W.push({key:{status:"valid",value:X},value:{status:"valid",value:f.data[X]}});else if(k==="strict"){if(F.length>0)n(f,{code:I.unrecognized_keys,keys:F}),$.dirty()}else if(k==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const k=this._def.catchall;for(let X of F){const w=f.data[X];W.push({key:{status:"valid",value:X},value:k._parse(new rS(f,w,f.path,X)),alwaysSet:X in f.data})}}if(f.common.async)return Promise.resolve().then(async()=>{const k=[];for(let X of W){const w=await X.key,K=await X.value;k.push({key:w,value:K,alwaysSet:X.alwaysSet})}return k}).then((k)=>{return wS.mergeObjectSync($,k)});else return wS.mergeObjectSync($,W)}get shape(){return this._def.shape()}strict(T){return u.errToObj,new bT({...this._def,unknownKeys:"strict",...T!==void 0?{errorMap:(S,$)=>{var f,M,J,F;const W=(J=(M=(f=this._def).errorMap)===null||M===void 0?void 0:M.call(f,S,$).message)!==null&&J!==void 0?J:$.defaultError;if(S.code==="unrecognized_keys")return{message:(F=u.errToObj(T).message)!==null&&F!==void 0?F:W};return{message:W}}}:{}})}strip(){return new bT({...this._def,unknownKeys:"strip"})}passthrough(){return new bT({...this._def,unknownKeys:"passthrough"})}extend(T){return new bT({...this._def,shape:()=>({...this._def.shape(),...T})})}merge(T){return new bT({unknownKeys:T._def.unknownKeys,catchall:T._def.catchall,shape:()=>({...this._def.shape(),...T._def.shape()}),typeName:b.ZodObject})}setKey(T,S){return this.augment({[T]:S})}catchall(T){return new bT({...this._def,catchall:T})}pick(T){const S={};return OT.objectKeys(T).forEach(($)=>{if(T[$]&&this.shape[$])S[$]=this.shape[$]}),new bT({...this._def,shape:()=>S})}omit(T){const S={};return OT.objectKeys(this.shape).forEach(($)=>{if(!T[$])S[$]=this.shape[$]}),new bT({...this._def,shape:()=>S})}deepPartial(){return Pf(this)}partial(T){const S={};return OT.objectKeys(this.shape).forEach(($)=>{const f=this.shape[$];if(T&&!T[$])S[$]=f;else S[$]=f.optional()}),new bT({...this._def,shape:()=>S})}required(T){const S={};return OT.objectKeys(this.shape).forEach(($)=>{if(T&&!T[$])S[$]=this.shape[$];else{let M=this.shape[$];while(M instanceof dS)M=M._def.innerType;S[$]=M}}),new bT({...this._def,shape:()=>S})}keyof(){return OX(OT.objectKeys(this.shape))}}bT.create=(T,S)=>{return new bT({shape:()=>T,unknownKeys:"strip",catchall:W$.create(),typeName:b.ZodObject,...FT(S)})};bT.strictCreate=(T,S)=>{return new bT({shape:()=>T,unknownKeys:"strict",catchall:W$.create(),typeName:b.ZodObject,...FT(S)})};bT.lazycreate=(T,S)=>{return new bT({shape:T,unknownKeys:"strip",catchall:W$.create(),typeName:b.ZodObject,...FT(S)})};class uf extends WT{_parse(T){const{ctx:S}=this._processInputParams(T),$=this._def.options;function f(M){for(let F of M)if(F.result.status==="valid")return F.result;for(let F of M)if(F.result.status==="dirty")return S.common.issues.push(...F.ctx.common.issues),F.result;const J=M.map((F)=>new BS(F.ctx.common.issues));return n(S,{code:I.invalid_union,unionErrors:J}),ST}if(S.common.async)return Promise.all($.map(async(M)=>{const J={...S,common:{...S.common,issues:[]},parent:null};return{result:await M._parseAsync({data:S.data,path:S.path,parent:J}),ctx:J}})).then(f);else{let M=void 0;const J=[];for(let W of $){const k={...S,common:{...S.common,issues:[]},parent:null},X=W._parseSync({data:S.data,path:S.path,parent:k});if(X.status==="valid")return X;else if(X.status==="dirty"&&!M)M={result:X,ctx:k};if(k.common.issues.length)J.push(k.common.issues)}if(M)return S.common.issues.push(...M.ctx.common.issues),M.result;const F=J.map((W)=>new BS(W));return n(S,{code:I.invalid_union,unionErrors:F}),ST}}get options(){return this._def.options}}uf.create=(T,S)=>{return new uf({options:T,typeName:b.ZodUnion,...FT(S)})};var H$=(T)=>{if(T instanceof df)return H$(T.schema);else if(T instanceof hS)return H$(T.innerType());else if(T instanceof rf)return[T.value];else if(T instanceof Z$)return T.options;else if(T instanceof af)return OT.objectValues(T.enum);else if(T instanceof ef)return H$(T._def.innerType);else if(T instanceof tf)return[void 0];else if(T instanceof pf)return[null];else if(T instanceof dS)return[void 0,...H$(T.unwrap())];else if(T instanceof _$)return[null,...H$(T.unwrap())];else if(T instanceof YF)return H$(T.unwrap());else if(T instanceof TM)return H$(T.unwrap());else if(T instanceof sf)return H$(T._def.innerType);else return[]};class AF extends WT{_parse(T){const{ctx:S}=this._processInputParams(T);if(S.parsedType!==c.object)return n(S,{code:I.invalid_type,expected:c.object,received:S.parsedType}),ST;const $=this.discriminator,f=S.data[$],M=this.optionsMap.get(f);if(!M)return n(S,{code:I.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[$]}),ST;if(S.common.async)return M._parseAsync({data:S.data,path:S.path,parent:S});else return M._parseSync({data:S.data,path:S.path,parent:S})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(T,S,$){const f=new Map;for(let M of S){const J=H$(M.shape[T]);if(!J.length)throw new Error(`A discriminator value for key \`${T}\` could not be extracted from all schema options`);for(let F of J){if(f.has(F))throw new Error(`Discriminator property ${String(T)} has duplicate value ${String(F)}`);f.set(F,M)}}return new AF({typeName:b.ZodDiscriminatedUnion,discriminator:T,options:S,optionsMap:f,...FT($)})}}class lf extends WT{_parse(T){const{status:S,ctx:$}=this._processInputParams(T),f=(M,J)=>{if(A0(M)||A0(J))return ST;const F=O0(M.value,J.value);if(!F.valid)return n($,{code:I.invalid_intersection_types}),ST;if(Y0(M)||Y0(J))S.dirty();return{status:S.value,value:F.data}};if($.common.async)return Promise.all([this._def.left._parseAsync({data:$.data,path:$.path,parent:$}),this._def.right._parseAsync({data:$.data,path:$.path,parent:$})]).then(([M,J])=>f(M,J));else return f(this._def.left._parseSync({data:$.data,path:$.path,parent:$}),this._def.right._parseSync({data:$.data,path:$.path,parent:$}))}}lf.create=(T,S,$)=>{return new lf({left:T,right:S,typeName:b.ZodIntersection,...FT($)})};class k$ extends WT{_parse(T){const{status:S,ctx:$}=this._processInputParams(T);if($.parsedType!==c.array)return n($,{code:I.invalid_type,expected:c.array,received:$.parsedType}),ST;if($.data.length<this._def.items.length)return n($,{code:I.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ST;if(!this._def.rest&&$.data.length>this._def.items.length)n($,{code:I.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),S.dirty();const M=[...$.data].map((J,F)=>{const W=this._def.items[F]||this._def.rest;if(!W)return null;return W._parse(new rS($,J,$.path,F))}).filter((J)=>!!J);if($.common.async)return Promise.all(M).then((J)=>{return wS.mergeArray(S,J)});else return wS.mergeArray(S,M)}get items(){return this._def.items}rest(T){return new k$({...this._def,rest:T})}}k$.create=(T,S)=>{if(!Array.isArray(T))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new k$({items:T,typeName:b.ZodTuple,rest:null,...FT(S)})};class FJ extends WT{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(T){const{status:S,ctx:$}=this._processInputParams(T);if($.parsedType!==c.object)return n($,{code:I.invalid_type,expected:c.object,received:$.parsedType}),ST;const f=[],M=this._def.keyType,J=this._def.valueType;for(let F in $.data)f.push({key:M._parse(new rS($,F,$.path,F)),value:J._parse(new rS($,$.data[F],$.path,F)),alwaysSet:F in $.data});if($.common.async)return wS.mergeObjectAsync(S,f);else return wS.mergeObjectSync(S,f)}get element(){return this._def.valueType}static create(T,S,$){if(S instanceof WT)return new FJ({keyType:T,valueType:S,typeName:b.ZodRecord,...FT($)});return new FJ({keyType:uS.create(),valueType:T,typeName:b.ZodRecord,...FT(S)})}}class WJ extends WT{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(T){const{status:S,ctx:$}=this._processInputParams(T);if($.parsedType!==c.map)return n($,{code:I.invalid_type,expected:c.map,received:$.parsedType}),ST;const f=this._def.keyType,M=this._def.valueType,J=[...$.data.entries()].map(([F,W],k)=>{return{key:f._parse(new rS($,F,$.path,[k,"key"])),value:M._parse(new rS($,W,$.path,[k,"value"]))}});if($.common.async){const F=new Map;return Promise.resolve().then(async()=>{for(let W of J){const k=await W.key,X=await W.value;if(k.status==="aborted"||X.status==="aborted")return ST;if(k.status==="dirty"||X.status==="dirty")S.dirty();F.set(k.value,X.value)}return{status:S.value,value:F}})}else{const F=new Map;for(let W of J){const{key:k,value:X}=W;if(k.status==="aborted"||X.status==="aborted")return ST;if(k.status==="dirty"||X.status==="dirty")S.dirty();F.set(k.value,X.value)}return{status:S.value,value:F}}}}WJ.create=(T,S,$)=>{return new WJ({valueType:S,keyType:T,typeName:b.ZodMap,...FT($)})};class l$ extends WT{_parse(T){const{status:S,ctx:$}=this._processInputParams(T);if($.parsedType!==c.set)return n($,{code:I.invalid_type,expected:c.set,received:$.parsedType}),ST;const f=this._def;if(f.minSize!==null){if($.data.size<f.minSize.value)n($,{code:I.too_small,minimum:f.minSize.value,type:"set",inclusive:!0,exact:!1,message:f.minSize.message}),S.dirty()}if(f.maxSize!==null){if($.data.size>f.maxSize.value)n($,{code:I.too_big,maximum:f.maxSize.value,type:"set",inclusive:!0,exact:!1,message:f.maxSize.message}),S.dirty()}const M=this._def.valueType;function J(W){const k=new Set;for(let X of W){if(X.status==="aborted")return ST;if(X.status==="dirty")S.dirty();k.add(X.value)}return{status:S.value,value:k}}const F=[...$.data.values()].map((W,k)=>M._parse(new rS($,W,$.path,k)));if($.common.async)return Promise.all(F).then((W)=>J(W));else return J(F)}min(T,S){return new l$({...this._def,minSize:{value:T,message:u.toString(S)}})}max(T,S){return new l$({...this._def,maxSize:{value:T,message:u.toString(S)}})}size(T,S){return this.min(T,S).max(T,S)}nonempty(T){return this.min(1,T)}}l$.create=(T,S)=>{return new l$({valueType:T,minSize:null,maxSize:null,typeName:b.ZodSet,...FT(S)})};class cf extends WT{constructor(){super(...arguments);this.validate=this.implement}_parse(T){const{ctx:S}=this._processInputParams(T);if(S.parsedType!==c.function)return n(S,{code:I.invalid_type,expected:c.function,received:S.parsedType}),ST;function $(F,W){return wF({data:F,path:S.path,errorMaps:[S.common.contextualErrorMap,S.schemaErrorMap,XF(),gf].filter((k)=>!!k),issueData:{code:I.invalid_arguments,argumentsError:W}})}function f(F,W){return wF({data:F,path:S.path,errorMaps:[S.common.contextualErrorMap,S.schemaErrorMap,XF(),gf].filter((k)=>!!k),issueData:{code:I.invalid_return_type,returnTypeError:W}})}const M={errorMap:S.common.contextualErrorMap},J=S.data;if(this._def.returns instanceof d$){const F=this;return GS(async function(...W){const k=new BS([]),X=await F._def.args.parseAsync(W,M).catch((O)=>{throw k.addIssue($(W,O)),k}),w=await Reflect.apply(J,this,X);return await F._def.returns._def.type.parseAsync(w,M).catch((O)=>{throw k.addIssue(f(w,O)),k})})}else{const F=this;return GS(function(...W){const k=F._def.args.safeParse(W,M);if(!k.success)throw new BS([$(W,k.error)]);const X=Reflect.apply(J,this,k.data),w=F._def.returns.safeParse(X,M);if(!w.success)throw new BS([f(X,w.error)]);return w.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...T){return new cf({...this._def,args:k$.create(T).rest(I$.create())})}returns(T){return new cf({...this._def,returns:T})}implement(T){return this.parse(T)}strictImplement(T){return this.parse(T)}static create(T,S,$){return new cf({args:T?T:k$.create([]).rest(I$.create()),returns:S||I$.create(),typeName:b.ZodFunction,...FT($)})}}class df extends WT{get schema(){return this._def.getter()}_parse(T){const{ctx:S}=this._processInputParams(T);return this._def.getter()._parse({data:S.data,path:S.path,parent:S})}}df.create=(T,S)=>{return new df({getter:T,typeName:b.ZodLazy,...FT(S)})};class rf extends WT{_parse(T){if(T.data!==this._def.value){const S=this._getOrReturnCtx(T);return n(S,{received:S.data,code:I.invalid_literal,expected:this._def.value}),ST}return{status:"valid",value:T.data}}get value(){return this._def.value}}rf.create=(T,S)=>{return new rf({value:T,typeName:b.ZodLiteral,...FT(S)})};class Z$ extends WT{constructor(){super(...arguments);TJ.set(this,void 0)}_parse(T){if(typeof T.data!=="string"){const S=this._getOrReturnCtx(T),$=this._def.values;return n(S,{expected:OT.joinValues($),received:S.parsedType,code:I.invalid_type}),ST}if(!KF(this,TJ,"f"))wX(this,TJ,new Set(this._def.values),"f");if(!KF(this,TJ,"f").has(T.data)){const S=this._getOrReturnCtx(T),$=this._def.values;return n(S,{received:S.data,code:I.invalid_enum_value,options:$}),ST}return GS(T.data)}get options(){return this._def.values}get enum(){const T={};for(let S of this._def.values)T[S]=S;return T}get Values(){const T={};for(let S of this._def.values)T[S]=S;return T}get Enum(){const T={};for(let S of this._def.values)T[S]=S;return T}extract(T,S=this._def){return Z$.create(T,{...this._def,...S})}exclude(T,S=this._def){return Z$.create(this.options.filter(($)=>!T.includes($)),{...this._def,...S})}}TJ=new WeakMap;Z$.create=OX;class af extends WT{constructor(){super(...arguments);SJ.set(this,void 0)}_parse(T){const S=OT.getValidEnumValues(this._def.values),$=this._getOrReturnCtx(T);if($.parsedType!==c.string&&$.parsedType!==c.number){const f=OT.objectValues(S);return n($,{expected:OT.joinValues(f),received:$.parsedType,code:I.invalid_type}),ST}if(!KF(this,SJ,"f"))wX(this,SJ,new Set(OT.getValidEnumValues(this._def.values)),"f");if(!KF(this,SJ,"f").has(T.data)){const f=OT.objectValues(S);return n($,{received:$.data,code:I.invalid_enum_value,options:f}),ST}return GS(T.data)}get enum(){return this._def.values}}SJ=new WeakMap;af.create=(T,S)=>{return new af({values:T,typeName:b.ZodNativeEnum,...FT(S)})};class d$ extends WT{unwrap(){return this._def.type}_parse(T){const{ctx:S}=this._processInputParams(T);if(S.parsedType!==c.promise&&S.common.async===!1)return n(S,{code:I.invalid_type,expected:c.promise,received:S.parsedType}),ST;const $=S.parsedType===c.promise?S.data:Promise.resolve(S.data);return GS($.then((f)=>{return this._def.type.parseAsync(f,{path:S.path,errorMap:S.common.contextualErrorMap})}))}}d$.create=(T,S)=>{return new d$({type:T,typeName:b.ZodPromise,...FT(S)})};class hS extends WT{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===b.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(T){const{status:S,ctx:$}=this._processInputParams(T),f=this._def.effect||null,M={addIssue:(J)=>{if(n($,J),J.fatal)S.abort();else S.dirty()},get path(){return $.path}};if(M.addIssue=M.addIssue.bind(M),f.type==="preprocess"){const J=f.transform($.data,M);if($.common.async)return Promise.resolve(J).then(async(F)=>{if(S.value==="aborted")return ST;const W=await this._def.schema._parseAsync({data:F,path:$.path,parent:$});if(W.status==="aborted")return ST;if(W.status==="dirty")return nf(W.value);if(S.value==="dirty")return nf(W.value);return W});else{if(S.value==="aborted")return ST;const F=this._def.schema._parseSync({data:J,path:$.path,parent:$});if(F.status==="aborted")return ST;if(F.status==="dirty")return nf(F.value);if(S.value==="dirty")return nf(F.value);return F}}if(f.type==="refinement"){const J=(F)=>{const W=f.refinement(F,M);if($.common.async)return Promise.resolve(W);if(W instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return F};if($.common.async===!1){const F=this._def.schema._parseSync({data:$.data,path:$.path,parent:$});if(F.status==="aborted")return ST;if(F.status==="dirty")S.dirty();return J(F.value),{status:S.value,value:F.value}}else return this._def.schema._parseAsync({data:$.data,path:$.path,parent:$}).then((F)=>{if(F.status==="aborted")return ST;if(F.status==="dirty")S.dirty();return J(F.value).then(()=>{return{status:S.value,value:F.value}})})}if(f.type==="transform")if($.common.async===!1){const J=this._def.schema._parseSync({data:$.data,path:$.path,parent:$});if(!$J(J))return J;const F=f.transform(J.value,M);if(F instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:S.value,value:F}}else return this._def.schema._parseAsync({data:$.data,path:$.path,parent:$}).then((J)=>{if(!$J(J))return J;return Promise.resolve(f.transform(J.value,M)).then((F)=>({status:S.value,value:F}))});OT.assertNever(f)}}hS.create=(T,S,$)=>{return new hS({schema:T,typeName:b.ZodEffects,effect:S,...FT($)})};hS.createWithPreprocess=(T,S,$)=>{return new hS({schema:S,effect:{type:"preprocess",transform:T},typeName:b.ZodEffects,...FT($)})};class dS extends WT{_parse(T){if(this._getType(T)===c.undefined)return GS(void 0);return this._def.innerType._parse(T)}unwrap(){return this._def.innerType}}dS.create=(T,S)=>{return new dS({innerType:T,typeName:b.ZodOptional,...FT(S)})};class _$ extends WT{_parse(T){if(this._getType(T)===c.null)return GS(null);return this._def.innerType._parse(T)}unwrap(){return this._def.innerType}}_$.create=(T,S)=>{return new _$({innerType:T,typeName:b.ZodNullable,...FT(S)})};class ef extends WT{_parse(T){const{ctx:S}=this._processInputParams(T);let $=S.data;if(S.parsedType===c.undefined)$=this._def.defaultValue();return this._def.innerType._parse({data:$,path:S.path,parent:S})}removeDefault(){return this._def.innerType}}ef.create=(T,S)=>{return new ef({innerType:T,typeName:b.ZodDefault,defaultValue:typeof S.default==="function"?S.default:()=>S.default,...FT(S)})};class sf extends WT{_parse(T){const{ctx:S}=this._processInputParams(T),$={...S,common:{...S.common,issues:[]}},f=this._def.innerType._parse({data:$.data,path:$.path,parent:{...$}});if(fJ(f))return f.then((M)=>{return{status:"valid",value:M.status==="valid"?M.value:this._def.catchValue({get error(){return new BS($.common.issues)},input:$.data})}});else return{status:"valid",value:f.status==="valid"?f.value:this._def.catchValue({get error(){return new BS($.common.issues)},input:$.data})}}removeCatch(){return this._def.innerType}}sf.create=(T,S)=>{return new sf({innerType:T,typeName:b.ZodCatch,catchValue:typeof S.catch==="function"?S.catch:()=>S.catch,...FT(S)})};class kJ extends WT{_parse(T){if(this._getType(T)!==c.nan){const $=this._getOrReturnCtx(T);return n($,{code:I.invalid_type,expected:c.nan,received:$.parsedType}),ST}return{status:"valid",value:T.data}}}kJ.create=(T)=>{return new kJ({typeName:b.ZodNaN,...FT(T)})};var r4=Symbol("zod_brand");class YF extends WT{_parse(T){const{ctx:S}=this._processInputParams(T),$=S.data;return this._def.type._parse({data:$,path:S.path,parent:S})}unwrap(){return this._def.type}}class XJ extends WT{_parse(T){const{status:S,ctx:$}=this._processInputParams(T);if($.common.async)return(async()=>{const M=await this._def.in._parseAsync({data:$.data,path:$.path,parent:$});if(M.status==="aborted")return ST;if(M.status==="dirty")return S.dirty(),nf(M.value);else return this._def.out._parseAsync({data:M.value,path:$.path,parent:$})})();else{const f=this._def.in._parseSync({data:$.data,path:$.path,parent:$});if(f.status==="aborted")return ST;if(f.status==="dirty")return S.dirty(),{status:"dirty",value:f.value};else return this._def.out._parseSync({data:f.value,path:$.path,parent:$})}}static create(T,S){return new XJ({in:T,out:S,typeName:b.ZodPipeline})}}class TM extends WT{_parse(T){const S=this._def.innerType._parse(T),$=(f)=>{if($J(f))f.value=Object.freeze(f.value);return f};return fJ(S)?S.then((f)=>$(f)):$(S)}unwrap(){return this._def.innerType}}TM.create=(T,S)=>{return new TM({innerType:T,typeName:b.ZodReadonly,...FT(S)})};var a4={object:bT.lazycreate},b;(function(T){T.ZodString="ZodString",T.ZodNumber="ZodNumber",T.ZodNaN="ZodNaN",T.ZodBigInt="ZodBigInt",T.ZodBoolean="ZodBoolean",T.ZodDate="ZodDate",T.ZodSymbol="ZodSymbol",T.ZodUndefined="ZodUndefined",T.ZodNull="ZodNull",T.ZodAny="ZodAny",T.ZodUnknown="ZodUnknown",T.ZodNever="ZodNever",T.ZodVoid="ZodVoid",T.ZodArray="ZodArray",T.ZodObject="ZodObject",T.ZodUnion="ZodUnion",T.ZodDiscriminatedUnion="ZodDiscriminatedUnion",T.ZodIntersection="ZodIntersection",T.ZodTuple="ZodTuple",T.ZodRecord="ZodRecord",T.ZodMap="ZodMap",T.ZodSet="ZodSet",T.ZodFunction="ZodFunction",T.ZodLazy="ZodLazy",T.ZodLiteral="ZodLiteral",T.ZodEnum="ZodEnum",T.ZodEffects="ZodEffects",T.ZodNativeEnum="ZodNativeEnum",T.ZodOptional="ZodOptional",T.ZodNullable="ZodNullable",T.ZodDefault="ZodDefault",T.ZodCatch="ZodCatch",T.ZodPromise="ZodPromise",T.ZodBranded="ZodBranded",T.ZodPipeline="ZodPipeline",T.ZodReadonly="ZodReadonly"})(b||(b={}));var e4=(T,S={message:`Input not instance of ${T.name}`})=>RX(($)=>$ instanceof T,S),GX=uS.create,zX=b$.create,s4=kJ.create,TY=q$.create,HX=of.create,SY=p$.create,$Y=MJ.create,fY=tf.create,MY=pf.create,JY=u$.create,FY=I$.create,WY=W$.create,kY=JJ.create,XY=lS.create,wJ=bT.create,wY=bT.strictCreate,KY=uf.create,AY=AF.create,YY=lf.create,OY=k$.create,RY=FJ.create,GY=WJ.create,zY=l$.create,HY=cf.create,_Y=df.create,EY=rf.create,DY=Z$.create,yY=af.create,QY=d$.create,kX=hS.create,UY=dS.create,VY=_$.create,LY=hS.createWithPreprocess,BY=XJ.create,NY=()=>GX().optional(),CY=()=>zX().optional(),xY=()=>HX().optional(),jY={string:(T)=>uS.create({...T,coerce:!0}),number:(T)=>b$.create({...T,coerce:!0}),boolean:(T)=>of.create({...T,coerce:!0}),bigint:(T)=>q$.create({...T,coerce:!0}),date:(T)=>p$.create({...T,coerce:!0})},IY=ST,VT=Object.freeze({__proto__:null,defaultErrorMap:gf,setErrorMap:b4,getErrorMap:XF,makeIssue:wF,EMPTY_PATH:q4,addIssueToContext:n,ParseStatus:wS,INVALID:ST,DIRTY:nf,OK:GS,isAborted:A0,isDirty:Y0,isValid:$J,isAsync:fJ,get util(){return OT},get objectUtil(){return K0},ZodParsedType:c,getParsedType:j$,ZodType:WT,datetimeRegex:YX,ZodString:uS,ZodNumber:b$,ZodBigInt:q$,ZodBoolean:of,ZodDate:p$,ZodSymbol:MJ,ZodUndefined:tf,ZodNull:pf,ZodAny:u$,ZodUnknown:I$,ZodNever:W$,ZodVoid:JJ,ZodArray:lS,ZodObject:bT,ZodUnion:uf,ZodDiscriminatedUnion:AF,ZodIntersection:lf,ZodTuple:k$,ZodRecord:FJ,ZodMap:WJ,ZodSet:l$,ZodFunction:cf,ZodLazy:df,ZodLiteral:rf,ZodEnum:Z$,ZodNativeEnum:af,ZodPromise:d$,ZodEffects:hS,ZodTransformer:hS,ZodOptional:dS,ZodNullable:_$,ZodDefault:ef,ZodCatch:sf,ZodNaN:kJ,BRAND:r4,ZodBranded:YF,ZodPipeline:XJ,ZodReadonly:TM,custom:RX,Schema:WT,ZodSchema:WT,late:a4,get ZodFirstPartyTypeKind(){return b},coerce:jY,any:JY,array:XY,bigint:TY,boolean:HX,date:SY,discriminatedUnion:AY,effect:kX,enum:DY,function:HY,instanceof:e4,intersection:YY,lazy:_Y,literal:EY,map:GY,nan:s4,nativeEnum:yY,never:WY,null:MY,nullable:VY,number:zX,object:wJ,oboolean:xY,onumber:CY,optional:UY,ostring:NY,pipeline:BY,preprocess:LY,promise:QY,record:RY,set:zY,strictObject:wY,string:GX,symbol:$Y,transformer:kX,tuple:OY,undefined:fY,union:KY,unknown:FY,void:kY,NEVER:IY,ZodIssueCode:I,quotelessJson:I4,ZodError:BS});function _X(){return{}}function EX(T,S){const $={type:"array"};if(T.type?._def?.typeName!==b.ZodAny)$.items=s(T.type._def,{...S,currentPath:[...S.currentPath,"items"]});if(T.minLength)YT($,"minItems",T.minLength.value,T.minLength.message,S);if(T.maxLength)YT($,"maxItems",T.maxLength.value,T.maxLength.message,S);if(T.exactLength)YT($,"minItems",T.exactLength.value,T.exactLength.message,S),YT($,"maxItems",T.exactLength.value,T.exactLength.message,S);return $}function DX(T,S){const $={type:"integer",format:"int64"};if(!T.checks)return $;for(let f of T.checks)switch(f.kind){case"min":if(S.target==="jsonSchema7")if(f.inclusive)YT($,"minimum",f.value,f.message,S);else YT($,"exclusiveMinimum",f.value,f.message,S);else{if(!f.inclusive)$.exclusiveMinimum=!0;YT($,"minimum",f.value,f.message,S)}break;case"max":if(S.target==="jsonSchema7")if(f.inclusive)YT($,"maximum",f.value,f.message,S);else YT($,"exclusiveMaximum",f.value,f.message,S);else{if(!f.inclusive)$.exclusiveMaximum=!0;YT($,"maximum",f.value,f.message,S)}break;case"multipleOf":YT($,"multipleOf",f.value,f.message,S);break}return $}function yX(){return{type:"boolean"}}function QX(T,S){return s(T.type._def,S)}var UX=(T,S)=>{return s(T.innerType._def,S)};function R0(T,S,$){const f=$??S.dateStrategy;if(Array.isArray(f))return{anyOf:f.map((M,J)=>R0(T,S,M))};switch(f){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return bY(T,S)}}var bY=(T,S)=>{const $={type:"integer",format:"unix-time"};if(S.target==="openApi3")return $;for(let f of T.checks)switch(f.kind){case"min":YT($,"minimum",f.value,f.message,S);break;case"max":YT($,"maximum",f.value,f.message,S);break}return $};function VX(T,S){return{...s(T.innerType._def,S),default:T.defaultValue()}}function LX(T,S){return S.effectStrategy==="input"?s(T.schema._def,S):{}}function BX(T){return{type:"string",enum:T.values}}function NX(T,S){const $=[s(T.left._def,{...S,currentPath:[...S.currentPath,"allOf","0"]}),s(T.right._def,{...S,currentPath:[...S.currentPath,"allOf","1"]})].filter((J)=>!!J);let f=S.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const M=[];return $.forEach((J)=>{if(qY(J)){if(M.push(...J.allOf),J.unevaluatedProperties===void 0)f=void 0}else{let F=J;if("additionalProperties"in J&&J.additionalProperties===!1){const{additionalProperties:W,...k}=J;F=k}else f=void 0;M.push(F)}}),M.length?{allOf:M,...f}:void 0}var qY=(T)=>{if("type"in T&&T.type==="string")return!1;return"allOf"in T};function CX(T,S){const $=typeof T.value;if($!=="bigint"&&$!=="number"&&$!=="boolean"&&$!=="string")return{type:Array.isArray(T.value)?"array":"object"};if(S.target==="openApi3")return{type:$==="bigint"?"integer":$,enum:[T.value]};return{type:$==="bigint"?"integer":$,const:T.value}}function OF(T,S){const $={type:"string"};function f(M){return S.patternStrategy==="escape"?ZY(M):M}if(T.checks)for(let M of T.checks)switch(M.kind){case"min":YT($,"minLength",typeof $.minLength==="number"?Math.max($.minLength,M.value):M.value,M.message,S);break;case"max":YT($,"maxLength",typeof $.maxLength==="number"?Math.min($.maxLength,M.value):M.value,M.message,S);break;case"email":switch(S.emailStrategy){case"format:email":aS($,"email",M.message,S);break;case"format:idn-email":aS($,"idn-email",M.message,S);break;case"pattern:zod":eS($,r$.email,M.message,S);break}break;case"url":aS($,"uri",M.message,S);break;case"uuid":aS($,"uuid",M.message,S);break;case"regex":eS($,M.regex,M.message,S);break;case"cuid":eS($,r$.cuid,M.message,S);break;case"cuid2":eS($,r$.cuid2,M.message,S);break;case"startsWith":eS($,RegExp(`^${f(M.value)}`),M.message,S);break;case"endsWith":eS($,RegExp(`${f(M.value)}\$`),M.message,S);break;case"datetime":aS($,"date-time",M.message,S);break;case"date":aS($,"date",M.message,S);break;case"time":aS($,"time",M.message,S);break;case"duration":aS($,"duration",M.message,S);break;case"length":YT($,"minLength",typeof $.minLength==="number"?Math.max($.minLength,M.value):M.value,M.message,S),YT($,"maxLength",typeof $.maxLength==="number"?Math.min($.maxLength,M.value):M.value,M.message,S);break;case"includes":{eS($,RegExp(f(M.value)),M.message,S);break}case"ip":{if(M.version!=="v6")aS($,"ipv4",M.message,S);if(M.version!=="v4")aS($,"ipv6",M.message,S);break}case"emoji":eS($,r$.emoji,M.message,S);break;case"ulid":{eS($,r$.ulid,M.message,S);break}case"base64":{switch(S.base64Strategy){case"format:binary":{aS($,"binary",M.message,S);break}case"contentEncoding:base64":{YT($,"contentEncoding","base64",M.message,S);break}case"pattern:zod":{eS($,r$.base64,M.message,S);break}}break}case"nanoid":eS($,r$.nanoid,M.message,S);case"toLowerCase":case"toUpperCase":case"trim":break;default:((J)=>{})(M)}return $}var G0,r$={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(G0===void 0)G0=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return G0},uuid:/^[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}$/,ipv4:/^(?:(?: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])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/},ZY=(T)=>Array.from(T).map((S)=>/[a-zA-Z0-9]/.test(S)?S:`\\${S}`).join(""),aS=(T,S,$,f)=>{if(T.format||T.anyOf?.some((M)=>M.format)){if(!T.anyOf)T.anyOf=[];if(T.format){if(T.anyOf.push({format:T.format,...T.errorMessage&&f.errorMessages&&{errorMessage:{format:T.errorMessage.format}}}),delete T.format,T.errorMessage){if(delete T.errorMessage.format,Object.keys(T.errorMessage).length===0)delete T.errorMessage}}T.anyOf.push({format:S,...$&&f.errorMessages&&{errorMessage:{format:$}}})}else YT(T,"format",S,$,f)},eS=(T,S,$,f)=>{if(T.pattern||T.allOf?.some((M)=>M.pattern)){if(!T.allOf)T.allOf=[];if(T.pattern){if(T.allOf.push({pattern:T.pattern,...T.errorMessage&&f.errorMessages&&{errorMessage:{pattern:T.errorMessage.pattern}}}),delete T.pattern,T.errorMessage){if(delete T.errorMessage.pattern,Object.keys(T.errorMessage).length===0)delete T.errorMessage}}T.allOf.push({pattern:xX(S,f),...$&&f.errorMessages&&{errorMessage:{pattern:$}}})}else YT(T,"pattern",xX(S,f),$,f)},xX=(T,S)=>{const $=typeof T==="function"?T():T;if(!S.applyRegexFlags||!$.flags)return $.source;const f={i:$.flags.includes("i"),m:$.flags.includes("m"),s:$.flags.includes("s")},M=f.i?$.source.toLowerCase():$.source;let J="",F=!1,W=!1,k=!1;for(let X=0;X<M.length;X++){if(F){J+=M[X],F=!1;continue}if(f.i){if(W){if(M[X].match(/[a-z]/)){if(k)J+=M[X],J+=`${M[X-2]}-${M[X]}`.toUpperCase(),k=!1;else if(M[X+1]==="-"&&M[X+2]?.match(/[a-z]/))J+=M[X],k=!0;else J+=`${M[X]}${M[X].toUpperCase()}`;continue}}else if(M[X].match(/[a-z]/)){J+=`[${M[X]}${M[X].toUpperCase()}]`;continue}}if(f.m){if(M[X]==="^"){J+="(^|(?<=[\r\n]))";continue}else if(M[X]==="$"){J+="($|(?=[\r\n]))";continue}}if(f.s&&M[X]==="."){J+=W?`${M[X]}\r\n`:`[${M[X]}\r\n]`;continue}if(J+=M[X],M[X]==="\\")F=!0;else if(W&&M[X]==="]")W=!1;else if(!W&&M[X]==="[")W=!0}try{const X=new RegExp(J)}catch{return console.warn(`Could not convert regex pattern at ${S.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),$.source}return J};function RF(T,S){if(S.target==="openApi3"&&T.keyType?._def.typeName===b.ZodEnum)return{type:"object",required:T.keyType._def.values,properties:T.keyType._def.values.reduce((f,M)=>({...f,[M]:s(T.valueType._def,{...S,currentPath:[...S.currentPath,"properties",M]})??{}}),{}),additionalProperties:!1};const $={type:"object",additionalProperties:s(T.valueType._def,{...S,currentPath:[...S.currentPath,"additionalProperties"]})??{}};if(S.target==="openApi3")return $;if(T.keyType?._def.typeName===b.ZodString&&T.keyType._def.checks?.length){const f=Object.entries(OF(T.keyType._def,S)).reduce((M,[J,F])=>J==="type"?M:{...M,[J]:F},{});return{...$,propertyNames:f}}else if(T.keyType?._def.typeName===b.ZodEnum)return{...$,propertyNames:{enum:T.keyType._def.values}};return $}function jX(T,S){if(S.mapStrategy==="record")return RF(T,S);const $=s(T.keyType._def,{...S,currentPath:[...S.currentPath,"items","items","0"]})||{},f=s(T.valueType._def,{...S,currentPath:[...S.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[$,f],minItems:2,maxItems:2}}}function IX(T){const S=T.values,f=Object.keys(T.values).filter((J)=>{return typeof S[S[J]]!=="number"}).map((J)=>S[J]),M=Array.from(new Set(f.map((J)=>typeof J)));return{type:M.length===1?M[0]==="string"?"string":"number":["string","number"],enum:f}}function bX(){return{not:{}}}function qX(T){return T.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}function mX(T,S){if(S.target==="openApi3")return ZX(T,S);const $=T.options instanceof Map?Array.from(T.options.values()):T.options;if($.every((f)=>(f._def.typeName in KJ)&&(!f._def.checks||!f._def.checks.length))){const f=$.reduce((M,J)=>{const F=KJ[J._def.typeName];return F&&!M.includes(F)?[...M,F]:M},[]);return{type:f.length>1?f:f[0]}}else if($.every((f)=>f._def.typeName==="ZodLiteral"&&!f.description)){const f=$.reduce((M,J)=>{const F=typeof J._def.value;switch(F){case"string":case"number":case"boolean":return[...M,F];case"bigint":return[...M,"integer"];case"object":if(J._def.value===null)return[...M,"null"];case"symbol":case"undefined":case"function":default:return M}},[]);if(f.length===$.length){const M=f.filter((J,F,W)=>W.indexOf(J)===F);return{type:M.length>1?M:M[0],enum:$.reduce((J,F)=>{return J.includes(F._def.value)?J:[...J,F._def.value]},[])}}}else if($.every((f)=>f._def.typeName==="ZodEnum"))return{type:"string",enum:$.reduce((f,M)=>[...f,...M._def.values.filter((J)=>!f.includes(J))],[])};return ZX(T,S)}var KJ={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"},ZX=(T,S)=>{const $=(T.options instanceof Map?Array.from(T.options.values()):T.options).map((f,M)=>s(f._def,{...S,currentPath:[...S.currentPath,"anyOf",`${M}`]})).filter((f)=>!!f&&(!S.strictUnions||typeof f==="object"&&Object.keys(f).length>0));return $.length?{anyOf:$}:void 0};function hX(T,S){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(T.innerType._def.typeName)&&(!T.innerType._def.checks||!T.innerType._def.checks.length)){if(S.target==="openApi3")return{type:KJ[T.innerType._def.typeName],nullable:!0};return{type:[KJ[T.innerType._def.typeName],"null"]}}if(S.target==="openApi3"){const f=s(T.innerType._def,{...S,currentPath:[...S.currentPath]});if(f&&"$ref"in f)return{allOf:[f],nullable:!0};return f&&{...f,nullable:!0}}const $=s(T.innerType._def,{...S,currentPath:[...S.currentPath,"anyOf","0"]});return $&&{anyOf:[$,{type:"null"}]}}function vX(T,S){const $={type:"number"};if(!T.checks)return $;for(let f of T.checks)switch(f.kind){case"int":$.type="integer",X0($,"type",f.message,S);break;case"min":if(S.target==="jsonSchema7")if(f.inclusive)YT($,"minimum",f.value,f.message,S);else YT($,"exclusiveMinimum",f.value,f.message,S);else{if(!f.inclusive)$.exclusiveMinimum=!0;YT($,"minimum",f.value,f.message,S)}break;case"max":if(S.target==="jsonSchema7")if(f.inclusive)YT($,"maximum",f.value,f.message,S);else YT($,"exclusiveMaximum",f.value,f.message,S);else{if(!f.inclusive)$.exclusiveMaximum=!0;YT($,"maximum",f.value,f.message,S)}break;case"multipleOf":YT($,"multipleOf",f.value,f.message,S);break}return $}function mY(T,S){if(S.removeAdditionalStrategy==="strict")return T.catchall._def.typeName==="ZodNever"?T.unknownKeys!=="strict":s(T.catchall._def,{...S,currentPath:[...S.currentPath,"additionalProperties"]})??!0;else return T.catchall._def.typeName==="ZodNever"?T.unknownKeys==="passthrough":s(T.catchall._def,{...S,currentPath:[...S.currentPath,"additionalProperties"]})??!0}function PX(T,S){const $={type:"object",...Object.entries(T.shape()).reduce((f,[M,J])=>{if(J===void 0||J._def===void 0)return f;const F=s(J._def,{...S,currentPath:[...S.currentPath,"properties",M],propertyPath:[...S.currentPath,"properties",M]});if(F===void 0)return f;return{properties:{...f.properties,[M]:F},required:J.isOptional()?f.required:[...f.required,M]}},{properties:{},required:[]}),additionalProperties:mY(T,S)};if(!$.required.length)delete $.required;return $}var nX=(T,S)=>{if(S.currentPath.toString()===S.propertyPath?.toString())return s(T.innerType._def,S);const $=s(T.innerType._def,{...S,currentPath:[...S.currentPath,"anyOf","1"]});return $?{anyOf:[{not:{}},$]}:{}};var cX=(T,S)=>{if(S.pipeStrategy==="input")return s(T.in._def,S);else if(S.pipeStrategy==="output")return s(T.out._def,S);const $=s(T.in._def,{...S,currentPath:[...S.currentPath,"allOf","0"]}),f=s(T.out._def,{...S,currentPath:[...S.currentPath,"allOf",$?"1":"0"]});return{allOf:[$,f].filter((M)=>M!==void 0)}};function gX(T,S){return s(T.type._def,S)}function oX(T,S){const f={type:"array",uniqueItems:!0,items:s(T.valueType._def,{...S,currentPath:[...S.currentPath,"items"]})};if(T.minSize)YT(f,"minItems",T.minSize.value,T.minSize.message,S);if(T.maxSize)YT(f,"maxItems",T.maxSize.value,T.maxSize.message,S);return f}function tX(T,S){if(T.rest)return{type:"array",minItems:T.items.length,items:T.items.map(($,f)=>s($._def,{...S,currentPath:[...S.currentPath,"items",`${f}`]})).reduce(($,f)=>f===void 0?$:[...$,f],[]),additionalItems:s(T.rest._def,{...S,currentPath:[...S.currentPath,"additionalItems"]})};else return{type:"array",minItems:T.items.length,maxItems:T.items.length,items:T.items.map(($,f)=>s($._def,{...S,currentPath:[...S.currentPath,"items",`${f}`]})).reduce(($,f)=>f===void 0?$:[...$,f],[])}}function iX(){return{not:{}}}function pX(){return{}}var uX=(T,S)=>{return s(T.innerType._def,S)};function s(T,S,$=!1){const f=S.seen.get(T);if(S.override){const F=S.override?.(T,S,f,$);if(F!==MX)return F}if(f&&!$){const F=hY(f,S);if(F!==void 0)return F}const M={def:T,path:S.currentPath,jsonSchema:void 0};S.seen.set(T,M);const J=PY(T,T.typeName,S);if(J)nY(T,S,J);return M.jsonSchema=J,J}var hY=(T,S)=>{switch(S.$refStrategy){case"root":return{$ref:T.path.join("/")};case"relative":return{$ref:vY(S.currentPath,T.path)};case"none":case"seen":{if(T.path.length<S.currentPath.length&&T.path.every(($,f)=>S.currentPath[f]===$))return console.warn(`Recursive reference detected at ${S.currentPath.join("/")}! Defaulting to any`),{};return S.$refStrategy==="seen"?{}:void 0}}},vY=(T,S)=>{let $=0;for(;$<T.length&&$<S.length;$++)if(T[$]!==S[$])break;return[(T.length-$).toString(),...S.slice($)].join("/")},PY=(T,S,$)=>{switch(S){case b.ZodString:return OF(T,$);case b.ZodNumber:return vX(T,$);case b.ZodObject:return PX(T,$);case b.ZodBigInt:return DX(T,$);case b.ZodBoolean:return yX();case b.ZodDate:return R0(T,$);case b.ZodUndefined:return iX();case b.ZodNull:return qX($);case b.ZodArray:return EX(T,$);case b.ZodUnion:case b.ZodDiscriminatedUnion:return mX(T,$);case b.ZodIntersection:return NX(T,$);case b.ZodTuple:return tX(T,$);case b.ZodRecord:return RF(T,$);case b.ZodLiteral:return CX(T,$);case b.ZodEnum:return BX(T);case b.ZodNativeEnum:return IX(T);case b.ZodNullable:return hX(T,$);case b.ZodOptional:return nX(T,$);case b.ZodMap:return jX(T,$);case b.ZodSet:return oX(T,$);case b.ZodLazy:return s(T.getter()._def,$);case b.ZodPromise:return gX(T,$);case b.ZodNaN:case b.ZodNever:return bX();case b.ZodEffects:return LX(T,$);case b.ZodAny:return _X();case b.ZodUnknown:return pX();case b.ZodDefault:return VX(T,$);case b.ZodBranded:return QX(T,$);case b.ZodReadonly:return uX(T,$);case b.ZodCatch:return UX(T,$);case b.ZodPipeline:return cX(T,$);case b.ZodFunction:case b.ZodVoid:case b.ZodSymbol:return;default:return((f)=>{return})(S)}},nY=(T,S,$)=>{if(T.description){if($.description=T.description,S.markdownDescription)$.markdownDescription=T.description}return $};var lX=(T,S)=>{const $=FX(S),f=typeof S==="object"&&S.definitions?Object.entries(S.definitions).reduce((k,[X,w])=>({...k,[X]:s(w._def,{...$,currentPath:[...$.basePath,$.definitionPath,X]},!0)??{}}),{}):void 0,M=typeof S==="string"?S:S?.nameStrategy==="title"?void 0:S?.name,J=s(T._def,M===void 0?$:{...$,currentPath:[...$.basePath,$.definitionPath,M]},!1)??{},F=typeof S==="object"&&S.name!==void 0&&S.nameStrategy==="title"?S.name:void 0;if(F!==void 0)J.title=F;const W=M===void 0?f?{...J,[$.definitionPath]:f}:J:{$ref:[...$.$refStrategy==="relative"?[]:$.basePath,$.definitionPath,M].join("/"),[$.definitionPath]:{...f,[M]:J}};if($.target==="jsonSchema7")W.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="jsonSchema2019-09")W.$schema="https://json-schema.org/draft/2019-09/schema#";return W};var dX=lX;function rX(T,S){return function $({schema:f,fallback:M}){const J=dX(f);return async function F(W,k=3){let X;const w=[];while(w.length<k){X=await T(W,J,M,w);const K=f.safeParse(X);if(K.success)return K.data;S?.warn(`safegen failed to generate well-formed data.
4
+ `,`Here's what was returned last time:
5
+ `,JSON.stringify(X,null," "),`
6
+ `,`Here's the error message from zod:
7
+ `,K.error.toString()),w.push({response:X,error:K.error})}return S?.error(`safegen was unable to generate well-formed data after ${k} failed attempts.`),M}}}function aX(T){return["Please generate a response in JSON that conforms to the following JSON Schema:",JSON.stringify(T,null,2)].join(`
8
+ `)}import{createHash as p6}from"crypto";var a$="4.67.3";function sX(T,S={auto:!1}){if(eX)throw new Error(`you must \`import 'openai/shims/${T.kind}'\` before importing anything else from openai`);if(e$)throw new Error(`can't \`import 'openai/shims/${T.kind}'\` after \`import 'openai/shims/${e$}'\``);eX=S.auto,e$=T.kind,z0=T.fetch,cY=T.Request,gY=T.Response,oY=T.Headers,H0=T.FormData,tY=T.Blob,GF=T.File,_0=T.ReadableStream,E0=T.getMultipartRequestOptions,D0=T.getDefaultAgent,zF=T.fileFromPath,y0=T.isFsReadStream}var eX=!1,e$=void 0,z0=void 0,cY=void 0,gY=void 0,oY=void 0,H0=void 0,tY=void 0,GF=void 0,_0=void 0,E0=void 0,D0=void 0,zF=void 0,y0=void 0;class Q0{constructor(T){this.body=T}get[Symbol.toStringTag](){return"MultipartBody"}}function Tw({manuallyImported:T}={}){const S=T?"You may need to use polyfills":`Add one of these imports before your first \`import \u2026 from 'openai'\`:
9
+ - \`import 'openai/shims/node'\` (if you're running on Node)
10
+ - \`import 'openai/shims/web'\` (otherwise)
11
+ `;let $,f,M,J;try{$=fetch,f=Request,M=Response,J=Headers}catch(F){throw new Error(`this environment is missing the following Web Fetch API type: ${F.message}. ${S}`)}return{kind:"web",fetch:$,Request:f,Response:M,Headers:J,FormData:typeof FormData!=="undefined"?FormData:class F{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${S}`)}},Blob:typeof Blob!=="undefined"?Blob:class F{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${S}`)}},File:typeof File!=="undefined"?File:class F{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${S}`)}},ReadableStream:typeof ReadableStream!=="undefined"?ReadableStream:class F{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${S}`)}},getMultipartRequestOptions:async(F,W)=>({...W,body:new Q0(F)}),getDefaultAgent:(F)=>{return},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads")},isFsReadStream:(F)=>!1}}import{ReadStream as pY}from"fs";function Sw(){const T=Tw();function S($){return $ instanceof pY}return{...T,isFsReadStream:S}}if(!e$)sX(Sw(),{auto:!0});class m${constructor(){this.buffer=[],this.trailingCR=!1}decode(T){let S=this.decodeText(T);if(this.trailingCR)S="\r"+S,this.trailingCR=!1;if(S.endsWith("\r"))this.trailingCR=!0,S=S.slice(0,-1);if(!S)return[];const $=m$.NEWLINE_CHARS.has(S[S.length-1]||"");let f=S.split(m$.NEWLINE_REGEXP);if($)f.pop();if(f.length===1&&!$)return this.buffer.push(f[0]),[];if(this.buffer.length>0)f=[this.buffer.join("")+f[0],...f.slice(1)],this.buffer=[];if(!$)this.buffer=[f.pop()||""];return f}decodeText(T){if(T==null)return"";if(typeof T==="string")return T;if(typeof Buffer!=="undefined"){if(T instanceof Buffer)return T.toString();if(T instanceof Uint8Array)return Buffer.from(T).toString();throw new $T(`Unexpected: received non-Uint8Array (${T.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder!=="undefined"){if(T instanceof Uint8Array||T instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(T);throw new $T(`Unexpected: received non-Uint8Array/ArrayBuffer (${T.constructor.name}) in a web platform. Please report this error.`)}throw new $T("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];const T=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,T}}m$.NEWLINE_CHARS=new Set(["\n","\r"]);m$.NEWLINE_REGEXP=/\r\n|[\n\r]/g;async function*uY(T,S){if(!T.body)throw S.abort(),new $T("Attempted to iterate over a response with no body");const $=new $w,f=new m$,M=fw(T.body);for await(let J of lY(M))for(let F of f.decode(J)){const W=$.decode(F);if(W)yield W}for(let J of f.flush()){const F=$.decode(J);if(F)yield F}}async function*lY(T){let S=new Uint8Array;for await(let $ of T){if($==null)continue;const f=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?new TextEncoder().encode($):$;let M=new Uint8Array(S.length+f.length);M.set(S),M.set(f,S.length),S=M;let J;while((J=dY(S))!==-1)yield S.slice(0,J),S=S.slice(J)}if(S.length>0)yield S}function dY(T){for(let f=0;f<T.length-2;f++){if(T[f]===10&&T[f+1]===10)return f+2;if(T[f]===13&&T[f+1]===13)return f+2;if(T[f]===13&&T[f+1]===10&&f+3<T.length&&T[f+2]===13&&T[f+3]===10)return f+4}return-1}function rY(T,S){const $=T.indexOf(S);if($!==-1)return[T.substring(0,$),S,T.substring($+S.length)];return[T,"",""]}function fw(T){if(T[Symbol.asyncIterator])return T;const S=T.getReader();return{async next(){try{const $=await S.read();if($?.done)S.releaseLock();return $}catch($){throw S.releaseLock(),$}},async return(){const $=S.cancel();return S.releaseLock(),await $,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}class NS{constructor(T,S){this.iterator=T,this.controller=S}static fromSSEResponse(T,S){let $=!1;async function*f(){if($)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");$=!0;let M=!1;try{for await(let J of uY(T,S)){if(M)continue;if(J.data.startsWith("[DONE]")){M=!0;continue}if(J.event===null){let F;try{F=JSON.parse(J.data)}catch(W){throw console.error("Could not parse message into JSON:",J.data),console.error("From chunk:",J.raw),W}if(F&&F.error)throw new oT(void 0,F.error,void 0,void 0);yield F}else{let F;try{F=JSON.parse(J.data)}catch(W){throw console.error("Could not parse message into JSON:",J.data),console.error("From chunk:",J.raw),W}if(J.event=="error")throw new oT(void 0,F.error,F.message,void 0);yield{event:J.event,data:F}}}M=!0}catch(J){if(J instanceof Error&&J.name==="AbortError")return;throw J}finally{if(!M)S.abort()}}return new NS(f,S)}static fromReadableStream(T,S){let $=!1;async function*f(){const J=new m$,F=fw(T);for await(let W of F)for(let k of J.decode(W))yield k;for(let W of J.flush())yield W}async function*M(){if($)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");$=!0;let J=!1;try{for await(let F of f()){if(J)continue;if(F)yield JSON.parse(F)}J=!0}catch(F){if(F instanceof Error&&F.name==="AbortError")return;throw F}finally{if(!J)S.abort()}}return new NS(M,S)}[Symbol.asyncIterator](){return this.iterator()}tee(){const T=[],S=[],$=this.iterator(),f=(M)=>{return{next:()=>{if(M.length===0){const J=$.next();T.push(J),S.push(J)}return M.shift()}}};return[new NS(()=>f(T),this.controller),new NS(()=>f(S),this.controller)]}toReadableStream(){const T=this;let S;const $=new TextEncoder;return new _0({async start(){S=T[Symbol.asyncIterator]()},async pull(f){try{const{value:M,done:J}=await S.next();if(J)return f.close();const F=$.encode(JSON.stringify(M)+"\n");f.enqueue(F)}catch(M){f.error(M)}},async cancel(){await S.return?.()}})}}class $w{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(T){if(T.endsWith("\r"))T=T.substring(0,T.length-1);if(!T){if(!this.event&&!this.data.length)return null;const M={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],M}if(this.chunks.push(T),T.startsWith(":"))return null;let[S,$,f]=rY(T,":");if(f.startsWith(" "))f=f.substring(1);if(S==="event")this.event=f;else if(S==="data")this.data.push(f);return null}}async function L0(T,S,$){if(T=await T,Jw(T))return T;if(Mw(T)){const M=await T.blob();S||(S=new URL(T.url).pathname.split(/[\\/]/).pop()??"unknown_file");const J=AJ(M)?[await M.arrayBuffer()]:[M];return new GF(J,S,$)}const f=await eY(T);if(S||(S=T6(T)??"unknown_file"),!$?.type){const M=f[0]?.type;if(typeof M==="string")$={...$,type:M}}return new GF(f,S,$)}async function eY(T){let S=[];if(typeof T==="string"||ArrayBuffer.isView(T)||T instanceof ArrayBuffer)S.push(T);else if(AJ(T))S.push(await T.arrayBuffer());else if(S6(T))for await(let $ of T)S.push($);else throw new Error(`Unexpected data type: ${typeof T}; constructor: ${T?.constructor?.name}; props: ${sY(T)}`);return S}function sY(T){return`[${Object.getOwnPropertyNames(T).map(($)=>`"${$}"`).join(", ")}]`}function T6(T){return U0(T.name)||U0(T.filename)||U0(T.path)?.split(/[\\/]/).pop()}var Mw=(T)=>T!=null&&typeof T==="object"&&typeof T.url==="string"&&typeof T.blob==="function",Jw=(T)=>T!=null&&typeof T==="object"&&typeof T.name==="string"&&typeof T.lastModified==="number"&&AJ(T),AJ=(T)=>T!=null&&typeof T==="object"&&typeof T.size==="number"&&typeof T.type==="string"&&typeof T.text==="function"&&typeof T.slice==="function"&&typeof T.arrayBuffer==="function",aY=(T)=>{return Jw(T)||Mw(T)||y0(T)},U0=(T)=>{if(typeof T==="string")return T;if(typeof Buffer!=="undefined"&&T instanceof Buffer)return String(T);return},S6=(T)=>T!=null&&typeof T==="object"&&typeof T[Symbol.asyncIterator]==="function",B0=(T)=>T&&typeof T==="object"&&T.body&&T[Symbol.toStringTag]==="MultipartBody";var vS=async(T)=>{const S=await Fw(T.body);return E0(S,T)},Fw=async(T)=>{const S=new H0;return await Promise.all(Object.entries(T||{}).map(([$,f])=>V0(S,$,f))),S};var V0=async(T,S,$)=>{if($===void 0)return;if($==null)throw new TypeError(`Received null for "${S}"; to pass null in FormData, you must use the string 'null'`);if(typeof $==="string"||typeof $==="number"||typeof $==="boolean")T.append(S,String($));else if(aY($)){const f=await L0($);T.append(S,f)}else if(Array.isArray($))await Promise.all($.map((f)=>V0(T,S+"[]",f)));else if(typeof $==="object")await Promise.all(Object.entries($).map(([f,M])=>V0(T,`${S}[${f}]`,M)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${$} instead`)};async function Kw(T){const{response:S}=T;if(T.options.stream){if(SM("response",S.status,S.url,S.headers,S.body),T.options.__streamClass)return T.options.__streamClass.fromSSEResponse(S,T.controller);return NS.fromSSEResponse(S,T.controller)}if(S.status===204)return null;if(T.options.__binaryResponse)return S;const $=S.headers.get("content-type");if($?.includes("application/json")||$?.includes("application/vnd.api+json")){const J=await S.json();return SM("response",S.status,S.url,S.headers,J),Aw(J,S)}const M=await S.text();return SM("response",S.status,S.url,S.headers,M),M}function Aw(T,S){if(!T||typeof T!=="object"||Array.isArray(T))return T;return Object.defineProperty(T,"_request_id",{value:S.headers.get("x-request-id"),enumerable:!1})}function k6(){if(typeof navigator==="undefined"||!navigator)return null;const T=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:S,pattern:$}of T){const f=$.exec(navigator.userAgent);if(f){const M=f[1]||0,J=f[2]||0,F=f[3]||0;return{browser:S,version:`${M}.${J}.${F}`}}}return null}function Ow(T){if(!T)return!0;for(let S in T)return!1;return!0}function Rw(T,S){return Object.prototype.hasOwnProperty.call(T,S)}function ww(T,S){for(let $ in S){if(!Rw(S,$))continue;const f=$.toLowerCase();if(!f)continue;const M=S[$];if(M===null)delete T[f];else if(M!==void 0)T[f]=M}}function SM(T,...S){if(typeof process!=="undefined"&&process?.env?.DEBUG==="true")console.log(`OpenAI:DEBUG:${T}`,...S)}function OJ(T){return T!=null&&typeof T==="object"&&!Array.isArray(T)}var f6=function(T,S,$,f,M){if(f==="m")throw new TypeError("Private method is not writable");if(f==="a"&&!M)throw new TypeError("Private accessor was defined without a setter");if(typeof S==="function"?T!==S||!M:!S.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return f==="a"?M.call(T,$):M?M.value=$:S.set(T,$),$},M6=function(T,S,$,f){if($==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof S==="function"?T!==S||!f:!S.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return $==="m"?f:$==="a"?f.call(T):f?f.value:S.get(T)},HF;class EF extends Promise{constructor(T,S=Kw){super(($)=>{$(null)});this.responsePromise=T,this.parseResponse=S}_thenUnwrap(T){return new EF(this.responsePromise,async(S)=>Aw(T(await this.parseResponse(S),S),S.response))}asResponse(){return this.responsePromise.then((T)=>T.response)}async withResponse(){const[T,S]=await Promise.all([this.parse(),this.asResponse()]);return{data:T,response:S,request_id:S.headers.get("x-request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(this.parseResponse);return this.parsedPromise}then(T,S){return this.parse().then(T,S)}catch(T){return this.parse().catch(T)}finally(T){return this.parse().finally(T)}}class C0{constructor({baseURL:T,maxRetries:S=2,timeout:$=600000,httpAgent:f,fetch:M}){this.baseURL=T,this.maxRetries=N0("maxRetries",S),this.timeout=N0("timeout",$),this.httpAgent=f,this.fetch=M??z0}authHeaders(T){return{}}defaultHeaders(T){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...X6(),...this.authHeaders(T)}}validateHeaders(T,S){}defaultIdempotencyKey(){return`stainless-node-retry-${Y6()}`}get(T,S){return this.methodRequest("get",T,S)}post(T,S){return this.methodRequest("post",T,S)}patch(T,S){return this.methodRequest("patch",T,S)}put(T,S){return this.methodRequest("put",T,S)}delete(T,S){return this.methodRequest("delete",T,S)}methodRequest(T,S,$){return this.request(Promise.resolve($).then(async(f)=>{const M=f&&AJ(f?.body)?new DataView(await f.body.arrayBuffer()):f?.body instanceof DataView?f.body:f?.body instanceof ArrayBuffer?new DataView(f.body):f&&ArrayBuffer.isView(f?.body)?new DataView(f.body.buffer):f?.body;return{method:T,path:S,...f,body:M}}))}getAPIList(T,S,$){return this.requestAPIList(S,{method:"get",path:T,...$})}calculateContentLength(T){if(typeof T==="string"){if(typeof Buffer!=="undefined")return Buffer.byteLength(T,"utf8").toString();if(typeof TextEncoder!=="undefined")return new TextEncoder().encode(T).length.toString()}else if(ArrayBuffer.isView(T))return T.byteLength.toString();return null}buildRequest(T,{retryCount:S=0}={}){const{method:$,path:f,query:M,headers:J={}}=T,F=ArrayBuffer.isView(T.body)||T.__binaryRequest&&typeof T.body==="string"?T.body:B0(T.body)?T.body.body:T.body?JSON.stringify(T.body,null,2):null,W=this.calculateContentLength(F),k=this.buildURL(f,M);if("timeout"in T)N0("timeout",T.timeout);const X=T.timeout??this.timeout,w=T.httpAgent??this.httpAgent??D0(k),K=X+1000;if(typeof w?.options?.timeout==="number"&&K>(w.options.timeout??0))w.options.timeout=K;if(this.idempotencyHeader&&$!=="get"){if(!T.idempotencyKey)T.idempotencyKey=this.defaultIdempotencyKey();J[this.idempotencyHeader]=T.idempotencyKey}const O=this.buildHeaders({options:T,headers:J,contentLength:W,retryCount:S});return{req:{method:$,...F&&{body:F},headers:O,...w&&{agent:w},signal:T.signal??null},url:k,timeout:X}}buildHeaders({options:T,headers:S,contentLength:$,retryCount:f}){const M={};if($)M["content-length"]=$;const J=this.defaultHeaders(T);if(ww(M,J),ww(M,S),B0(T.body)&&e$!=="node")delete M["content-type"];if(R6(S,"x-stainless-retry-count")===void 0)M["x-stainless-retry-count"]=String(f);return this.validateHeaders(M,S),M}async prepareOptions(T){}async prepareRequest(T,{url:S,options:$}){}parseHeaders(T){return!T?{}:(Symbol.iterator in T)?Object.fromEntries(Array.from(T).map((S)=>[...S])):{...T}}makeStatusError(T,S,$,f){return oT.generate(T,S,$,f)}request(T,S=null){return new EF(this.makeRequest(T,S))}async makeRequest(T,S){const $=await T,f=$.maxRetries??this.maxRetries;if(S==null)S=f;await this.prepareOptions($);const{req:M,url:J,timeout:F}=this.buildRequest($,{retryCount:f-S});if(await this.prepareRequest(M,{url:J,options:$}),SM("request",J,$,M.headers),$.signal?.aborted)throw new SS;const W=new AbortController,k=await this.fetchWithTimeout(J,M,F,W).catch(_F);if(k instanceof Error){if($.signal?.aborted)throw new SS;if(S)return this.retryRequest($,S);if(k.name==="AbortError")throw new Sf;throw new Tf({cause:k})}const X=J6(k.headers);if(!k.ok){if(S&&this.shouldRetry(k)){const Q=`retrying, ${S} attempts remaining`;return SM(`response (error; ${Q})`,k.status,J,X),this.retryRequest($,S,X)}const w=await k.text().catch((Q)=>_F(Q).message),K=w6(w),O=K?void 0:w;throw SM(`response (error; ${S?"(error; no more retries left)":"(error; not retryable)"})`,k.status,J,X,O),this.makeStatusError(k.status,K,O,X)}return{response:k,options:$,controller:W}}requestAPIList(T,S){const $=this.makeRequest(S,null);return new Yw(this,$,T)}buildURL(T,S){const $=A6(T)?new URL(T):new URL(this.baseURL+(this.baseURL.endsWith("/")&&T.startsWith("/")?T.slice(1):T)),f=this.defaultQuery();if(!Ow(f))S={...f,...S};if(typeof S==="object"&&S&&!Array.isArray(S))$.search=this.stringifyQuery(S);return $.toString()}stringifyQuery(T){return Object.entries(T).filter(([S,$])=>typeof $!=="undefined").map(([S,$])=>{if(typeof $==="string"||typeof $==="number"||typeof $==="boolean")return`${encodeURIComponent(S)}=${encodeURIComponent($)}`;if($===null)return`${encodeURIComponent(S)}=`;throw new $T(`Cannot stringify type ${typeof $}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(T,S,$,f){const{signal:M,...J}=S||{};if(M)M.addEventListener("abort",()=>f.abort());const F=setTimeout(()=>f.abort(),$);return this.getRequestClient().fetch.call(void 0,T,{signal:f.signal,...J}).finally(()=>{clearTimeout(F)})}getRequestClient(){return{fetch:this.fetch}}shouldRetry(T){const S=T.headers.get("x-should-retry");if(S==="true")return!0;if(S==="false")return!1;if(T.status===408)return!0;if(T.status===409)return!0;if(T.status===429)return!0;if(T.status>=500)return!0;return!1}async retryRequest(T,S,$){let f;const M=$?.["retry-after-ms"];if(M){const F=parseFloat(M);if(!Number.isNaN(F))f=F}const J=$?.["retry-after"];if(J&&!f){const F=parseFloat(J);if(!Number.isNaN(F))f=F*1000;else f=Date.parse(J)-Date.now()}if(!(f&&0<=f&&f<60000)){const F=T.maxRetries??this.maxRetries;f=this.calculateDefaultRetryTimeoutMillis(S,F)}return await E$(f),this.makeRequest(T,S-1)}calculateDefaultRetryTimeoutMillis(T,S){const M=S-T,J=Math.min(0.5*Math.pow(2,M),8),F=1-Math.random()*0.25;return J*F*1000}getUserAgent(){return`${this.constructor.name}/JS ${a$}`}}class DF{constructor(T,S,$,f){HF.set(this,void 0),f6(this,HF,T,"f"),this.options=f,this.response=S,this.body=$}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageInfo()!=null}async getNextPage(){const T=this.nextPageInfo();if(!T)throw new $T("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");const S={...this.options};if("params"in T&&typeof S.query==="object")S.query={...S.query,...T.params};else if("url"in T){const $=[...Object.entries(S.query||{}),...T.url.searchParams.entries()];for(let[f,M]of $)T.url.searchParams.set(f,M);S.query=void 0,S.path=T.url.toString()}return await M6(this,HF,"f").requestAPIList(this.constructor,S)}async*iterPages(){let T=this;yield T;while(T.hasNextPage())T=await T.getNextPage(),yield T}async*[(HF=new WeakMap,Symbol.asyncIterator)](){for await(let T of this.iterPages())for(let S of T.getPaginatedItems())yield S}}class Yw extends EF{constructor(T,S,$){super(S,async(f)=>new $(T,f.response,await Kw(f),f.options))}async*[Symbol.asyncIterator](){const T=await this;for await(let S of T)yield S}}var J6=(T)=>{return new Proxy(Object.fromEntries(T.entries()),{get(S,$){const f=$.toString();return S[f.toLowerCase()]||S[f]}})},F6={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},LT=(T)=>{return typeof T==="object"&&T!==null&&!Ow(T)&&Object.keys(T).every((S)=>Rw(F6,S))},W6=()=>{if(typeof Deno!=="undefined"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":a$,"X-Stainless-OS":kw(Deno.build.os),"X-Stainless-Arch":Ww(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime!=="undefined")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":a$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process!=="undefined"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":a$,"X-Stainless-OS":kw(process.platform),"X-Stainless-Arch":Ww(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const T=k6();if(T)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":a$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${T.browser}`,"X-Stainless-Runtime-Version":T.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":a$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},Ww=(T)=>{if(T==="x32")return"x32";if(T==="x86_64"||T==="x64")return"x64";if(T==="arm")return"arm";if(T==="aarch64"||T==="arm64")return"arm64";if(T)return`other:${T}`;return"unknown"},kw=(T)=>{if(T=T.toLowerCase(),T.includes("ios"))return"iOS";if(T==="android")return"Android";if(T==="darwin")return"MacOS";if(T==="win32")return"Windows";if(T==="freebsd")return"FreeBSD";if(T==="openbsd")return"OpenBSD";if(T==="linux")return"Linux";if(T)return`Other:${T}`;return"Unknown"},Xw,X6=()=>{return Xw??(Xw=W6())},w6=(T)=>{try{return JSON.parse(T)}catch(S){return}},K6=new RegExp("^(?:[a-z]+:)?//","i"),A6=(T)=>{return K6.test(T)},E$=(T)=>new Promise((S)=>setTimeout(S,T)),N0=(T,S)=>{if(typeof S!=="number"||!Number.isInteger(S))throw new $T(`${T} must be an integer`);if(S<0)throw new $T(`${T} must be a positive integer`);return S},_F=(T)=>{if(T instanceof Error)return T;if(typeof T==="object"&&T!==null)try{return new Error(JSON.stringify(T))}catch{}return new Error(T)};var YJ=(T)=>{if(typeof process!=="undefined")return process.env?.[T]?.trim()??void 0;if(typeof Deno!=="undefined")return Deno.env?.get?.(T)?.trim();return};var Y6=()=>{return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(T)=>{const S=Math.random()*16|0;return(T==="x"?S:S&3|8).toString(16)})},Gw=()=>{return typeof window!=="undefined"&&typeof window.document!=="undefined"&&typeof navigator!=="undefined"},O6=(T)=>{return typeof T?.get==="function"};var R6=(T,S)=>{const $=S.toLowerCase();if(O6(T)){const f=S[0]?.toUpperCase()+S.substring(1).replace(/([^\w])(\w)/g,(M,J,F)=>J+F.toUpperCase());for(let M of[S,$,S.toUpperCase(),f]){const J=T.get(M);if(J)return J}}for(let[f,M]of Object.entries(T))if(f.toLowerCase()===$){if(Array.isArray(M)){if(M.length<=1)return M[0];return console.warn(`Received ${M.length} entries for the ${S} header, using the first entry.`),M[0]}return M}return};class $T extends Error{}class oT extends $T{constructor(T,S,$,f){super(`${oT.makeMessage(T,S,$)}`);this.status=T,this.headers=f,this.request_id=f?.["x-request-id"];const M=S;this.error=M,this.code=M?.code,this.param=M?.param,this.type=M?.type}static makeMessage(T,S,$){const f=S?.message?typeof S.message==="string"?S.message:JSON.stringify(S.message):S?JSON.stringify(S):$;if(T&&f)return`${T} ${f}`;if(T)return`${T} status code (no body)`;if(f)return f;return"(no status code or body)"}static generate(T,S,$,f){if(!T)return new Tf({message:$,cause:_F(S)});const M=S?.error;if(T===400)return new yF(T,M,$,f);if(T===401)return new QF(T,M,$,f);if(T===403)return new UF(T,M,$,f);if(T===404)return new VF(T,M,$,f);if(T===409)return new LF(T,M,$,f);if(T===422)return new BF(T,M,$,f);if(T===429)return new NF(T,M,$,f);if(T>=500)return new CF(T,M,$,f);return new oT(T,M,$,f)}}class SS extends oT{constructor({message:T}={}){super(void 0,void 0,T||"Request was aborted.",void 0);this.status=void 0}}class Tf extends oT{constructor({message:T,cause:S}){super(void 0,void 0,T||"Connection error.",void 0);if(this.status=void 0,S)this.cause=S}}class Sf extends Tf{constructor({message:T}={}){super({message:T??"Request timed out."})}}class yF extends oT{constructor(){super(...arguments);this.status=400}}class QF extends oT{constructor(){super(...arguments);this.status=401}}class UF extends oT{constructor(){super(...arguments);this.status=403}}class VF extends oT{constructor(){super(...arguments);this.status=404}}class LF extends oT{constructor(){super(...arguments);this.status=409}}class BF extends oT{constructor(){super(...arguments);this.status=422}}class NF extends oT{constructor(){super(...arguments);this.status=429}}class CF extends oT{}class RJ extends $T{constructor(){super("Could not parse response content as the length limit was reached")}}class GJ extends $T{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}var xF="RFC3986",jF={RFC1738:(T)=>String(T).replace(/%20/g,"+"),RFC3986:(T)=>String(T)},zw="RFC1738";function _w(T){if(!T||typeof T!=="object")return!1;return!!(T.constructor&&T.constructor.isBuffer&&T.constructor.isBuffer(T))}function j0(T,S){if(z6(T)){const $=[];for(let f=0;f<T.length;f+=1)$.push(S(T[f]));return $}return S(T)}var z6=Array.isArray,X$=(()=>{const T=[];for(let S=0;S<256;++S)T.push("%"+((S<16?"0":"")+S.toString(16)).toUpperCase());return T})(),x0=1024,Hw=(T,S,$,f,M)=>{if(T.length===0)return T;let J=T;if(typeof T==="symbol")J=Symbol.prototype.toString.call(T);else if(typeof T!=="string")J=String(T);if($==="iso-8859-1")return escape(J).replace(/%u[0-9a-f]{4}/gi,function(W){return"%26%23"+parseInt(W.slice(2),16)+"%3B"});let F="";for(let W=0;W<J.length;W+=x0){const k=J.length>=x0?J.slice(W,W+x0):J,X=[];for(let w=0;w<k.length;++w){let K=k.charCodeAt(w);if(K===45||K===46||K===95||K===126||K>=48&&K<=57||K>=65&&K<=90||K>=97&&K<=122||M===zw&&(K===40||K===41)){X[X.length]=k.charAt(w);continue}if(K<128){X[X.length]=X$[K];continue}if(K<2048){X[X.length]=X$[192|K>>6]+X$[128|K&63];continue}if(K<55296||K>=57344){X[X.length]=X$[224|K>>12]+X$[128|K>>6&63]+X$[128|K&63];continue}w+=1,K=65536+((K&1023)<<10|k.charCodeAt(w)&1023),X[X.length]=X$[240|K>>18]+X$[128|K>>12&63]+X$[128|K>>6&63]+X$[128|K&63]}F+=X.join("")}return F};function D6(T){return typeof T==="string"||typeof T==="number"||typeof T==="boolean"||typeof T==="symbol"||typeof T==="bigint"}function yw(T,S,$,f,M,J,F,W,k,X,w,K,O,H,_,Q,N,V){let U=T,C=V,B=0,D=!1;while((C=C.get(I0))!==void 0&&!D){const G=C.get(T);if(B+=1,typeof G!=="undefined")if(G===B)throw new RangeError("Cyclic object value");else D=!0;if(typeof C.get(I0)==="undefined")B=0}if(typeof X==="function")U=X(S,U);else if(U instanceof Date)U=O?.(U);else if($==="comma"&&w$(U))U=j0(U,function(G){if(G instanceof Date)return O?.(G);return G});if(U===null){if(J)return k&&!Q?k(S,dT.encoder,N,"key",H):S;U=""}if(D6(U)||_w(U)){if(k){const G=Q?S:k(S,dT.encoder,N,"key",H);return[_?.(G)+"="+_?.(k(U,dT.encoder,N,"value",H))]}return[_?.(S)+"="+_?.(String(U))]}const z=[];if(typeof U==="undefined")return z;let y;if($==="comma"&&w$(U)){if(Q&&k)U=j0(U,k);y=[{value:U.length>0?U.join(",")||null:void 0}]}else if(w$(X))y=X;else{const G=Object.keys(U);y=w?G.sort(w):G}const j=W?String(S).replace(/\./g,"%2E"):String(S),v=f&&w$(U)&&U.length===1?j+"[]":j;if(M&&w$(U)&&U.length===0)return v+"[]";for(let G=0;G<y.length;++G){const m=y[G],q=typeof m==="object"&&typeof m.value!=="undefined"?m.value:U[m];if(F&&q===null)continue;const d=K&&W?m.replace(/\./g,"%2E"):m,MT=w$(U)?typeof $==="function"?$(v,d):v:v+(K?"."+d:"["+d+"]");V.set(T,B);const JT=new WeakMap;JT.set(I0,V),Dw(z,yw(q,MT,$,f,M,J,F,W,$==="comma"&&Q&&w$(U)?null:k,X,w,K,O,H,_,Q,N,JT))}return z}function y6(T=dT){if(typeof T.allowEmptyArrays!=="undefined"&&typeof T.allowEmptyArrays!=="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof T.encodeDotInKeys!=="undefined"&&typeof T.encodeDotInKeys!=="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(T.encoder!==null&&typeof T.encoder!=="undefined"&&typeof T.encoder!=="function")throw new TypeError("Encoder has to be a function.");const S=T.charset||dT.charset;if(typeof T.charset!=="undefined"&&T.charset!=="utf-8"&&T.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let $=xF;if(typeof T.format!=="undefined"){if(!H6.call(jF,T.format))throw new TypeError("Unknown format option provided.");$=T.format}const f=jF[$];let M=dT.filter;if(typeof T.filter==="function"||w$(T.filter))M=T.filter;let J;if(T.arrayFormat&&T.arrayFormat in Ew)J=T.arrayFormat;else if("indices"in T)J=T.indices?"indices":"repeat";else J=dT.arrayFormat;if("commaRoundTrip"in T&&typeof T.commaRoundTrip!=="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const F=typeof T.allowDots==="undefined"?!!T.encodeDotInKeys===!0?!0:dT.allowDots:!!T.allowDots;return{addQueryPrefix:typeof T.addQueryPrefix==="boolean"?T.addQueryPrefix:dT.addQueryPrefix,allowDots:F,allowEmptyArrays:typeof T.allowEmptyArrays==="boolean"?!!T.allowEmptyArrays:dT.allowEmptyArrays,arrayFormat:J,charset:S,charsetSentinel:typeof T.charsetSentinel==="boolean"?T.charsetSentinel:dT.charsetSentinel,commaRoundTrip:!!T.commaRoundTrip,delimiter:typeof T.delimiter==="undefined"?dT.delimiter:T.delimiter,encode:typeof T.encode==="boolean"?T.encode:dT.encode,encodeDotInKeys:typeof T.encodeDotInKeys==="boolean"?T.encodeDotInKeys:dT.encodeDotInKeys,encoder:typeof T.encoder==="function"?T.encoder:dT.encoder,encodeValuesOnly:typeof T.encodeValuesOnly==="boolean"?T.encodeValuesOnly:dT.encodeValuesOnly,filter:M,format:$,formatter:f,serializeDate:typeof T.serializeDate==="function"?T.serializeDate:dT.serializeDate,skipNulls:typeof T.skipNulls==="boolean"?T.skipNulls:dT.skipNulls,sort:typeof T.sort==="function"?T.sort:null,strictNullHandling:typeof T.strictNullHandling==="boolean"?T.strictNullHandling:dT.strictNullHandling}}function b0(T,S={}){let $=T;const f=y6(S);let M,J;if(typeof f.filter==="function")J=f.filter,$=J("",$);else if(w$(f.filter))J=f.filter,M=J;const F=[];if(typeof $!=="object"||$===null)return"";const W=Ew[f.arrayFormat],k=W==="comma"&&f.commaRoundTrip;if(!M)M=Object.keys($);if(f.sort)M.sort(f.sort);const X=new WeakMap;for(let O=0;O<M.length;++O){const H=M[O];if(f.skipNulls&&$[H]===null)continue;Dw(F,yw($[H],H,W,k,f.allowEmptyArrays,f.strictNullHandling,f.skipNulls,f.encodeDotInKeys,f.encode?f.encoder:null,f.filter,f.sort,f.allowDots,f.serializeDate,f.format,f.formatter,f.encodeValuesOnly,f.charset,X))}const w=F.join(f.delimiter);let K=f.addQueryPrefix===!0?"?":"";if(f.charsetSentinel)if(f.charset==="iso-8859-1")K+="utf8=%26%2310003%3B&";else K+="utf8=%E2%9C%93&";return w.length>0?K+w:""}var H6=Object.prototype.hasOwnProperty,Ew={brackets(T){return String(T)+"[]"},comma:"comma",indices(T,S){return String(T)+"["+S+"]"},repeat(T){return String(T)}},w$=Array.isArray,_6=Array.prototype.push,Dw=function(T,S){_6.apply(T,w$(S)?S:[S])},E6=Date.prototype.toISOString,dT={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Hw,encodeValuesOnly:!1,format:xF,formatter:jF[xF],indices:!1,serializeDate(T){return E6.call(T)},skipNulls:!1,strictNullHandling:!1},I0={};class $f extends DF{constructor(T,S,$,f){super(T,S,$,f);this.data=$.data||[],this.object=$.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class vT extends DF{constructor(T,S,$,f){super(T,S,$,f);this.data=$.data||[]}getPaginatedItems(){return this.data??[]}nextPageParams(){const T=this.nextPageInfo();if(!T)return null;if("params"in T)return T.params;const S=Object.fromEntries(T.url.searchParams);if(!Object.keys(S).length)return null;return S}nextPageInfo(){const T=this.getPaginatedItems();if(!T.length)return null;const S=T[T.length-1]?.id;if(!S)return null;return{params:{after:S}}}}class p{constructor(T){this._client=T}}class $M extends p{create(T,S){return this._client.post("/chat/completions",{body:T,...S,stream:T.stream??!1})}}(function(T){})($M||($M={}));class ff extends p{constructor(){super(...arguments);this.completions=new $M(this._client)}}(function(T){T.Completions=$M})(ff||(ff={}));class fM extends p{create(T,S){return this._client.post("/audio/speech",{body:T,...S,__binaryResponse:!0})}}(function(T){})(fM||(fM={}));class MM extends p{create(T,S){return this._client.post("/audio/transcriptions",vS({body:T,...S}))}}(function(T){})(MM||(MM={}));class JM extends p{create(T,S){return this._client.post("/audio/translations",vS({body:T,...S}))}}(function(T){})(JM||(JM={}));class Mf extends p{constructor(){super(...arguments);this.transcriptions=new MM(this._client),this.translations=new JM(this._client),this.speech=new fM(this._client)}}(function(T){T.Transcriptions=MM,T.Translations=JM,T.Speech=fM})(Mf||(Mf={}));class Jf extends p{create(T,S){return this._client.post("/batches",{body:T,...S})}retrieve(T,S){return this._client.get(`/batches/${T}`,S)}list(T={},S){if(LT(T))return this.list({},T);return this._client.getAPIList("/batches",Ff,{query:T,...S})}cancel(T,S){return this._client.post(`/batches/${T}/cancel`,S)}}class Ff extends vT{}(function(T){T.BatchesPage=Ff})(Jf||(Jf={}));class FM extends p{create(T,S){return this._client.post("/assistants",{body:T,...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}retrieve(T,S){return this._client.get(`/assistants/${T}`,{...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}update(T,S,$){return this._client.post(`/assistants/${T}`,{body:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}list(T={},S){if(LT(T))return this.list({},T);return this._client.getAPIList("/assistants",WM,{query:T,...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}del(T,S){return this._client.delete(`/assistants/${T}`,{...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}}class WM extends vT{}(function(T){T.AssistantsPage=WM})(FM||(FM={}));function q0(T){return typeof T.parse==="function"}var h$=(T)=>{return T?.role==="assistant"},Z0=(T)=>{return T?.role==="function"},m0=(T)=>{return T?.role==="tool"};var sS=function(T,S,$,f,M){if(f==="m")throw new TypeError("Private method is not writable");if(f==="a"&&!M)throw new TypeError("Private accessor was defined without a setter");if(typeof S==="function"?T!==S||!M:!S.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return f==="a"?M.call(T,$):M?M.value=$:S.set(T,$),$},qT=function(T,S,$,f){if($==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof S==="function"?T!==S||!f:!S.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return $==="m"?f:$==="a"?f.call(T):f?f.value:S.get(T)},h0,IF,bF,zJ,HJ,qF,_J,D$,EJ,ZF,mF,kM,Uw;class DJ{constructor(){h0.add(this),this.controller=new AbortController,IF.set(this,void 0),bF.set(this,()=>{}),zJ.set(this,()=>{}),HJ.set(this,void 0),qF.set(this,()=>{}),_J.set(this,()=>{}),D$.set(this,{}),EJ.set(this,!1),ZF.set(this,!1),mF.set(this,!1),kM.set(this,!1),sS(this,IF,new Promise((T,S)=>{sS(this,bF,T,"f"),sS(this,zJ,S,"f")}),"f"),sS(this,HJ,new Promise((T,S)=>{sS(this,qF,T,"f"),sS(this,_J,S,"f")}),"f"),qT(this,IF,"f").catch(()=>{}),qT(this,HJ,"f").catch(()=>{})}_run(T){setTimeout(()=>{T().then(()=>{this._emitFinal(),this._emit("end")},qT(this,h0,"m",Uw).bind(this))},0)}_connected(){if(this.ended)return;qT(this,bF,"f").call(this),this._emit("connect")}get ended(){return qT(this,EJ,"f")}get errored(){return qT(this,ZF,"f")}get aborted(){return qT(this,mF,"f")}abort(){this.controller.abort()}on(T,S){return(qT(this,D$,"f")[T]||(qT(this,D$,"f")[T]=[])).push({listener:S}),this}off(T,S){const $=qT(this,D$,"f")[T];if(!$)return this;const f=$.findIndex((M)=>M.listener===S);if(f>=0)$.splice(f,1);return this}once(T,S){return(qT(this,D$,"f")[T]||(qT(this,D$,"f")[T]=[])).push({listener:S,once:!0}),this}emitted(T){return new Promise((S,$)=>{if(sS(this,kM,!0,"f"),T!=="error")this.once("error",$);this.once(T,S)})}async done(){sS(this,kM,!0,"f"),await qT(this,HJ,"f")}_emit(T,...S){if(qT(this,EJ,"f"))return;if(T==="end")sS(this,EJ,!0,"f"),qT(this,qF,"f").call(this);const $=qT(this,D$,"f")[T];if($)qT(this,D$,"f")[T]=$.filter((f)=>!f.once),$.forEach(({listener:f})=>f(...S));if(T==="abort"){const f=S[0];if(!qT(this,kM,"f")&&!$?.length)Promise.reject(f);qT(this,zJ,"f").call(this,f),qT(this,_J,"f").call(this,f),this._emit("end");return}if(T==="error"){const f=S[0];if(!qT(this,kM,"f")&&!$?.length)Promise.reject(f);qT(this,zJ,"f").call(this,f),qT(this,_J,"f").call(this,f),this._emit("end")}}_emitFinal(){}}IF=new WeakMap,bF=new WeakMap,zJ=new WeakMap,HJ=new WeakMap,qF=new WeakMap,_J=new WeakMap,D$=new WeakMap,EJ=new WeakMap,ZF=new WeakMap,mF=new WeakMap,kM=new WeakMap,h0=new WeakSet,Uw=function T(S){if(sS(this,ZF,!0,"f"),S instanceof Error&&S.name==="AbortError")S=new SS;if(S instanceof SS)return sS(this,mF,!0,"f"),this._emit("abort",S);if(S instanceof $T)return this._emit("error",S);if(S instanceof Error){const $=new $T(S.message);return $.cause=S,this._emit("error",$)}return this._emit("error",new $T(String(S)))};function v0(T){return T?.$brand==="auto-parseable-response-format"}function Wf(T){return T?.$brand==="auto-parseable-tool"}function Vw(T,S){if(!S||!P0(S))return{...T,choices:T.choices.map(($)=>({...$,message:{...$.message,parsed:null,tool_calls:$.message.tool_calls??[]}}))};return yJ(T,S)}function yJ(T,S){const $=T.choices.map((f)=>{if(f.finish_reason==="length")throw new RJ;if(f.finish_reason==="content_filter")throw new GJ;return{...f,message:{...f.message,tool_calls:f.message.tool_calls?.map((M)=>j6(S,M))??[],parsed:f.message.content&&!f.message.refusal?x6(S,f.message.content):null}}});return{...T,choices:$}}function x6(T,S){if(T.response_format?.type!=="json_schema")return null;if(T.response_format?.type==="json_schema"){if("$parseRaw"in T.response_format)return T.response_format.$parseRaw(S);return JSON.parse(S)}return null}function j6(T,S){const $=T.tools?.find((f)=>f.function?.name===S.function.name);return{...S,function:{...S.function,parsed_arguments:Wf($)?$.$parseRaw(S.function.arguments):$?.function.strict?JSON.parse(S.function.arguments):null}}}function Lw(T,S){if(!T)return!1;const $=T.tools?.find((f)=>f.function?.name===S.function.name);return Wf($)||$?.function.strict||!1}function P0(T){if(v0(T.response_format))return!0;return T.tools?.some((S)=>Wf(S)||S.type==="function"&&S.function.strict===!0)??!1}function Bw(T){for(let S of T??[]){if(S.type!=="function")throw new $T(`Currently only \`function\` tool types support auto-parsing; Received \`${S.type}\``);if(S.function.strict!==!0)throw new $T(`The \`${S.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var DS=function(T,S,$,f){if($==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof S==="function"?T!==S||!f:!S.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return $==="m"?f:$==="a"?f.call(T):f?f.value:S.get(T)},KS,n0,hF,c0,g0,o0,Cw,t0,Nw=10;class QJ extends DJ{constructor(){super(...arguments);KS.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(T){this._chatCompletions.push(T),this._emit("chatCompletion",T);const S=T.choices[0]?.message;if(S)this._addMessage(S);return T}_addMessage(T,S=!0){if(!("content"in T))T.content=null;if(this.messages.push(T),S){if(this._emit("message",T),(Z0(T)||m0(T))&&T.content)this._emit("functionCallResult",T.content);else if(h$(T)&&T.function_call)this._emit("functionCall",T.function_call);else if(h$(T)&&T.tool_calls){for(let $ of T.tool_calls)if($.type==="function")this._emit("functionCall",$.function)}}}async finalChatCompletion(){await this.done();const T=this._chatCompletions[this._chatCompletions.length-1];if(!T)throw new $T("stream ended without producing a ChatCompletion");return T}async finalContent(){return await this.done(),DS(this,KS,"m",n0).call(this)}async finalMessage(){return await this.done(),DS(this,KS,"m",hF).call(this)}async finalFunctionCall(){return await this.done(),DS(this,KS,"m",c0).call(this)}async finalFunctionCallResult(){return await this.done(),DS(this,KS,"m",g0).call(this)}async totalUsage(){return await this.done(),DS(this,KS,"m",o0).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const T=this._chatCompletions[this._chatCompletions.length-1];if(T)this._emit("finalChatCompletion",T);const S=DS(this,KS,"m",hF).call(this);if(S)this._emit("finalMessage",S);const $=DS(this,KS,"m",n0).call(this);if($)this._emit("finalContent",$);const f=DS(this,KS,"m",c0).call(this);if(f)this._emit("finalFunctionCall",f);const M=DS(this,KS,"m",g0).call(this);if(M!=null)this._emit("finalFunctionCallResult",M);if(this._chatCompletions.some((J)=>J.usage))this._emit("totalUsage",DS(this,KS,"m",o0).call(this))}async _createChatCompletion(T,S,$){const f=$?.signal;if(f){if(f.aborted)this.controller.abort();f.addEventListener("abort",()=>this.controller.abort())}DS(this,KS,"m",Cw).call(this,S);const M=await T.chat.completions.create({...S,stream:!1},{...$,signal:this.controller.signal});return this._connected(),this._addChatCompletion(yJ(M,S))}async _runChatCompletion(T,S,$){for(let f of S.messages)this._addMessage(f,!1);return await this._createChatCompletion(T,S,$)}async _runFunctions(T,S,$){const{function_call:M="auto",stream:J,...F}=S,W=typeof M!=="string"&&M?.name,{maxChatCompletions:k=Nw}=$||{},X={};for(let K of S.functions)X[K.name||K.function.name]=K;const w=S.functions.map((K)=>({name:K.name||K.function.name,parameters:K.parameters,description:K.description}));for(let K of S.messages)this._addMessage(K,!1);for(let K=0;K<k;++K){const H=(await this._createChatCompletion(T,{...F,function_call:M,functions:w,messages:[...this.messages]},$)).choices[0]?.message;if(!H)throw new $T("missing message in ChatCompletion response");if(!H.function_call)return;const{name:_,arguments:Q}=H.function_call,N=X[_];if(!N){const B=`Invalid function_call: ${JSON.stringify(_)}. Available options are: ${w.map((D)=>JSON.stringify(D.name)).join(", ")}. Please try again`;this._addMessage({role:"function",name:_,content:B});continue}else if(W&&W!==_){const B=`Invalid function_call: ${JSON.stringify(_)}. ${JSON.stringify(W)} requested. Please try again`;this._addMessage({role:"function",name:_,content:B});continue}let V;try{V=q0(N)?await N.parse(Q):Q}catch(B){this._addMessage({role:"function",name:_,content:B instanceof Error?B.message:String(B)});continue}const U=await N.function(V,this),C=DS(this,KS,"m",t0).call(this,U);if(this._addMessage({role:"function",name:_,content:C}),W)return}}async _runTools(T,S,$){const{tool_choice:M="auto",stream:J,...F}=S,W=typeof M!=="string"&&M?.function?.name,{maxChatCompletions:k=Nw}=$||{},X=S.tools.map((O)=>{if(Wf(O)){if(!O.$callback)throw new $T("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:O.$callback,name:O.function.name,description:O.function.description||"",parameters:O.function.parameters,parse:O.$parseRaw,strict:!0}}}return O}),w={};for(let O of X)if(O.type==="function")w[O.function.name||O.function.function.name]=O.function;const K="tools"in S?X.map((O)=>O.type==="function"?{type:"function",function:{name:O.function.name||O.function.function.name,parameters:O.function.parameters,description:O.function.description,strict:O.function.strict}}:O):void 0;for(let O of S.messages)this._addMessage(O,!1);for(let O=0;O<k;++O){const _=(await this._createChatCompletion(T,{...F,tool_choice:M,tools:K,messages:[...this.messages]},$)).choices[0]?.message;if(!_)throw new $T("missing message in ChatCompletion response");if(!_.tool_calls?.length)return;for(let Q of _.tool_calls){if(Q.type!=="function")continue;const N=Q.id,{name:V,arguments:U}=Q.function,C=w[V];if(!C){const y=`Invalid tool_call: ${JSON.stringify(V)}. Available options are: ${Object.keys(w).map((j)=>JSON.stringify(j)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:N,content:y});continue}else if(W&&W!==V){const y=`Invalid tool_call: ${JSON.stringify(V)}. ${JSON.stringify(W)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:N,content:y});continue}let B;try{B=q0(C)?await C.parse(U):U}catch(y){const j=y instanceof Error?y.message:String(y);this._addMessage({role:"tool",tool_call_id:N,content:j});continue}const D=await C.function(B,this),z=DS(this,KS,"m",t0).call(this,D);if(this._addMessage({role:"tool",tool_call_id:N,content:z}),W)return}}return}}KS=new WeakSet,n0=function T(){return DS(this,KS,"m",hF).call(this).content??null},hF=function T(){let S=this.messages.length;while(S-- >0){const $=this.messages[S];if(h$($)){const{function_call:f,...M}=$,J={...M,content:$.content??null,refusal:$.refusal??null};if(f)J.function_call=f;return J}}throw new $T("stream ended without producing a ChatCompletionMessage with role=assistant")},c0=function T(){for(let S=this.messages.length-1;S>=0;S--){const $=this.messages[S];if(h$($)&&$?.function_call)return $.function_call;if(h$($)&&$?.tool_calls?.length)return $.tool_calls.at(-1)?.function}return},g0=function T(){for(let S=this.messages.length-1;S>=0;S--){const $=this.messages[S];if(Z0($)&&$.content!=null)return $.content;if(m0($)&&$.content!=null&&typeof $.content==="string"&&this.messages.some((f)=>f.role==="assistant"&&f.tool_calls?.some((M)=>M.type==="function"&&M.id===$.tool_call_id)))return $.content}return},o0=function T(){const S={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:$}of this._chatCompletions)if($)S.completion_tokens+=$.completion_tokens,S.prompt_tokens+=$.prompt_tokens,S.total_tokens+=$.total_tokens;return S},Cw=function T(S){if(S.n!=null&&S.n>1)throw new $T("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},t0=function T(S){return typeof S==="string"?S:S===void 0?"undefined":JSON.stringify(S)};class XM extends QJ{static runFunctions(T,S,$){const f=new XM,M={...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return f._run(()=>f._runFunctions(T,S,M)),f}static runTools(T,S,$){const f=new XM,M={...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"runTools"}};return f._run(()=>f._runTools(T,S,M)),f}_addMessage(T,S=!0){if(super._addMessage(T,S),h$(T)&&T.content)this._emit("content",T.content)}}function I6(T,S=sT.ALL){if(typeof T!=="string")throw new TypeError(`expecting str, got ${typeof T}`);if(!T.trim())throw new Error(`${T} is empty`);return b6(T.trim(),S)}var sT={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511};class xw extends Error{}class jw extends Error{}var b6=(T,S)=>{const $=T.length;let f=0;const M=(O)=>{throw new xw(`${O} at position ${f}`)},J=(O)=>{throw new jw(`${O} at position ${f}`)},F=()=>{if(K(),f>=$)M("Unexpected end of input");if(T[f]==='"')return W();if(T[f]==="{")return k();if(T[f]==="[")return X();if(T.substring(f,f+4)==="null"||sT.NULL&S&&$-f<4&&"null".startsWith(T.substring(f)))return f+=4,null;if(T.substring(f,f+4)==="true"||sT.BOOL&S&&$-f<4&&"true".startsWith(T.substring(f)))return f+=4,!0;if(T.substring(f,f+5)==="false"||sT.BOOL&S&&$-f<5&&"false".startsWith(T.substring(f)))return f+=5,!1;if(T.substring(f,f+8)==="Infinity"||sT.INFINITY&S&&$-f<8&&"Infinity".startsWith(T.substring(f)))return f+=8,1/0;if(T.substring(f,f+9)==="-Infinity"||sT.MINUS_INFINITY&S&&1<$-f&&$-f<9&&"-Infinity".startsWith(T.substring(f)))return f+=9,-1/0;if(T.substring(f,f+3)==="NaN"||sT.NAN&S&&$-f<3&&"NaN".startsWith(T.substring(f)))return f+=3,NaN;return w()},W=()=>{const O=f;let H=!1;f++;while(f<$&&(T[f]!=='"'||H&&T[f-1]==="\\"))H=T[f]==="\\"?!H:!1,f++;if(T.charAt(f)=='"')try{return JSON.parse(T.substring(O,++f-Number(H)))}catch(_){J(String(_))}else if(sT.STR&S)try{return JSON.parse(T.substring(O,f-Number(H))+'"')}catch(_){return JSON.parse(T.substring(O,T.lastIndexOf("\\"))+'"')}M("Unterminated string literal")},k=()=>{f++,K();const O={};try{while(T[f]!=="}"){if(K(),f>=$&&sT.OBJ&S)return O;const H=W();K(),f++;try{const _=F();Object.defineProperty(O,H,{value:_,writable:!0,enumerable:!0,configurable:!0})}catch(_){if(sT.OBJ&S)return O;else throw _}if(K(),T[f]===",")f++}}catch(H){if(sT.OBJ&S)return O;else M("Expected '}' at end of object")}return f++,O},X=()=>{f++;const O=[];try{while(T[f]!=="]")if(O.push(F()),K(),T[f]===",")f++}catch(H){if(sT.ARR&S)return O;M("Expected ']' at end of array")}return f++,O},w=()=>{if(f===0){if(T==="-"&&sT.NUM&S)M("Not sure what '-' is");try{return JSON.parse(T)}catch(H){if(sT.NUM&S)try{if(T[T.length-1]===".")return JSON.parse(T.substring(0,T.lastIndexOf(".")));return JSON.parse(T.substring(0,T.lastIndexOf("e")))}catch(_){}J(String(H))}}const O=f;if(T[f]==="-")f++;while(T[f]&&!",]}".includes(T[f]))f++;if(f==$&&!(sT.NUM&S))M("Unterminated number literal");try{return JSON.parse(T.substring(O,f))}catch(H){if(T.substring(O,f)==="-"&&sT.NUM&S)M("Not sure what '-' is");try{return JSON.parse(T.substring(O,T.lastIndexOf("e")))}catch(_){J(String(_))}}},K=()=>{while(f<$&&" \n\r\t".includes(T[f]))f++};return F()},i0=(T)=>I6(T,sT.ALL^sT.NUM);function q6(T,S){const{id:$,choices:f,created:M,model:J,system_fingerprint:F,...W}=T,k={...W,id:$,choices:f.map(({message:X,finish_reason:w,index:K,logprobs:O,...H})=>{if(!w)throw new $T(`missing finish_reason for choice ${K}`);const{content:_=null,function_call:Q,tool_calls:N,...V}=X,U=X.role;if(!U)throw new $T(`missing role for choice ${K}`);if(Q){const{arguments:C,name:B}=Q;if(C==null)throw new $T(`missing function_call.arguments for choice ${K}`);if(!B)throw new $T(`missing function_call.name for choice ${K}`);return{...H,message:{content:_,function_call:{arguments:C,name:B},role:U,refusal:X.refusal??null},finish_reason:w,index:K,logprobs:O}}if(N)return{...H,index:K,finish_reason:w,logprobs:O,message:{...V,role:U,content:_,refusal:X.refusal??null,tool_calls:N.map((C,B)=>{const{function:D,type:z,id:y,...j}=C,{arguments:v,name:G,...m}=D||{};if(y==null)throw new $T(`missing choices[${K}].tool_calls[${B}].id\n${nF(T)}`);if(z==null)throw new $T(`missing choices[${K}].tool_calls[${B}].type\n${nF(T)}`);if(G==null)throw new $T(`missing choices[${K}].tool_calls[${B}].function.name\n${nF(T)}`);if(v==null)throw new $T(`missing choices[${K}].tool_calls[${B}].function.arguments\n${nF(T)}`);return{...j,id:y,type:z,function:{...m,name:G,arguments:v}}})}};return{...H,message:{...V,content:_,role:U,refusal:X.refusal??null},finish_reason:w,index:K,logprobs:O}}),created:M,model:J,object:"chat.completion",...F?{system_fingerprint:F}:{}};return Vw(k,S)}function nF(T){return JSON.stringify(T)}function bw(T){return}function qw(T){}var wM=function(T,S,$,f,M){if(f==="m")throw new TypeError("Private method is not writable");if(f==="a"&&!M)throw new TypeError("Private accessor was defined without a setter");if(typeof S==="function"?T!==S||!M:!S.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return f==="a"?M.call(T,$):M?M.value=$:S.set(T,$),$},_T=function(T,S,$,f){if($==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof S==="function"?T!==S||!f:!S.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return $==="m"?f:$==="a"?f.call(T):f?f.value:S.get(T)},rT,y$,KM,v$,p0,vF,u0,l0,d0,PF,r0,Iw;class kf extends QJ{constructor(T){super();rT.add(this),y$.set(this,void 0),KM.set(this,void 0),v$.set(this,void 0),wM(this,y$,T,"f"),wM(this,KM,[],"f")}get currentChatCompletionSnapshot(){return _T(this,v$,"f")}static fromReadableStream(T){const S=new kf(null);return S._run(()=>S._fromReadableStream(T)),S}static createChatCompletion(T,S,$){const f=new kf(S);return f._run(()=>f._runChatCompletion(T,{...S,stream:!0},{...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"stream"}})),f}async _createChatCompletion(T,S,$){super._createChatCompletion;const f=$?.signal;if(f){if(f.aborted)this.controller.abort();f.addEventListener("abort",()=>this.controller.abort())}_T(this,rT,"m",p0).call(this);const M=await T.chat.completions.create({...S,stream:!0},{...$,signal:this.controller.signal});this._connected();for await(let J of M)_T(this,rT,"m",u0).call(this,J);if(M.controller.signal?.aborted)throw new SS;return this._addChatCompletion(_T(this,rT,"m",PF).call(this))}async _fromReadableStream(T,S){const $=S?.signal;if($){if($.aborted)this.controller.abort();$.addEventListener("abort",()=>this.controller.abort())}_T(this,rT,"m",p0).call(this),this._connected();const f=NS.fromReadableStream(T,this.controller);let M;for await(let J of f){if(M&&M!==J.id)this._addChatCompletion(_T(this,rT,"m",PF).call(this));_T(this,rT,"m",u0).call(this,J),M=J.id}if(f.controller.signal?.aborted)throw new SS;return this._addChatCompletion(_T(this,rT,"m",PF).call(this))}[(y$=new WeakMap,KM=new WeakMap,v$=new WeakMap,rT=new WeakSet,p0=function T(){if(this.ended)return;wM(this,v$,void 0,"f")},vF=function T(S){let $=_T(this,KM,"f")[S.index];if($)return $;return $={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},_T(this,KM,"f")[S.index]=$,$},u0=function T(S){if(this.ended)return;const $=_T(this,rT,"m",Iw).call(this,S);this._emit("chunk",S,$);for(let f of S.choices){const M=$.choices[f.index];if(f.delta.content!=null&&M.message?.role==="assistant"&&M.message?.content)this._emit("content",f.delta.content,M.message.content),this._emit("content.delta",{delta:f.delta.content,snapshot:M.message.content,parsed:M.message.parsed});if(f.delta.refusal!=null&&M.message?.role==="assistant"&&M.message?.refusal)this._emit("refusal.delta",{delta:f.delta.refusal,snapshot:M.message.refusal});if(f.logprobs?.content!=null&&M.message?.role==="assistant")this._emit("logprobs.content.delta",{content:f.logprobs?.content,snapshot:M.logprobs?.content??[]});if(f.logprobs?.refusal!=null&&M.message?.role==="assistant")this._emit("logprobs.refusal.delta",{refusal:f.logprobs?.refusal,snapshot:M.logprobs?.refusal??[]});const J=_T(this,rT,"m",vF).call(this,M);if(M.finish_reason){if(_T(this,rT,"m",d0).call(this,M),J.current_tool_call_index!=null)_T(this,rT,"m",l0).call(this,M,J.current_tool_call_index)}for(let F of f.delta.tool_calls??[]){if(J.current_tool_call_index!==F.index){if(_T(this,rT,"m",d0).call(this,M),J.current_tool_call_index!=null)_T(this,rT,"m",l0).call(this,M,J.current_tool_call_index)}J.current_tool_call_index=F.index}for(let F of f.delta.tool_calls??[]){const W=M.message.tool_calls?.[F.index];if(!W?.type)continue;if(W?.type==="function")this._emit("tool_calls.function.arguments.delta",{name:W.function?.name,index:F.index,arguments:W.function.arguments,parsed_arguments:W.function.parsed_arguments,arguments_delta:F.function?.arguments??""});else qw(W?.type)}}},l0=function T(S,$){if(_T(this,rT,"m",vF).call(this,S).done_tool_calls.has($))return;const M=S.message.tool_calls?.[$];if(!M)throw new Error("no tool call snapshot");if(!M.type)throw new Error("tool call snapshot missing `type`");if(M.type==="function"){const J=_T(this,y$,"f")?.tools?.find((F)=>F.type==="function"&&F.function.name===M.function.name);this._emit("tool_calls.function.arguments.done",{name:M.function.name,index:$,arguments:M.function.arguments,parsed_arguments:Wf(J)?J.$parseRaw(M.function.arguments):J?.function.strict?JSON.parse(M.function.arguments):null})}else qw(M.type)},d0=function T(S){const $=_T(this,rT,"m",vF).call(this,S);if(S.message.content&&!$.content_done){$.content_done=!0;const f=_T(this,rT,"m",r0).call(this);this._emit("content.done",{content:S.message.content,parsed:f?f.$parseRaw(S.message.content):null})}if(S.message.refusal&&!$.refusal_done)$.refusal_done=!0,this._emit("refusal.done",{refusal:S.message.refusal});if(S.logprobs?.content&&!$.logprobs_content_done)$.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:S.logprobs.content});if(S.logprobs?.refusal&&!$.logprobs_refusal_done)$.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:S.logprobs.refusal})},PF=function T(){if(this.ended)throw new $T("stream has ended, this shouldn't happen");const S=_T(this,v$,"f");if(!S)throw new $T("request ended without sending any chunks");return wM(this,v$,void 0,"f"),wM(this,KM,[],"f"),q6(S,_T(this,y$,"f"))},r0=function T(){const S=_T(this,y$,"f")?.response_format;if(v0(S))return S;return null},Iw=function T(S){var $,f,M,J;let F=_T(this,v$,"f");const{choices:W,...k}=S;if(!F)F=wM(this,v$,{...k,choices:[]},"f");else Object.assign(F,k);for(let{delta:X,finish_reason:w,index:K,logprobs:O=null,...H}of S.choices){let _=F.choices[K];if(!_)_=F.choices[K]={finish_reason:w,index:K,message:{},logprobs:O,...H};if(O)if(!_.logprobs)_.logprobs=Object.assign({},O);else{const{content:D,refusal:z,...y}=O;if(bw(y),Object.assign(_.logprobs,y),D)($=_.logprobs).content??($.content=[]),_.logprobs.content.push(...D);if(z)(f=_.logprobs).refusal??(f.refusal=[]),_.logprobs.refusal.push(...z)}if(w){if(_.finish_reason=w,_T(this,y$,"f")&&P0(_T(this,y$,"f"))){if(w==="length")throw new RJ;if(w==="content_filter")throw new GJ}}if(Object.assign(_,H),!X)continue;const{content:Q,refusal:N,function_call:V,role:U,tool_calls:C,...B}=X;if(bw(B),Object.assign(_.message,B),N)_.message.refusal=(_.message.refusal||"")+N;if(U)_.message.role=U;if(V)if(!_.message.function_call)_.message.function_call=V;else{if(V.name)_.message.function_call.name=V.name;if(V.arguments)(M=_.message.function_call).arguments??(M.arguments=""),_.message.function_call.arguments+=V.arguments}if(Q){if(_.message.content=(_.message.content||"")+Q,!_.message.refusal&&_T(this,rT,"m",r0).call(this))_.message.parsed=i0(_.message.content)}if(C){if(!_.message.tool_calls)_.message.tool_calls=[];for(let{index:D,id:z,type:y,function:j,...v}of C){const G=(J=_.message.tool_calls)[D]??(J[D]={});if(Object.assign(G,v),z)G.id=z;if(y)G.type=y;if(j)G.function??(G.function={name:j.name??"",arguments:""});if(j?.name)G.function.name=j.name;if(j?.arguments){if(G.function.arguments+=j.arguments,Lw(_T(this,y$,"f"),G))G.function.parsed_arguments=i0(G.function.arguments)}}}}return F},Symbol.asyncIterator)](){const T=[],S=[];let $=!1;return this.on("chunk",(f)=>{const M=S.shift();if(M)M.resolve(f);else T.push(f)}),this.on("end",()=>{$=!0;for(let f of S)f.resolve(void 0);S.length=0}),this.on("abort",(f)=>{$=!0;for(let M of S)M.reject(f);S.length=0}),this.on("error",(f)=>{$=!0;for(let M of S)M.reject(f);S.length=0}),{next:async()=>{if(!T.length){if($)return{value:void 0,done:!0};return new Promise((M,J)=>S.push({resolve:M,reject:J})).then((M)=>M?{value:M,done:!1}:{value:void 0,done:!0})}return{value:T.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new NS(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}class Xf extends kf{static fromReadableStream(T){const S=new Xf(null);return S._run(()=>S._fromReadableStream(T)),S}static runFunctions(T,S,$){const f=new Xf(null),M={...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return f._run(()=>f._runFunctions(T,S,M)),f}static runTools(T,S,$){const f=new Xf(S),M={...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"runTools"}};return f._run(()=>f._runTools(T,S,M)),f}}class cF extends p{parse(T,S){return Bw(T.tools),this._client.chat.completions.create(T,{...S,headers:{...S?.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap(($)=>yJ($,T))}runFunctions(T,S){if(T.stream)return Xf.runFunctions(this._client,T,S);return XM.runFunctions(this._client,T,S)}runTools(T,S){if(T.stream)return Xf.runTools(this._client,T,S);return XM.runTools(this._client,T,S)}stream(T,S){return kf.createChatCompletion(this._client,T,S)}}class AM extends p{constructor(){super(...arguments);this.completions=new cF(this._client)}}(function(T){T.Completions=cF})(AM||(AM={}));var l=function(T,S,$,f){if($==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof S==="function"?T!==S||!f:!S.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return $==="m"?f:$==="a"?f.call(T):f?f.value:S.get(T)},CS=function(T,S,$,f,M){if(f==="m")throw new TypeError("Private method is not writable");if(f==="a"&&!M)throw new TypeError("Private accessor was defined without a setter");if(typeof S==="function"?T!==S||!M:!S.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return f==="a"?M.call(T,$):M?M.value=$:S.set(T,$),$},$S,a0,K$,gF,T$,Kf,YM,wf,iF,xS,oF,tF,LJ,UJ,VJ,Zw,mw,hw,vw,Pw,nw,cw;class jS extends DJ{constructor(){super(...arguments);$S.add(this),a0.set(this,[]),K$.set(this,{}),gF.set(this,{}),T$.set(this,void 0),Kf.set(this,void 0),YM.set(this,void 0),wf.set(this,void 0),iF.set(this,void 0),xS.set(this,void 0),oF.set(this,void 0),tF.set(this,void 0),LJ.set(this,void 0)}[(a0=new WeakMap,K$=new WeakMap,gF=new WeakMap,T$=new WeakMap,Kf=new WeakMap,YM=new WeakMap,wf=new WeakMap,iF=new WeakMap,xS=new WeakMap,oF=new WeakMap,tF=new WeakMap,LJ=new WeakMap,$S=new WeakSet,Symbol.asyncIterator)](){const T=[],S=[];let $=!1;return this.on("event",(f)=>{const M=S.shift();if(M)M.resolve(f);else T.push(f)}),this.on("end",()=>{$=!0;for(let f of S)f.resolve(void 0);S.length=0}),this.on("abort",(f)=>{$=!0;for(let M of S)M.reject(f);S.length=0}),this.on("error",(f)=>{$=!0;for(let M of S)M.reject(f);S.length=0}),{next:async()=>{if(!T.length){if($)return{value:void 0,done:!0};return new Promise((M,J)=>S.push({resolve:M,reject:J})).then((M)=>M?{value:M,done:!1}:{value:void 0,done:!0})}return{value:T.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}static fromReadableStream(T){const S=new jS;return S._run(()=>S._fromReadableStream(T)),S}async _fromReadableStream(T,S){const $=S?.signal;if($){if($.aborted)this.controller.abort();$.addEventListener("abort",()=>this.controller.abort())}this._connected();const f=NS.fromReadableStream(T,this.controller);for await(let M of f)l(this,$S,"m",UJ).call(this,M);if(f.controller.signal?.aborted)throw new SS;return this._addRun(l(this,$S,"m",VJ).call(this))}toReadableStream(){return new NS(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(T,S,$,f,M){const J=new jS;return J._run(()=>J._runToolAssistantStream(T,S,$,f,{...M,headers:{...M?.headers,"X-Stainless-Helper-Method":"stream"}})),J}async _createToolAssistantStream(T,S,$,f,M){const J=M?.signal;if(J){if(J.aborted)this.controller.abort();J.addEventListener("abort",()=>this.controller.abort())}const F={...f,stream:!0},W=await T.submitToolOutputs(S,$,F,{...M,signal:this.controller.signal});this._connected();for await(let k of W)l(this,$S,"m",UJ).call(this,k);if(W.controller.signal?.aborted)throw new SS;return this._addRun(l(this,$S,"m",VJ).call(this))}static createThreadAssistantStream(T,S,$){const f=new jS;return f._run(()=>f._threadAssistantStream(T,S,{...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"stream"}})),f}static createAssistantStream(T,S,$,f){const M=new jS;return M._run(()=>M._runAssistantStream(T,S,$,{...f,headers:{...f?.headers,"X-Stainless-Helper-Method":"stream"}})),M}currentEvent(){return l(this,oF,"f")}currentRun(){return l(this,tF,"f")}currentMessageSnapshot(){return l(this,T$,"f")}currentRunStepSnapshot(){return l(this,LJ,"f")}async finalRunSteps(){return await this.done(),Object.values(l(this,K$,"f"))}async finalMessages(){return await this.done(),Object.values(l(this,gF,"f"))}async finalRun(){if(await this.done(),!l(this,Kf,"f"))throw Error("Final run was not received.");return l(this,Kf,"f")}async _createThreadAssistantStream(T,S,$){const f=$?.signal;if(f){if(f.aborted)this.controller.abort();f.addEventListener("abort",()=>this.controller.abort())}const M={...S,stream:!0},J=await T.createAndRun(M,{...$,signal:this.controller.signal});this._connected();for await(let F of J)l(this,$S,"m",UJ).call(this,F);if(J.controller.signal?.aborted)throw new SS;return this._addRun(l(this,$S,"m",VJ).call(this))}async _createAssistantStream(T,S,$,f){const M=f?.signal;if(M){if(M.aborted)this.controller.abort();M.addEventListener("abort",()=>this.controller.abort())}const J={...$,stream:!0},F=await T.create(S,J,{...f,signal:this.controller.signal});this._connected();for await(let W of F)l(this,$S,"m",UJ).call(this,W);if(F.controller.signal?.aborted)throw new SS;return this._addRun(l(this,$S,"m",VJ).call(this))}static accumulateDelta(T,S){for(let[$,f]of Object.entries(S)){if(!T.hasOwnProperty($)){T[$]=f;continue}let M=T[$];if(M===null||M===void 0){T[$]=f;continue}if($==="index"||$==="type"){T[$]=f;continue}if(typeof M==="string"&&typeof f==="string")M+=f;else if(typeof M==="number"&&typeof f==="number")M+=f;else if(OJ(M)&&OJ(f))M=this.accumulateDelta(M,f);else if(Array.isArray(M)&&Array.isArray(f)){if(M.every((J)=>typeof J==="string"||typeof J==="number")){M.push(...f);continue}for(let J of f){if(!OJ(J))throw new Error(`Expected array delta entry to be an object but got: ${J}`);const F=J.index;if(F==null)throw console.error(J),new Error("Expected array delta entry to have an `index` property");if(typeof F!=="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${F}`);const W=M[F];if(W==null)M.push(J);else M[F]=this.accumulateDelta(W,J)}continue}else throw Error(`Unhandled record type: ${$}, deltaValue: ${f}, accValue: ${M}`);T[$]=M}return T}_addRun(T){return T}async _threadAssistantStream(T,S,$){return await this._createThreadAssistantStream(S,T,$)}async _runAssistantStream(T,S,$,f){return await this._createAssistantStream(S,T,$,f)}async _runToolAssistantStream(T,S,$,f,M){return await this._createToolAssistantStream($,T,S,f,M)}}UJ=function T(S){if(this.ended)return;switch(CS(this,oF,S,"f"),l(this,$S,"m",hw).call(this,S),S.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":l(this,$S,"m",cw).call(this,S);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":l(this,$S,"m",mw).call(this,S);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":l(this,$S,"m",Zw).call(this,S);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},VJ=function T(){if(this.ended)throw new $T("stream has ended, this shouldn't happen");if(!l(this,Kf,"f"))throw Error("Final run has not been received");return l(this,Kf,"f")},Zw=function T(S){const[$,f]=l(this,$S,"m",Pw).call(this,S,l(this,T$,"f"));CS(this,T$,$,"f"),l(this,gF,"f")[$.id]=$;for(let M of f){const J=$.content[M.index];if(J?.type=="text")this._emit("textCreated",J.text)}switch(S.event){case"thread.message.created":this._emit("messageCreated",S.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",S.data.delta,$),S.data.delta.content)for(let M of S.data.delta.content){if(M.type=="text"&&M.text){let J=M.text,F=$.content[M.index];if(F&&F.type=="text")this._emit("textDelta",J,F.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(M.index!=l(this,YM,"f")){if(l(this,wf,"f"))switch(l(this,wf,"f").type){case"text":this._emit("textDone",l(this,wf,"f").text,l(this,T$,"f"));break;case"image_file":this._emit("imageFileDone",l(this,wf,"f").image_file,l(this,T$,"f"));break}CS(this,YM,M.index,"f")}CS(this,wf,$.content[M.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(l(this,YM,"f")!==void 0){const M=S.data.content[l(this,YM,"f")];if(M)switch(M.type){case"image_file":this._emit("imageFileDone",M.image_file,l(this,T$,"f"));break;case"text":this._emit("textDone",M.text,l(this,T$,"f"));break}}if(l(this,T$,"f"))this._emit("messageDone",S.data);CS(this,T$,void 0,"f")}},mw=function T(S){const $=l(this,$S,"m",vw).call(this,S);switch(CS(this,LJ,$,"f"),S.event){case"thread.run.step.created":this._emit("runStepCreated",S.data);break;case"thread.run.step.delta":const f=S.data.delta;if(f.step_details&&f.step_details.type=="tool_calls"&&f.step_details.tool_calls&&$.step_details.type=="tool_calls")for(let J of f.step_details.tool_calls)if(J.index==l(this,iF,"f"))this._emit("toolCallDelta",J,$.step_details.tool_calls[J.index]);else{if(l(this,xS,"f"))this._emit("toolCallDone",l(this,xS,"f"));if(CS(this,iF,J.index,"f"),CS(this,xS,$.step_details.tool_calls[J.index],"f"),l(this,xS,"f"))this._emit("toolCallCreated",l(this,xS,"f"))}this._emit("runStepDelta",S.data.delta,$);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(CS(this,LJ,void 0,"f"),S.data.step_details.type=="tool_calls"){if(l(this,xS,"f"))this._emit("toolCallDone",l(this,xS,"f")),CS(this,xS,void 0,"f")}this._emit("runStepDone",S.data,$);break;case"thread.run.step.in_progress":break}},hw=function T(S){l(this,a0,"f").push(S),this._emit("event",S)},vw=function T(S){switch(S.event){case"thread.run.step.created":return l(this,K$,"f")[S.data.id]=S.data,S.data;case"thread.run.step.delta":let $=l(this,K$,"f")[S.data.id];if(!$)throw Error("Received a RunStepDelta before creation of a snapshot");let f=S.data;if(f.delta){const M=jS.accumulateDelta($,f.delta);l(this,K$,"f")[S.data.id]=M}return l(this,K$,"f")[S.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":l(this,K$,"f")[S.data.id]=S.data;break}if(l(this,K$,"f")[S.data.id])return l(this,K$,"f")[S.data.id];throw new Error("No snapshot available")},Pw=function T(S,$){let f=[];switch(S.event){case"thread.message.created":return[S.data,f];case"thread.message.delta":if(!$)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let M=S.data;if(M.delta.content)for(let J of M.delta.content)if(J.index in $.content){let F=$.content[J.index];$.content[J.index]=l(this,$S,"m",nw).call(this,J,F)}else $.content[J.index]=J,f.push(J);return[$,f];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if($)return[$,f];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},nw=function T(S,$){return jS.accumulateDelta($,S)},cw=function T(S){switch(CS(this,tF,S.data,"f"),S.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":if(CS(this,Kf,S.data,"f"),l(this,xS,"f"))this._emit("toolCallDone",l(this,xS,"f")),CS(this,xS,void 0,"f");break;case"thread.run.cancelling":break}};class OM extends p{create(T,S,$){return this._client.post(`/threads/${T}/messages`,{body:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}retrieve(T,S,$){return this._client.get(`/threads/${T}/messages/${S}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}update(T,S,$,f){return this._client.post(`/threads/${T}/messages/${S}`,{body:$,...f,headers:{"OpenAI-Beta":"assistants=v2",...f?.headers}})}list(T,S={},$){if(LT(S))return this.list(T,{},S);return this._client.getAPIList(`/threads/${T}/messages`,RM,{query:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}del(T,S,$){return this._client.delete(`/threads/${T}/messages/${S}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}}class RM extends vT{}(function(T){T.MessagesPage=RM})(OM||(OM={}));class GM extends p{retrieve(T,S,$,f={},M){if(LT(f))return this.retrieve(T,S,$,{},f);return this._client.get(`/threads/${T}/runs/${S}/steps/${$}`,{query:f,...M,headers:{"OpenAI-Beta":"assistants=v2",...M?.headers}})}list(T,S,$={},f){if(LT($))return this.list(T,S,{},$);return this._client.getAPIList(`/threads/${T}/runs/${S}/steps`,zM,{query:$,...f,headers:{"OpenAI-Beta":"assistants=v2",...f?.headers}})}}class zM extends vT{}(function(T){T.RunStepsPage=zM})(GM||(GM={}));class HM extends p{constructor(){super(...arguments);this.steps=new GM(this._client)}create(T,S,$){const{include:f,...M}=S;return this._client.post(`/threads/${T}/runs`,{query:{include:f},body:M,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers},stream:S.stream??!1})}retrieve(T,S,$){return this._client.get(`/threads/${T}/runs/${S}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}update(T,S,$,f){return this._client.post(`/threads/${T}/runs/${S}`,{body:$,...f,headers:{"OpenAI-Beta":"assistants=v2",...f?.headers}})}list(T,S={},$){if(LT(S))return this.list(T,{},S);return this._client.getAPIList(`/threads/${T}/runs`,_M,{query:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}cancel(T,S,$){return this._client.post(`/threads/${T}/runs/${S}/cancel`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}async createAndPoll(T,S,$){const f=await this.create(T,S,$);return await this.poll(T,f.id,$)}createAndStream(T,S,$){return jS.createAssistantStream(T,this._client.beta.threads.runs,S,$)}async poll(T,S,$){const f={...$?.headers,"X-Stainless-Poll-Helper":"true"};if($?.pollIntervalMs)f["X-Stainless-Custom-Poll-Interval"]=$.pollIntervalMs.toString();while(!0){const{data:M,response:J}=await this.retrieve(T,S,{...$,headers:{...$?.headers,...f}}).withResponse();switch(M.status){case"queued":case"in_progress":case"cancelling":let F=5000;if($?.pollIntervalMs)F=$.pollIntervalMs;else{const W=J.headers.get("openai-poll-after-ms");if(W){const k=parseInt(W);if(!isNaN(k))F=k}}await E$(F);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return M}}}stream(T,S,$){return jS.createAssistantStream(T,this._client.beta.threads.runs,S,$)}submitToolOutputs(T,S,$,f){return this._client.post(`/threads/${T}/runs/${S}/submit_tool_outputs`,{body:$,...f,headers:{"OpenAI-Beta":"assistants=v2",...f?.headers},stream:$.stream??!1})}async submitToolOutputsAndPoll(T,S,$,f){const M=await this.submitToolOutputs(T,S,$,f);return await this.poll(T,M.id,f)}submitToolOutputsStream(T,S,$,f){return jS.createToolAssistantStream(T,S,this._client.beta.threads.runs,$,f)}}class _M extends vT{}(function(T){T.RunsPage=_M,T.Steps=GM,T.RunStepsPage=zM})(HM||(HM={}));class EM extends p{constructor(){super(...arguments);this.runs=new HM(this._client),this.messages=new OM(this._client)}create(T={},S){if(LT(T))return this.create({},T);return this._client.post("/threads",{body:T,...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}retrieve(T,S){return this._client.get(`/threads/${T}`,{...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}update(T,S,$){return this._client.post(`/threads/${T}`,{body:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}del(T,S){return this._client.delete(`/threads/${T}`,{...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}createAndRun(T,S){return this._client.post("/threads/runs",{body:T,...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers},stream:T.stream??!1})}async createAndRunPoll(T,S){const $=await this.createAndRun(T,S);return await this.runs.poll($.thread_id,$.id,S)}createAndRunStream(T,S){return jS.createThreadAssistantStream(T,this._client.beta.threads,S)}}(function(T){T.Runs=HM,T.RunsPage=_M,T.Messages=OM,T.MessagesPage=RM})(EM||(EM={}));var iw=async(T)=>{const S=await Promise.allSettled(T),$=S.filter((M)=>M.status==="rejected");if($.length){for(let M of $)console.error(M.reason);throw new Error(`${$.length} promise(s) failed - see the above errors`)}const f=[];for(let M of S)if(M.status==="fulfilled")f.push(M.value);return f};class DM extends p{create(T,S,$){return this._client.post(`/vector_stores/${T}/files`,{body:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}retrieve(T,S,$){return this._client.get(`/vector_stores/${T}/files/${S}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}list(T,S={},$){if(LT(S))return this.list(T,{},S);return this._client.getAPIList(`/vector_stores/${T}/files`,P$,{query:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}del(T,S,$){return this._client.delete(`/vector_stores/${T}/files/${S}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}async createAndPoll(T,S,$){const f=await this.create(T,S,$);return await this.poll(T,f.id,$)}async poll(T,S,$){const f={...$?.headers,"X-Stainless-Poll-Helper":"true"};if($?.pollIntervalMs)f["X-Stainless-Custom-Poll-Interval"]=$.pollIntervalMs.toString();while(!0){const M=await this.retrieve(T,S,{...$,headers:f}).withResponse(),J=M.data;switch(J.status){case"in_progress":let F=5000;if($?.pollIntervalMs)F=$.pollIntervalMs;else{const W=M.response.headers.get("openai-poll-after-ms");if(W){const k=parseInt(W);if(!isNaN(k))F=k}}await E$(F);break;case"failed":case"completed":return J}}}async upload(T,S,$){const f=await this._client.files.create({file:S,purpose:"assistants"},$);return this.create(T,{file_id:f.id},$)}async uploadAndPoll(T,S,$){const f=await this.upload(T,S,$);return await this.poll(T,f.id,$)}}class P$ extends vT{}(function(T){T.VectorStoreFilesPage=P$})(DM||(DM={}));class yM extends p{create(T,S,$){return this._client.post(`/vector_stores/${T}/file_batches`,{body:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}retrieve(T,S,$){return this._client.get(`/vector_stores/${T}/file_batches/${S}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}cancel(T,S,$){return this._client.post(`/vector_stores/${T}/file_batches/${S}/cancel`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}async createAndPoll(T,S,$){const f=await this.create(T,S);return await this.poll(T,f.id,$)}listFiles(T,S,$={},f){if(LT($))return this.listFiles(T,S,{},$);return this._client.getAPIList(`/vector_stores/${T}/file_batches/${S}/files`,P$,{query:$,...f,headers:{"OpenAI-Beta":"assistants=v2",...f?.headers}})}async poll(T,S,$){const f={...$?.headers,"X-Stainless-Poll-Helper":"true"};if($?.pollIntervalMs)f["X-Stainless-Custom-Poll-Interval"]=$.pollIntervalMs.toString();while(!0){const{data:M,response:J}=await this.retrieve(T,S,{...$,headers:f}).withResponse();switch(M.status){case"in_progress":let F=5000;if($?.pollIntervalMs)F=$.pollIntervalMs;else{const W=J.headers.get("openai-poll-after-ms");if(W){const k=parseInt(W);if(!isNaN(k))F=k}}await E$(F);break;case"failed":case"cancelled":case"completed":return M}}}async uploadAndPoll(T,{files:S,fileIds:$=[]},f){if(S==null||S.length==0)throw new Error("No \`files\` provided to process. If you've already uploaded files you should use \`.createAndPoll()\` instead");const M=f?.maxConcurrency??5,J=Math.min(M,S.length),F=this._client,W=S.values(),k=[...$];async function X(K){for(let O of K){const H=await F.files.create({file:O,purpose:"assistants"},f);k.push(H.id)}}const w=Array(J).fill(W).map(X);return await iw(w),await this.createAndPoll(T,{file_ids:k})}}(function(T){})(yM||(yM={}));class QM extends p{constructor(){super(...arguments);this.files=new DM(this._client),this.fileBatches=new yM(this._client)}create(T,S){return this._client.post("/vector_stores",{body:T,...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}retrieve(T,S){return this._client.get(`/vector_stores/${T}`,{...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}update(T,S,$){return this._client.post(`/vector_stores/${T}`,{body:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}list(T={},S){if(LT(T))return this.list({},T);return this._client.getAPIList("/vector_stores",UM,{query:T,...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}del(T,S){return this._client.delete(`/vector_stores/${T}`,{...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}}class UM extends vT{}(function(T){T.VectorStoresPage=UM,T.Files=DM,T.VectorStoreFilesPage=P$,T.FileBatches=yM})(QM||(QM={}));class Af extends p{constructor(){super(...arguments);this.vectorStores=new QM(this._client),this.chat=new AM(this._client),this.assistants=new FM(this._client),this.threads=new EM(this._client)}}(function(T){T.VectorStores=QM,T.VectorStoresPage=UM,T.Chat=AM,T.Assistants=FM,T.AssistantsPage=WM,T.Threads=EM})(Af||(Af={}));class Yf extends p{create(T,S){return this._client.post("/completions",{body:T,...S,stream:T.stream??!1})}}(function(T){})(Yf||(Yf={}));class Of extends p{create(T,S){return this._client.post("/embeddings",{body:T,...S})}}(function(T){})(Of||(Of={}));class Rf extends p{create(T,S){return this._client.post("/files",vS({body:T,...S}))}retrieve(T,S){return this._client.get(`/files/${T}`,S)}list(T={},S){if(LT(T))return this.list({},T);return this._client.getAPIList("/files",Gf,{query:T,...S})}del(T,S){return this._client.delete(`/files/${T}`,S)}content(T,S){return this._client.get(`/files/${T}/content`,{...S,__binaryResponse:!0})}retrieveContent(T,S){return this._client.get(`/files/${T}/content`,{...S,headers:{Accept:"application/json",...S?.headers}})}async waitForProcessing(T,{pollInterval:S=5000,maxWait:$=1800000}={}){const f=new Set(["processed","error","deleted"]),M=Date.now();let J=await this.retrieve(T);while(!J.status||!f.has(J.status))if(await E$(S),J=await this.retrieve(T),Date.now()-M>$)throw new Sf({message:`Giving up on waiting for file ${T} to finish processing after ${$} milliseconds.`});return J}}class Gf extends $f{}(function(T){T.FileObjectsPage=Gf})(Rf||(Rf={}));class VM extends p{list(T,S={},$){if(LT(S))return this.list(T,{},S);return this._client.getAPIList(`/fine_tuning/jobs/${T}/checkpoints`,LM,{query:S,...$})}}class LM extends vT{}(function(T){T.FineTuningJobCheckpointsPage=LM})(VM||(VM={}));class BM extends p{constructor(){super(...arguments);this.checkpoints=new VM(this._client)}create(T,S){return this._client.post("/fine_tuning/jobs",{body:T,...S})}retrieve(T,S){return this._client.get(`/fine_tuning/jobs/${T}`,S)}list(T={},S){if(LT(T))return this.list({},T);return this._client.getAPIList("/fine_tuning/jobs",NM,{query:T,...S})}cancel(T,S){return this._client.post(`/fine_tuning/jobs/${T}/cancel`,S)}listEvents(T,S={},$){if(LT(S))return this.listEvents(T,{},S);return this._client.getAPIList(`/fine_tuning/jobs/${T}/events`,CM,{query:S,...$})}}class NM extends vT{}class CM extends vT{}(function(T){T.FineTuningJobsPage=NM,T.FineTuningJobEventsPage=CM,T.Checkpoints=VM,T.FineTuningJobCheckpointsPage=LM})(BM||(BM={}));class zf extends p{constructor(){super(...arguments);this.jobs=new BM(this._client)}}(function(T){T.Jobs=BM,T.FineTuningJobsPage=NM,T.FineTuningJobEventsPage=CM})(zf||(zf={}));class Hf extends p{createVariation(T,S){return this._client.post("/images/variations",vS({body:T,...S}))}edit(T,S){return this._client.post("/images/edits",vS({body:T,...S}))}generate(T,S){return this._client.post("/images/generations",{body:T,...S})}}(function(T){})(Hf||(Hf={}));class _f extends p{retrieve(T,S){return this._client.get(`/models/${T}`,S)}list(T){return this._client.getAPIList("/models",Ef,T)}del(T,S){return this._client.delete(`/models/${T}`,S)}}class Ef extends $f{}(function(T){T.ModelsPage=Ef})(_f||(_f={}));class Df extends p{create(T,S){return this._client.post("/moderations",{body:T,...S})}}(function(T){})(Df||(Df={}));class xM extends p{create(T,S,$){return this._client.post(`/uploads/${T}/parts`,vS({body:S,...$}))}}(function(T){})(xM||(xM={}));class yf extends p{constructor(){super(...arguments);this.parts=new xM(this._client)}create(T,S){return this._client.post("/uploads",{body:T,...S})}cancel(T,S){return this._client.post(`/uploads/${T}/cancel`,S)}complete(T,S,$){return this._client.post(`/uploads/${T}/complete`,{body:S,...$})}}(function(T){T.Parts=xM})(yf||(yf={}));var rw;class PT extends C0{constructor({baseURL:T=YJ("OPENAI_BASE_URL"),apiKey:S=YJ("OPENAI_API_KEY"),organization:$=YJ("OPENAI_ORG_ID")??null,project:f=YJ("OPENAI_PROJECT_ID")??null,...M}={}){if(S===void 0)throw new $T("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const J={apiKey:S,organization:$,project:f,...M,baseURL:T||"https://api.openai.com/v1"};if(!J.dangerouslyAllowBrowser&&Gw())throw new $T("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");super({baseURL:J.baseURL,timeout:J.timeout??600000,httpAgent:J.httpAgent,maxRetries:J.maxRetries,fetch:J.fetch});this.completions=new Yf(this),this.chat=new ff(this),this.embeddings=new Of(this),this.files=new Rf(this),this.images=new Hf(this),this.audio=new Mf(this),this.moderations=new Df(this),this.models=new _f(this),this.fineTuning=new zf(this),this.beta=new Af(this),this.batches=new Jf(this),this.uploads=new yf(this),this._options=J,this.apiKey=S,this.organization=$,this.project=f}defaultQuery(){return this._options.defaultQuery}defaultHeaders(T){return{...super.defaultHeaders(T),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(T){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(T){return b0(T,{arrayFormat:"brackets"})}}rw=PT;PT.OpenAI=rw;PT.DEFAULT_TIMEOUT=600000;PT.OpenAIError=$T;PT.APIError=oT;PT.APIConnectionError=Tf;PT.APIConnectionTimeoutError=Sf;PT.APIUserAbortError=SS;PT.NotFoundError=VF;PT.ConflictError=LF;PT.RateLimitError=NF;PT.BadRequestError=yF;PT.AuthenticationError=QF;PT.InternalServerError=CF;PT.PermissionDeniedError=UF;PT.UnprocessableEntityError=BF;PT.toFile=L0;PT.fileFromPath=zF;(function(T){T.Page=$f,T.CursorPage=vT,T.Completions=Yf,T.Chat=ff,T.Embeddings=Of,T.Files=Rf,T.FileObjectsPage=Gf,T.Images=Hf,T.Audio=Mf,T.Moderations=Df,T.Models=_f,T.ModelsPage=Ef,T.FineTuning=zf,T.Beta=Af,T.Batches=Jf,T.BatchesPage=Ff,T.Uploads=yf})(PT||(PT={}));var aw=PT;import{createHash as o6}from"crypto";import*as aT from"fs";import*as Q$ from"path";function t6(T){const S=T.replace(i6,"-");if(S.length<=64)return S;const $=o6("sha256").update(T).digest("hex");return S.slice(-64)+"+"+$}var i6=/[^a-zA-Z0-9\-._]/g;class e0{mode;baseDir;filenameCache=new Map;filesTouched=new Map;constructor(T="off",S=Q$.join(process.cwd(),".varmint")){this.mode=T,this.baseDir=S}read(T,S,$){const f=Q$.join(this.baseDir,`${T}/${S}.input.json`);if(!aT.existsSync(f))throw new Error(`Squirrel: input file for key "${T}" does not exist`);const M=aT.readFileSync(f,"utf-8"),J=JSON.stringify($,null,"\t");if(J!==M)throw new Error(`Squirrel: the content of the cached input file ${f} does not match the input provided.\n\nProvided:\n${J}\n\nCached:\n${M}`);const F=Q$.join(this.baseDir,`${T}/${S}.output.json`);return JSON.parse(aT.readFileSync(F,"utf-8"))}async write(T,S,$,f){const M=Q$.join(this.baseDir,T),J=Q$.join(M,`${S}.input.json`),F=Q$.join(M,`${S}.output.json`),W=JSON.stringify($,null,"\t");if(!aT.existsSync(this.baseDir))aT.mkdirSync(this.baseDir);if(!aT.existsSync(M))aT.mkdirSync(M);if(aT.writeFileSync(J,W),aT.existsSync(F))aT.unlinkSync(F);const k=await f(...$);return aT.writeFileSync(F,JSON.stringify(k,null,"\t")),k}add(T,S){return{flush:()=>{this.flush(T)},for:($)=>{if(this.mode!=="off"&&!this.filesTouched.has(T))this.filesTouched.set(T,new Set);return{get:async(...f)=>{let M=$;if(this.mode!=="off"){let J=this.filenameCache.get($);if(!J)J=t6($),this.filenameCache.set($,M),M=J;this.filesTouched.get(T)?.add(M)}switch(this.mode){case"off":return S(...f);case"read":return this.read(T,M,f);case"write":return this.write(T,M,f,S);case"read-write":try{return this.read(T,M,f)}catch(J){if(J instanceof Error)return this.write(T,M,f,S);throw J}}}}}}}flush(...T){for(let[S,$]of this.filesTouched.entries())if(T.length===0||T.includes(S)){const f=Q$.join(this.baseDir,S),M=aT.readdirSync(f);for(let J of M){const F=J.replace(".input.json","").replace(".output.json","");if(!$.has(F))console.log(`\uD83D\uDCA5 Flushing ${F}`),aT.unlinkSync(Q$.join(f,J))}}}}function u6(T,...S){const[$,f,M,J]=S,F=[{role:"user",content:$},{role:"user",content:aX(f)}],W=J.at(-1);if(W)F.push({role:"user",content:["Oops! That didn't work. Here's what was returned last time:",JSON.stringify(W.response,null,2),"Here's the error message:",W.error.toString()].join(`
12
+ `)});return{model:T,messages:F}}function l6(T="NO_API_KEY_PROVIDED"){const S=p6("sha256").update(T).digest("hex");return async function $(f,M){let J=ew.get(S);if(!J)J=new aw({apiKey:T,dangerouslyAllowBrowser:!1}),ew.set(S,J);const F=await J.chat.completions.create({...f,stream:!1,response_format:{type:"json_object"}},M),W=F.choices[0].message?.content,{usage:k}=F;if(W&&k){const X=k.prompt_tokens,w=k.prompt_tokens_details?.cached_tokens??0,K=X-w,O=k.completion_tokens,H=X*s0[f.model].promptPricePerToken+K*s0[f.model].promptPricePerTokenCached+O*s0[f.model].completionPricePerToken;return{data:JSON.parse(W),usdPrice:H}}if(!W&&!k)throw new Error("No content or usage found in completion");if(!W)throw new Error("No content found in completion");throw new Error("No usage found in completion")}}var s0={"gpt-4o":{promptPricePerToken:0.0000025,promptPricePerTokenCached:0.00000125,completionPricePerToken:0.00001},"gpt-4o-mini":{promptPricePerToken:0.00000015,promptPricePerTokenCached:0.000000075,completionPricePerToken:0.0000006}},ew=new Map;var sw=class{usdFloor;usdBudget;getUnknownJsonFromOpenAi;getUnknownJsonFromOpenAiSquirreled;squirrel;constructor({model:T,usdBudget:S,usdMinimum:$,apiKey:f,logger:M}){this.usdBudget=S,this.usdFloor=$,this.squirrel=new e0("read"),this.getUnknownJsonFromOpenAi=l6(f),this.getUnknownJsonFromOpenAiSquirreled=this.squirrel.add("openai-safegen",this.getUnknownJsonFromOpenAi),this.from=rX(async(...J)=>{if(this.usdBudget<this.usdFloor)return M?.warn("SafeGen budget exhausted"),J[1];const F=u6(T,...J),W=J[0],k=J[3],X=await this.getUnknownJsonFromOpenAiSquirreled.for(`${W.replace(/[^a-zA-Z0-9-_. ]/g,"_")}-${k.length}`).get(F);return this.usdBudget-=X.usdPrice,X.data})}from};import{exec as $7}from"child_process";import{existsSync as f7}from"fs";import{readFile as M7,writeFile as J7}from"fs/promises";import{resolve as F7}from"path";var T1=(T)=>{const S=ES(T,{key:"\uD83D\uDD0D Atom Token Index (Internal)",default:()=>{const $=new Map;for(let[f,M]of T.atoms)if(!f.includes("\uD83D\uDD0D")){const J=XS(M);if(M.family){let F=$.get(M.family.key);if(!F||!("familyMembers"in F))F={key:M.family.key,familyMembers:new Map},$.set(M.family.key,F);F.familyMembers.set(M.family.subKey,J)}else $.set(f,J)}return $},effects:[({setSelf:$})=>{T.on.atomCreation.subscribe("introspection",(f)=>{if(f.key.includes("\uD83D\uDD0D"))return;$((M)=>{if(f.family){const{key:J,subKey:F}=f.family;let W=M.get(J);if(W===void 0||!("familyMembers"in W))W={key:J,familyMembers:new Map},M.set(J,W);W.familyMembers.set(F,f)}else M.set(f.key,f);return M})}),T.on.atomDisposal.subscribe("introspection",(f)=>{$((M)=>{if(f.family){const{key:J,subKey:F}=f.family,W=M.get(J);if(W&&"familyMembers"in W){if(W.familyMembers.delete(F),W.familyMembers.size===0)M.delete(J)}}else M.delete(f.key);return M})})}]},void 0);return tS(T,{key:"\uD83D\uDD0D Atom Token Index",get:({get:$})=>$(S)})};var S1=(T)=>{const S=ES(T,{key:"\uD83D\uDD0D Selector Token Index (Internal)",default:()=>{const $=new Map;for(let f of[T.readonlySelectors,T.selectors])for(let[M,J]of f)if(!M.includes("\uD83D\uDD0D")){const F=XS(J);if(J.family){let W=$.get(J.family.key);if(!W||!("familyMembers"in W))W={key:J.family.key,familyMembers:new Map},$.set(J.family.key,W);W.familyMembers.set(J.family.subKey,F)}else $.set(M,F)}return $},effects:[({setSelf:$})=>{T.on.selectorCreation.subscribe("introspection",(f)=>{if(f.key.includes("\uD83D\uDD0D"))return;$((M)=>{if(f.family){const{key:J,subKey:F}=f.family;let W=M.get(J);if(W===void 0||!("familyMembers"in W))W={key:J,familyMembers:new Map},M.set(J,W);W.familyMembers.set(F,f)}else M.set(f.key,f);return M})}),T.on.selectorDisposal.subscribe("introspection",(f)=>{$((M)=>{if(f.family){const{key:J,subKey:F}=f.family,W=M.get(J);if(W&&"familyMembers"in W){if(W.familyMembers.delete(F),W.familyMembers.size===0)M.delete(J)}}else M.delete(f.key);return M})})}]},void 0);return tS(T,{key:"\uD83D\uDD0D Selector Token Index",get:({get:$})=>$(S)})};function f1(T){if(!T)return!1;return Object.getPrototypeOf(T)===Object.prototype}class pF{supported;constructor(T){this.supported=T}refine(T){for(let[S,$]of Object.entries(this.supported))try{if($(T)===!0&&$!==Boolean)return{type:S,data:T}}catch(f){try{if(T instanceof $)return{type:S,data:T}}catch(M){}}return null}}var $1=new pF({number:(T)=>typeof T==="number",string:(T)=>typeof T==="string",boolean:(T)=>typeof T==="boolean",null:(T)=>T===null}),M1=new pF({object:f1,array:(T)=>Array.isArray(T)}),d6=new pF({...$1.supported,...M1.supported}),jM=(T)=>{if(T===void 0)return"undefined";const S=d6.refine(T);if(S)return S.type;return Object.getPrototypeOf(T).constructor.name};class TK{T;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(T=wT.STORE){this.store=T;this.atomIndex=T1(this.store),this.selectorIndex=S1(this.store),this.unsubscribeFromAtomCreation=this.store.on.atomCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:S})=>{this.statesCreatedAt.set(S,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromAtomDisposal=this.store.on.atomDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:S})=>{this.statesCreatedAt.delete(S)}),this.unsubscribeFromSelectorCreation=this.store.on.selectorCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:S})=>{this.statesCreatedAt.set(S,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromSelectorDisposal=this.store.on.selectorDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:S})=>{this.statesCreatedAt.delete(S)})}static DEFAULT_LIST_RESOURCES_PARAM={atomFamilies:!0,selectorFamilies:!0};listResources(T=TK.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");const S=hW(this.atomIndex),$=hW(this.selectorIndex),f=[...S.values()].filter((W)=>("familyMembers"in W)),M=[...$.values()].filter((W)=>("familyMembers"in W)),J=performance.now(),F=[];if(T.atomFamilies)for(let W of f){const k=W.familyMembers.values();for(let X of k){const K=this.statesCreatedAt.get(X.key)??this.auditorCreatedAt,O=J-K;F.push([X,O])}}if(T.selectorFamilies)for(let W of M){const k=W.familyMembers.values();for(let X of k){const K=this.statesCreatedAt.get(X.key)??this.auditorCreatedAt,O=J-K;F.push([X,O])}}return F}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}}var J1=(T,S)=>{const $=(f,M)=>{const F=((k,X)=>{const w=S(k,X);if(w)return w;return null})(f,M);if(F?.jobComplete??F?.pathComplete)return F;const W=Array.isArray(M)?M.map((k,X)=>[X,k]):f1(M)?Object.entries(M):[];for(let[k,X]of W){const w=$([...f,k],X);if(w?.jobComplete)return w}return{}};$([],T)};function r6(T,S){return{summary:`${T<S?"+":"-"}${Math.abs(T-S)} (${T} \u2192 ${S})`}}function a6(T,S){return{summary:`${T.length<S.length?"+":"-"}${Math.abs(T.length-S.length)} ("${T}" \u2192 "${S}")`}}function e6(T,S){return{summary:`${T} \u2192 ${S}`}}function SK(T,S,$){let f="";const M=[],J=[],F=[];return J1(T,(W,k)=>{let X;for(X of W){const w=S[X];if(w===void 0)J.push([X,JSON.stringify(k)]);else{const K=$(k,w);if(K.summary!=="No Change")F.push([X,K])}}}),J1(S,(W,k)=>{let X;for(X of W)if(T[X]===void 0)M.push([X,JSON.stringify(k)])}),f=`\uFF5E${F.length} \uFF0B${M.length} \uFF0D${J.length}`,{summary:f,added:M,removed:J,changed:F}}function s6(T,S,$){return SK(T,S,$)}class $K{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(T,S,$){this.leafRefinery=T,this.treeRefinery=S,this.leafDiffers={},this.treeDiffers={};for(let f of Object.keys(T.supported)){const M=$[f];this.leafDiffers[f]=M}for(let f of Object.keys(S.supported)){const M=$[f];this.treeDiffers[f]=M}}diff(T,S){if(T===S)return{summary:"No Change"};const $=this.leafRefinery.refine(T)??this.treeRefinery.refine(T),f=this.leafRefinery.refine(S)??this.treeRefinery.refine(S);if($!==null&&f!==null){if($.type===f.type){if($.type in this.leafDiffers)return this.leafDiffers[$.type]($.data,f.data);if($.type in this.treeDiffers)return this.treeDiffers[$.type]($.data,f.data,(W,k)=>this.diff(W,k))}}const M=jM(T),J=jM(S);if(M===J)return{summary:`${M} \u2192 ${J}`};return{summary:`Type change: ${M} \u2192 ${J}`}}}var BB=new $K($1,M1,{number:r6,string:a6,boolean:e6,null:()=>({summary:"No Change"}),object:SK,array:s6});function L(T,S){if(!T||typeof T!=="object")return!1;if(T instanceof S)return!0;if(!Object.prototype.hasOwnProperty.call(S,Y))throw new Error(`Class "${S.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 $=Object.getPrototypeOf(T).constructor;if($)while($){if(Y in $&&$[Y]===S[Y])return!0;$=Object.getPrototypeOf($)}return!1}var Y=Symbol.for("drizzle:entityKind"),ZB=Symbol.for("drizzle:hasOwnEntityKind");class BT{constructor(T,S){this.table=T,this.config=S,this.name=S.name,this.keyAsName=S.keyAsName,this.notNull=S.notNull,this.default=S.default,this.defaultFn=S.defaultFn,this.onUpdateFn=S.onUpdateFn,this.hasDefault=S.hasDefault,this.primary=S.primaryKey,this.isUnique=S.isUnique,this.uniqueName=S.uniqueName,this.uniqueType=S.uniqueType,this.dataType=S.dataType,this.columnType=S.columnType,this.generated=S.generated,this.generatedIdentity=S.generatedIdentity}static[Y]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(T){return T}mapToDriverValue(T){return T}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class F1{static[Y]="ColumnBuilder";config;constructor(T,S,$){this.config={name:T,keyAsName:T==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:S,columnType:$,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(T){return this.config.default=T,this.config.hasDefault=!0,this}$defaultFn(T){return this.config.defaultFn=T,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(T){return this.config.onUpdateFn=T,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(T){if(this.config.name!=="")return;this.config.name=T}}var S$=Symbol.for("drizzle:Name");class W1{static[Y]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(T,S){if(this.reference=()=>{const{name:$,columns:f,foreignColumns:M}=T();return{name:$,columns:f,foreignTable:M[0].table,foreignColumns:M}},S)this._onUpdate=S.onUpdate,this._onDelete=S.onDelete}onUpdate(T){return this._onUpdate=T===void 0?"no action":T,this}onDelete(T){return this._onDelete=T===void 0?"no action":T,this}build(T){return new fK(T,this)}}class fK{constructor(T,S){this.table=T,this.reference=S.reference,this.onUpdate=S._onUpdate,this.onDelete=S._onDelete}static[Y]="PgForeignKey";reference;onUpdate;onDelete;getName(){const{name:T,columns:S,foreignColumns:$}=this.reference(),f=S.map((F)=>F.name),M=$.map((F)=>F.name),J=[this.table[S$],...f,$[0].table[S$],...M];return T??`${J.join("_")}_fk`}}function uF(T,...S){return T(...S)}function MK(T,S){return`${T[S$]}_${S.join("_")}_unique`}function JK(T,S,$){for(let f=S;f<T.length;f++){const M=T[f];if(M==="\\"){f++;continue}if(M==='"')return[T.slice(S,f).replace(/\\/g,""),f+1];if($)continue;if(M===","||M==="}")return[T.slice(S,f).replace(/\\/g,""),f]}return[T.slice(S).replace(/\\/g,""),T.length]}function FK(T,S=0){const $=[];let f=S,M=!1;while(f<T.length){const J=T[f];if(J===","){if(M||f===S)$.push("");M=!0,f++;continue}if(M=!1,J==="\\"){f+=2;continue}if(J==='"'){const[k,X]=JK(T,f+1,!0);$.push(k),f=X;continue}if(J==="}")return[$,f+1];if(J==="{"){const[k,X]=FK(T,f+1);$.push(k),f=X;continue}const[F,W]=JK(T,f,!1);$.push(F),f=W}return[$,f]}function WK(T){const[S]=FK(T,1);return S}function k1(T){return`{${T.map((S)=>{if(Array.isArray(S))return k1(S);if(typeof S==="string")return`"${S.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`;return`${S}`}).join(",")}}`}class o extends F1{foreignKeyConfigs=[];static[Y]="PgColumnBuilder";array(T){return new XK(this.config.name,this,T)}references(T,S={}){return this.foreignKeyConfigs.push({ref:T,actions:S}),this}unique(T,S){return this.config.isUnique=!0,this.config.uniqueName=T,this.config.uniqueType=S?.nulls,this}generatedAlwaysAs(T){return this.config.generated={as:T,type:"always",mode:"stored"},this}buildForeignKeys(T,S){return this.foreignKeyConfigs.map(({ref:$,actions:f})=>{return uF((M,J)=>{const F=new W1(()=>{const W=M();return{columns:[T],foreignColumns:[W]}});if(J.onUpdate)F.onUpdate(J.onUpdate);if(J.onDelete)F.onDelete(J.onDelete);return F.build(S)},$,f)})}buildExtraConfigColumn(T){return new kK(T,this.config)}}class h extends BT{constructor(T,S){if(!S.uniqueName)S.uniqueName=MK(T,[S.name]);super(T,S);this.table=T}static[Y]="PgColumn"}class kK extends h{static[Y]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(T){return this.indexConfig.opClass=T,this}}class BJ{static[Y]="IndexedColumn";constructor(T,S,$,f){this.name=T,this.keyAsName=S,this.type=$,this.indexConfig=f}name;keyAsName;type;indexConfig}class XK extends o{static[Y]="PgArrayBuilder";constructor(T,S,$){super(T,"array","PgArray");this.config.baseBuilder=S,this.config.size=$}build(T){const S=this.config.baseBuilder.build(T);return new X1(T,this.config,S)}}class X1 extends h{constructor(T,S,$,f){super(T,S);this.baseColumn=$,this.range=f,this.size=S.size}size;static[Y]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(T){if(typeof T==="string")T=WK(T);return T.map((S)=>this.baseColumn.mapFromDriverValue(S))}mapToDriverValue(T,S=!1){const $=T.map((f)=>f===null?null:L(this.baseColumn,X1)?this.baseColumn.mapToDriverValue(f,!0):this.baseColumn.mapToDriverValue(f));if(S)return $;return k1($)}}function wK(T){return!!T&&typeof T==="function"&&w1 in T&&T[w1]===!0}function lF(T,S){return TO(T,S,void 0)}function TO(T,S,$){const f=Object.assign((M)=>new KK(M??"",f),{enumName:T,enumValues:S,schema:$,[w1]:!0});return f}var w1=Symbol.for("drizzle:isPgEnum");class KK extends o{static[Y]="PgEnumColumnBuilder";constructor(T,S){super(T,"string","PgEnumColumn");this.config.enum=S}build(T){return new AK(T,this.config)}}class AK extends h{static[Y]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(T,S){super(T,S);this.enum=S.enum}getSQLType(){return this.enum.enumName}}class fS{static[Y]="Subquery";constructor(T,S,$,f=!1){this._={brand:"Subquery",sql:T,selectedFields:S,alias:$,isWith:f}}}class NJ extends fS{static[Y]="WithSubquery"}var YK="0.35.1";var K1,A1,DT={startActiveSpan(T,S){if(!K1)return S();if(!A1)A1=K1.trace.getTracer("drizzle-orm",YK);return uF(($,f)=>f.startActiveSpan(T,(M)=>{try{return S(M)}catch(J){throw M.setStatus({code:$.SpanStatusCode.ERROR,message:J instanceof Error?J.message:"Unknown error"}),J}finally{M.end()}}),K1,A1)}};var ZT=Symbol.for("drizzle:ViewBaseConfig");function PS(T){return T[S$]}function Qf(T){return`${T[dF]??"public"}.${T[S$]}`}var dF=Symbol.for("drizzle:Schema"),OK=Symbol.for("drizzle:Columns"),RK=Symbol.for("drizzle:ExtraConfigColumns"),Y1=Symbol.for("drizzle:OriginalName"),O1=Symbol.for("drizzle:BaseName"),GK=Symbol.for("drizzle:IsAlias"),zK=Symbol.for("drizzle:ExtraConfigBuilder"),SO=Symbol.for("drizzle:IsDrizzleTable");class g{static[Y]="Table";static Symbol={Name:S$,Schema:dF,OriginalName:Y1,Columns:OK,ExtraConfigColumns:RK,BaseName:O1,IsAlias:GK,ExtraConfigBuilder:zK};[S$];[Y1];[dF];[OK];[RK];[O1];[GK]=!1;[SO]=!0;[zK]=void 0;constructor(T,S,$){this[S$]=this[Y1]=T,this[dF]=S,this[O1]=$}}function R1(T){return T!==null&&T!==void 0&&typeof T.getSQL==="function"}function $O(T){const S={sql:"",params:[]};for(let $ of T)if(S.sql+=$.sql,S.params.push(...$.params),$.typings?.length){if(!S.typings)S.typings=[];S.typings.push(...$.typings)}return S}function HK(T){return typeof T==="object"&&T!==null&&"mapToDriverValue"in T&&typeof T.mapToDriverValue==="function"}function R(T,...S){const $=[];if(S.length>0||T.length>0&&T[0]!=="")$.push(new eT(T[0]));for(let[f,M]of S.entries())$.push(M,new eT(T[f+1]));return new t($)}function G1(T,S){return T.map(($)=>{if(L($,n$)){if(!($.name in S))throw new Error(`No value for placeholder "${$.name}" was provided`);return S[$.name]}if(L($,IS)&&L($.value,n$)){if(!($.value.name in S))throw new Error(`No value for placeholder "${$.value.name}" was provided`);return $.encoder.mapToDriverValue(S[$.value.name])}return $})}class eT{static[Y]="StringChunk";value;constructor(T){this.value=Array.isArray(T)?T:[T]}getSQL(){return new t([this])}}class t{constructor(T){this.queryChunks=T}static[Y]="SQL";decoder=_K;shouldInlineParams=!1;append(T){return this.queryChunks.push(...T.queryChunks),this}toQuery(T){return DT.startActiveSpan("drizzle.buildSQL",(S)=>{const $=this.buildQueryFromSourceParams(this.queryChunks,T);return S?.setAttributes({"drizzle.query.text":$.sql,"drizzle.query.params":JSON.stringify($.params)}),$})}buildQueryFromSourceParams(T,S){const $=Object.assign({},S,{inlineParams:S.inlineParams||this.shouldInlineParams,paramStartIndex:S.paramStartIndex||{value:0}}),{casing:f,escapeName:M,escapeParam:J,prepareTyping:F,inlineParams:W,paramStartIndex:k}=$;return $O(T.map((X)=>{if(L(X,eT))return{sql:X.value.join(""),params:[]};if(L(X,rF))return{sql:M(X.value),params:[]};if(X===void 0)return{sql:"",params:[]};if(Array.isArray(X)){const w=[new eT("(")];for(let[K,O]of X.entries())if(w.push(O),K<X.length-1)w.push(new eT(", "));return w.push(new eT(")")),this.buildQueryFromSourceParams(w,$)}if(L(X,t))return this.buildQueryFromSourceParams(X.queryChunks,{...$,inlineParams:W||X.shouldInlineParams});if(L(X,g)){const w=X[g.Symbol.Schema],K=X[g.Symbol.Name];return{sql:w===void 0?M(K):M(w)+"."+M(K),params:[]}}if(L(X,BT)){const w=f.getColumnCasing(X);if(S.invokeSource==="indexes")return{sql:M(w),params:[]};return{sql:M(X.table[g.Symbol.Name])+"."+M(w),params:[]}}if(L(X,yS)){const w=X[ZT].schema,K=X[ZT].name;return{sql:w===void 0?M(K):M(w)+"."+M(K),params:[]}}if(L(X,IS)){if(L(X.value,n$))return{sql:J(k.value++,X),params:[X],typings:["none"]};const w=X.value===null?null:X.encoder.mapToDriverValue(X.value);if(L(w,t))return this.buildQueryFromSourceParams([w],$);if(W)return{sql:this.mapInlineParam(w,$),params:[]};let K=["none"];if(F)K=[F(X.encoder)];return{sql:J(k.value++,w),params:[w],typings:K}}if(L(X,n$))return{sql:J(k.value++,X),params:[X],typings:["none"]};if(L(X,t.Aliased)&&X.fieldAlias!==void 0)return{sql:M(X.fieldAlias),params:[]};if(L(X,fS)){if(X._.isWith)return{sql:M(X._.alias),params:[]};return this.buildQueryFromSourceParams([new eT("("),X._.sql,new eT(") "),new rF(X._.alias)],$)}if(wK(X)){if(X.schema)return{sql:M(X.schema)+"."+M(X.enumName),params:[]};return{sql:M(X.enumName),params:[]}}if(R1(X)){if(X.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([X.getSQL()],$);return this.buildQueryFromSourceParams([new eT("("),X.getSQL(),new eT(")")],$)}if(W)return{sql:this.mapInlineParam(X,$),params:[]};return{sql:J(k.value++,X),params:[X],typings:["none"]}}))}mapInlineParam(T,{escapeString:S}){if(T===null)return"null";if(typeof T==="number"||typeof T==="boolean")return T.toString();if(typeof T==="string")return S(T);if(typeof T==="object"){const $=T.toString();if($==="[object Object]")return S(JSON.stringify(T));return S($)}throw new Error("Unexpected param value: "+T)}getSQL(){return this}as(T){if(T===void 0)return this;return new t.Aliased(this,T)}mapWith(T){return this.decoder=typeof T==="function"?{mapFromDriverValue:T}:T,this}inlineParams(){return this.shouldInlineParams=!0,this}if(T){return T?this:void 0}}class rF{constructor(T){this.value=T}static[Y]="Name";brand;getSQL(){return new t([this])}}var _K={mapFromDriverValue:(T)=>T},EK={mapToDriverValue:(T)=>T},QN={..._K,...EK};class IS{constructor(T,S=EK){this.value=T,this.encoder=S}static[Y]="Param";brand;getSQL(){return new t([this])}}((T)=>{function S(){return new t([])}T.empty=S;function $(k){return new t(k)}T.fromList=$;function f(k){return new t([new eT(k)])}T.raw=f;function M(k,X){const w=[];for(let[K,O]of k.entries()){if(K>0&&X!==void 0)w.push(X);w.push(O)}return new t(w)}T.join=M;function J(k){return new rF(k)}T.identifier=J;function F(k){return new n$(k)}T.placeholder=F;function W(k,X){return new IS(k,X)}T.param=W})(R||(R={}));((T)=>{class S{constructor($,f){this.sql=$,this.fieldAlias=f}static[Y]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new S(this.sql,this.fieldAlias)}}T.Aliased=S})(t||(t={}));class n${constructor(T){this.name=T}static[Y]="Placeholder";getSQL(){return new t([this])}}class yS{static[Y]="View";[ZT];constructor({name:T,schema:S,selectedFields:$,query:f}){this[ZT]={name:T,originalName:T,schema:S,selectedFields:$,query:f,isExisting:!f,isAlias:!1}}getSQL(){return new t([this])}}BT.prototype.getSQL=function(){return new t([this])};g.prototype.getSQL=function(){return new t([this])};fS.prototype.getSQL=function(){return new t([this])};function aF(T,S){return new Proxy(T,new CJ(S,!1))}function A$(T,S){return new Proxy(T,new IM(new Proxy(T.table,new CJ(S,!1))))}function z1(T,S){return new t.Aliased(xJ(T.sql,S),T.fieldAlias)}function xJ(T,S){return R.join(T.queryChunks.map(($)=>{if(L($,BT))return A$($,S);if(L($,t))return xJ($,S);if(L($,t.Aliased))return z1($,S);return $}))}class IM{constructor(T){this.table=T}static[Y]="ColumnAliasProxyHandler";get(T,S){if(S==="table")return this.table;return T[S]}}class CJ{constructor(T,S){this.alias=T,this.replaceOriginalName=S}static[Y]="TableAliasProxyHandler";get(T,S){if(S===g.Symbol.IsAlias)return!0;if(S===g.Symbol.Name)return this.alias;if(this.replaceOriginalName&&S===g.Symbol.OriginalName)return this.alias;if(S===ZT)return{...T[ZT],name:this.alias,isAlias:!0};if(S===g.Symbol.Columns){const f=T[g.Symbol.Columns];if(!f)return f;const M={};return Object.keys(f).map((J)=>{M[J]=new Proxy(f[J],new IM(new Proxy(T,this)))}),M}const $=T[S];if(L($,BT))return new Proxy($,new IM(new Proxy(T,this)));return $}}class eF extends Error{static[Y]="DrizzleError";constructor({message:T,cause:S}){super(T);this.name="DrizzleError",this.cause=S}}class H1 extends eF{static[Y]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}function QS(T,S){if(HK(S)&&!R1(T)&&!L(T,IS)&&!L(T,n$)&&!L(T,BT)&&!L(T,g)&&!L(T,yS))return new IS(T,S);return T}function jJ(...T){const S=T.filter(($)=>$!==void 0);if(S.length===0)return;if(S.length===1)return new t(S);return new t([new eT("("),R.join(S,new eT(" and ")),new eT(")")])}function yK(...T){const S=T.filter(($)=>$!==void 0);if(S.length===0)return;if(S.length===1)return new t(S);return new t([new eT("("),R.join(S,new eT(" or ")),new eT(")")])}function QK(T){return R`not ${T}`}function BK(T,S){if(Array.isArray(S)){if(S.length===0)return R`false`;return R`${T} in ${S.map(($)=>QS($,T))}`}return R`${T} in ${QS(S,T)}`}function NK(T,S){if(Array.isArray(S)){if(S.length===0)return R`true`;return R`${T} not in ${S.map(($)=>QS($,T))}`}return R`${T} not in ${QS(S,T)}`}function CK(T){return R`${T} is null`}function xK(T){return R`${T} is not null`}function jK(T){return R`exists ${T}`}function IK(T){return R`not exists ${T}`}function bK(T,S,$){return R`${T} between ${QS(S,T)} and ${QS($,T)}`}function qK(T,S,$){return R`${T} not between ${QS(S,T)} and ${QS($,T)}`}function ZK(T,S){return R`${T} like ${S}`}function mK(T,S){return R`${T} not like ${S}`}function hK(T,S){return R`${T} ilike ${S}`}function vK(T,S){return R`${T} not ilike ${S}`}var sF=(T,S)=>{return R`${T} = ${QS(S,T)}`},DK=(T,S)=>{return R`${T} <> ${QS(S,T)}`},TW=(T,S)=>{return R`${T} > ${QS(S,T)}`},UK=(T,S)=>{return R`${T} >= ${QS(S,T)}`},VK=(T,S)=>{return R`${T} < ${QS(S,T)}`},LK=(T,S)=>{return R`${T} <= ${QS(S,T)}`};function PK(T){return R`${T} asc`}function nK(T){return R`${T} desc`}class cK{static[Y]="ConsoleLogWriter";write(T){console.log(T)}}class _1{static[Y]="DefaultLogger";writer;constructor(T){this.writer=T?.writer??new cK}logQuery(T,S){const $=S.map((M)=>{try{return JSON.stringify(M)}catch{return String(M)}}),f=$.length?` -- params: [${$.join(", ")}]`:"";this.writer.write(`Query: ${T}${f}`)}}class E1{static[Y]="NoopLogger";logQuery(){}}class zS{static[Y]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(T){return this.then(void 0,T)}finally(T){return this.then((S)=>{return T?.(),S},(S)=>{throw T?.(),S})}then(T,S){return this.execute().then(T,S)}}function gK(T,S,$){const f={},M=T.reduce((J,{path:F,field:W},k)=>{let X;if(L(W,BT))X=W;else if(L(W,t))X=W.decoder;else X=W.sql.decoder;let w=J;for(let[K,O]of F.entries())if(K<F.length-1){if(!(O in w))w[O]={};w=w[O]}else{const H=S[k],_=w[O]=H===null?null:X.mapFromDriverValue(H);if($&&L(W,BT)&&F.length===2){const Q=F[0];if(!(Q in f))f[Q]=_===null?PS(W.table):!1;else if(typeof f[Q]==="string"&&f[Q]!==PS(W.table))f[Q]=!1}}return J},{});if($&&Object.keys(f).length>0){for(let[J,F]of Object.entries(f))if(typeof F==="string"&&!$[F])M[J]=null}return M}function nS(T,S){return Object.entries(T).reduce(($,[f,M])=>{if(typeof f!=="string")return $;const J=S?[...S,f]:[f];if(L(M,BT)||L(M,t)||L(M,t.Aliased))$.push({path:J,field:M});else if(L(M,g))$.push(...nS(M[g.Symbol.Columns],J));else $.push(...nS(M,J));return $},[])}function D1(T,S){const $=Object.keys(T),f=Object.keys(S);if($.length!==f.length)return!1;for(let[M,J]of $.entries())if(J!==f[M])return!1;return!0}function SW(T,S){const $=Object.entries(S).filter(([,f])=>f!==void 0).map(([f,M])=>{if(L(M,t))return[f,M];else return[f,new IS(M,T[g.Symbol.Columns][f])]});if($.length===0)throw new Error("No values to set");return Object.fromEntries($)}function oK(T,S){for(let $ of S)for(let f of Object.getOwnPropertyNames($.prototype)){if(f==="constructor")continue;Object.defineProperty(T.prototype,f,Object.getOwnPropertyDescriptor($.prototype,f)||Object.create(null))}}function tK(T){return T[g.Symbol.Columns]}function y1(T){return L(T,fS)?T._.alias:L(T,yS)?T[ZT].name:L(T,t)?void 0:T[g.Symbol.IsAlias]?T[g.Symbol.Name]:T[g.Symbol.BaseName]}function KT(T,S){return{name:typeof T==="string"&&T.length>0?T:"",config:typeof T==="object"?T:S}}class c$ extends o{static[Y]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(T){if(T){const{name:S,...$}=T;this.config.generatedIdentity={type:"always",sequenceName:S,sequenceOptions:$}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(T){if(T){const{name:S,...$}=T;this.config.generatedIdentity={type:"byDefault",sequenceName:S,sequenceOptions:$}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}function dK(T,S){const{name:$,config:f}=KT(T,S);if(f.mode==="number")return new iK($);return new uK($)}class iK extends c${static[Y]="PgBigInt53Builder";constructor(T){super(T,"number","PgBigInt53")}build(T){return new pK(T,this.config)}}class pK extends h{static[Y]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class uK extends c${static[Y]="PgBigInt64Builder";constructor(T){super(T,"bigint","PgBigInt64")}build(T){return new lK(T,this.config)}}class lK extends h{static[Y]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(T){return BigInt(T)}}function TA(T,S){const{name:$,config:f}=KT(T,S);if(f.mode==="number")return new rK($);return new eK($)}class rK extends o{static[Y]="PgBigSerial53Builder";constructor(T){super(T,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new aK(T,this.config)}}class aK extends h{static[Y]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class eK extends o{static[Y]="PgBigSerial64Builder";constructor(T){super(T,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(T){return new sK(T,this.config)}}class sK extends h{static[Y]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(T){return BigInt(T)}}function IJ(T){return new SA(T??"")}class SA extends o{static[Y]="PgBooleanBuilder";constructor(T){super(T,"boolean","PgBoolean")}build(T){return new $A(T,this.config)}}class $A extends h{static[Y]="PgBoolean";getSQLType(){return"boolean"}}function JA(T,S={}){const{name:$,config:f}=KT(T,S);return new fA($,f)}class fA extends o{static[Y]="PgCharBuilder";constructor(T,S){super(T,"string","PgChar");this.config.length=S.length,this.config.enumValues=S.enum}build(T){return new MA(T,this.config)}}class MA extends h{static[Y]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function kA(T){return new FA(T??"")}class FA extends o{static[Y]="PgCidrBuilder";constructor(T){super(T,"string","PgCidr")}build(T){return new WA(T,this.config)}}class WA extends h{static[Y]="PgCidr";getSQLType(){return"cidr"}}function KA(T){return(S,$)=>{const{name:f,config:M}=KT(S,$);return new XA(f,M,T)}}class XA extends o{static[Y]="PgCustomColumnBuilder";constructor(T,S,$){super(T,"custom","PgCustomColumn");this.config.fieldConfig=S,this.config.customTypeParams=$}build(T){return new wA(T,this.config)}}class wA extends h{static[Y]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(T,S){super(T,S);this.sqlName=S.customTypeParams.dataType(S.fieldConfig),this.mapTo=S.customTypeParams.toDriver,this.mapFrom=S.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(T){return typeof this.mapFrom==="function"?this.mapFrom(T):T}mapToDriverValue(T){return typeof this.mapTo==="function"?this.mapTo(T):T}}class U$ extends o{static[Y]="PgDateColumnBaseBuilder";defaultNow(){return this.default(R`now()`)}}function OA(T,S){const{name:$,config:f}=KT(T,S);if(f?.mode==="date")return new AA($);return new YA($)}class AA extends U${static[Y]="PgDateBuilder";constructor(T){super(T,"date","PgDate")}build(T){return new $W(T,this.config)}}class $W extends h{static[Y]="PgDate";getSQLType(){return"date"}mapFromDriverValue(T){return new Date(T)}mapToDriverValue(T){return T.toISOString()}}class YA extends U${static[Y]="PgDateStringBuilder";constructor(T){super(T,"string","PgDateString")}build(T){return new fW(T,this.config)}}class fW extends h{static[Y]="PgDateString";getSQLType(){return"date"}}function zA(T){return new RA(T??"")}class RA extends o{static[Y]="PgDoublePrecisionBuilder";constructor(T){super(T,"number","PgDoublePrecision")}build(T){return new GA(T,this.config)}}class GA extends h{static[Y]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseFloat(T);return T}}function EA(T){return new HA(T??"")}class HA extends o{static[Y]="PgInetBuilder";constructor(T){super(T,"string","PgInet")}build(T){return new _A(T,this.config)}}class _A extends h{static[Y]="PgInet";getSQLType(){return"inet"}}function MW(T){return new DA(T??"")}class DA extends c${static[Y]="PgIntegerBuilder";constructor(T){super(T,"number","PgInteger")}build(T){return new yA(T,this.config)}}class yA extends h{static[Y]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseInt(T);return T}}function VA(T,S={}){const{name:$,config:f}=KT(T,S);return new QA($,f)}class QA extends o{static[Y]="PgIntervalBuilder";constructor(T,S){super(T,"string","PgInterval");this.config.intervalConfig=S}build(T){return new UA(T,this.config)}}class UA extends h{static[Y]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){const T=this.fields?` ${this.fields}`:"",S=this.precision?`(${this.precision})`:"";return`interval${T}${S}`}}function BA(T){return new LA(T??"")}class LA extends o{static[Y]="PgJsonBuilder";constructor(T){super(T,"json","PgJson")}build(T){return new JW(T,this.config)}}class JW extends h{static[Y]="PgJson";constructor(T,S){super(T,S)}getSQLType(){return"json"}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){if(typeof T==="string")try{return JSON.parse(T)}catch{return T}return T}}function CA(T){return new NA(T??"")}class NA extends o{static[Y]="PgJsonbBuilder";constructor(T){super(T,"json","PgJsonb")}build(T){return new FW(T,this.config)}}class FW extends h{static[Y]="PgJsonb";constructor(T,S){super(T,S)}getSQLType(){return"jsonb"}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){if(typeof T==="string")try{return JSON.parse(T)}catch{return T}return T}}function qA(T,S){const{name:$,config:f}=KT(T,S);if(!f?.mode||f.mode==="tuple")return new xA($);return new IA($)}class xA extends o{static[Y]="PgLineBuilder";constructor(T){super(T,"array","PgLine")}build(T){return new jA(T,this.config)}}class jA extends h{static[Y]="PgLine";getSQLType(){return"line"}mapFromDriverValue(T){const[S,$,f]=T.slice(1,-1).split(",");return[Number.parseFloat(S),Number.parseFloat($),Number.parseFloat(f)]}mapToDriverValue(T){return`{${T[0]},${T[1]},${T[2]}}`}}class IA extends o{static[Y]="PgLineABCBuilder";constructor(T){super(T,"json","PgLineABC")}build(T){return new bA(T,this.config)}}class bA extends h{static[Y]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(T){const[S,$,f]=T.slice(1,-1).split(",");return{a:Number.parseFloat(S),b:Number.parseFloat($),c:Number.parseFloat(f)}}mapToDriverValue(T){return`{${T.a},${T.b},${T.c}}`}}function hA(T){return new ZA(T??"")}class ZA extends o{static[Y]="PgMacaddrBuilder";constructor(T){super(T,"string","PgMacaddr")}build(T){return new mA(T,this.config)}}class mA extends h{static[Y]="PgMacaddr";getSQLType(){return"macaddr"}}function nA(T){return new vA(T??"")}class vA extends o{static[Y]="PgMacaddr8Builder";constructor(T){super(T,"string","PgMacaddr8")}build(T){return new PA(T,this.config)}}class PA extends h{static[Y]="PgMacaddr8";getSQLType(){return"macaddr8"}}function gA(T,S){const{name:$,config:f}=KT(T,S);return new cA($,f?.precision,f?.scale)}class cA extends o{static[Y]="PgNumericBuilder";constructor(T,S,$){super(T,"string","PgNumeric");this.config.precision=S,this.config.scale=$}build(T){return new WW(T,this.config)}}class WW extends h{static[Y]="PgNumeric";precision;scale;constructor(T,S){super(T,S);this.precision=S.precision,this.scale=S.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 uA(T,S){const{name:$,config:f}=KT(T,S);if(!f?.mode||f.mode==="tuple")return new oA($);return new iA($)}class oA extends o{static[Y]="PgPointTupleBuilder";constructor(T){super(T,"array","PgPointTuple")}build(T){return new tA(T,this.config)}}class tA extends h{static[Y]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){const[S,$]=T.slice(1,-1).split(",");return[Number.parseFloat(S),Number.parseFloat($)]}return[T.x,T.y]}mapToDriverValue(T){return`(${T[0]},${T[1]})`}}class iA extends o{static[Y]="PgPointObjectBuilder";constructor(T){super(T,"json","PgPointObject")}build(T){return new pA(T,this.config)}}class pA extends h{static[Y]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){const[S,$]=T.slice(1,-1).split(",");return{x:Number.parseFloat(S),y:Number.parseFloat($)}}return T}mapToDriverValue(T){return`(${T.x},${T.y})`}}function fO(T){const S=[];for(let $=0;$<T.length;$+=2)S.push(Number.parseInt(T.slice($,$+2),16));return new Uint8Array(S)}function lA(T,S){const $=new ArrayBuffer(8),f=new DataView($);for(let M=0;M<8;M++)f.setUint8(M,T[S+M]);return f.getFloat64(0,!0)}function Q1(T){const S=fO(T);let $=0;const f=S[$];$+=1;const M=new DataView(S.buffer),J=M.getUint32($,f===1);$+=4;let F;if(J&536870912)F=M.getUint32($,f===1),$+=4;if((J&65535)===1){const W=lA(S,$);$+=8;const k=lA(S,$);return $+=8,[W,k]}throw new Error("Unsupported geometry type")}function sA(T,S){const{name:$,config:f}=KT(T,S);if(!f?.mode||f.mode==="tuple")return new dA($);return new aA($)}class dA extends o{static[Y]="PgGeometryBuilder";constructor(T){super(T,"array","PgGeometry")}build(T){return new rA(T,this.config)}}class rA extends h{static[Y]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){return Q1(T)}mapToDriverValue(T){return`point(${T[0]} ${T[1]})`}}class aA extends o{static[Y]="PgGeometryObjectBuilder";constructor(T){super(T,"json","PgGeometryObject")}build(T){return new eA(T,this.config)}}class eA extends h{static[Y]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){const S=Q1(T);return{x:S[0],y:S[1]}}mapToDriverValue(T){return`point(${T.x} ${T.y})`}}function $2(T){return new T2(T??"")}class T2 extends o{static[Y]="PgRealBuilder";constructor(T,S){super(T,"number","PgReal");this.config.length=S}build(T){return new S2(T,this.config)}}class S2 extends h{static[Y]="PgReal";constructor(T,S){super(T,S)}getSQLType(){return"real"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number.parseFloat(T);return T}}function J2(T){return new f2(T??"")}class f2 extends o{static[Y]="PgSerialBuilder";constructor(T){super(T,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new M2(T,this.config)}}class M2 extends h{static[Y]="PgSerial";getSQLType(){return"serial"}}function k2(T){return new F2(T??"")}class F2 extends c${static[Y]="PgSmallIntBuilder";constructor(T){super(T,"number","PgSmallInt")}build(T){return new W2(T,this.config)}}class W2 extends h{static[Y]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number(T);return T}}function K2(T){return new X2(T??"")}class X2 extends o{static[Y]="PgSmallSerialBuilder";constructor(T){super(T,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new w2(T,this.config)}}class w2 extends h{static[Y]="PgSmallSerial";getSQLType(){return"smallserial"}}function O2(T,S={}){const{name:$,config:f}=KT(T,S);return new A2($,f)}class A2 extends o{static[Y]="PgTextBuilder";constructor(T,S){super(T,"string","PgText");this.config.enumValues=S.enum}build(T){return new Y2(T,this.config)}}class Y2 extends h{static[Y]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function G2(T,S={}){const{name:$,config:f}=KT(T,S);return new R2($,f.withTimezone??!1,f.precision)}class R2 extends U${constructor(T,S,$){super(T,"string","PgTime");this.withTimezone=S,this.precision=$,this.config.withTimezone=S,this.config.precision=$}static[Y]="PgTimeBuilder";build(T){return new kW(T,this.config)}}class kW extends h{static[Y]="PgTime";withTimezone;precision;constructor(T,S){super(T,S);this.withTimezone=S.withTimezone,this.precision=S.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function $$(T,S={}){const{name:$,config:f}=KT(T,S);if(f?.mode==="string")return new H2($,f.withTimezone??!1,f.precision);return new z2($,f?.withTimezone??!1,f?.precision)}class z2 extends U${static[Y]="PgTimestampBuilder";constructor(T,S,$){super(T,"date","PgTimestamp");this.config.withTimezone=S,this.config.precision=$}build(T){return new XW(T,this.config)}}class XW extends h{static[Y]="PgTimestamp";withTimezone;precision;constructor(T,S){super(T,S);this.withTimezone=S.withTimezone,this.precision=S.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(T)=>{return new Date(this.withTimezone?T:T+"+0000")};mapToDriverValue=(T)=>{return T.toISOString()}}class H2 extends U${static[Y]="PgTimestampStringBuilder";constructor(T,S,$){super(T,"string","PgTimestampString");this.config.withTimezone=S,this.config.precision=$}build(T){return new wW(T,this.config)}}class wW extends h{static[Y]="PgTimestampString";withTimezone;precision;constructor(T,S){super(T,S);this.withTimezone=S.withTimezone,this.precision=S.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function bS(T){return new _2(T??"")}class _2 extends o{static[Y]="PgUUIDBuilder";constructor(T){super(T,"string","PgUUID")}defaultRandom(){return this.default(R`gen_random_uuid()`)}build(T){return new KW(T,this.config)}}class KW extends h{static[Y]="PgUUID";getSQLType(){return"uuid"}}function MS(T,S={}){const{name:$,config:f}=KT(T,S);return new E2($,f)}class E2 extends o{static[Y]="PgVarcharBuilder";constructor(T,S){super(T,"string","PgVarchar");this.config.length=S.length,this.config.enumValues=S.enum}build(T){return new D2(T,this.config)}}class D2 extends h{static[Y]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function U2(T,S){const{name:$,config:f}=KT(T,S);return new y2($,f)}class y2 extends o{static[Y]="PgBinaryVectorBuilder";constructor(T,S){super(T,"string","PgBinaryVector");this.config.dimensions=S.dimensions}build(T){return new Q2(T,this.config)}}class Q2 extends h{static[Y]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function B2(T,S){const{name:$,config:f}=KT(T,S);return new V2($,f)}class V2 extends o{static[Y]="PgHalfVectorBuilder";constructor(T,S){super(T,"array","PgHalfVector");this.config.dimensions=S.dimensions}build(T){return new L2(T,this.config)}}class L2 extends h{static[Y]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){return T.slice(1,-1).split(",").map((S)=>Number.parseFloat(S))}}function x2(T,S){const{name:$,config:f}=KT(T,S);return new N2($,f)}class N2 extends o{static[Y]="PgSparseVectorBuilder";constructor(T,S){super(T,"string","PgSparseVector");this.config.dimensions=S.dimensions}build(T){return new C2(T,this.config)}}class C2 extends h{static[Y]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function b2(T,S){const{name:$,config:f}=KT(T,S);return new j2($,f)}class j2 extends o{static[Y]="PgVectorBuilder";constructor(T,S){super(T,"array","PgVector");this.config.dimensions=S.dimensions}build(T){return new I2(T,this.config)}}class I2 extends h{static[Y]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){return T.slice(1,-1).split(",").map((S)=>Number.parseFloat(S))}}function q2(){return{bigint:dK,bigserial:TA,boolean:IJ,char:JA,cidr:kA,customType:KA,date:OA,doublePrecision:zA,inet:EA,integer:MW,interval:VA,json:BA,jsonb:CA,line:qA,macaddr:hA,macaddr8:nA,numeric:gA,point:uA,geometry:sA,real:$2,serial:J2,smallint:k2,smallserial:K2,text:O2,time:G2,timestamp:$$,uuid:bS,varchar:MS,bit:U2,halfvec:B2,sparsevec:x2,vector:b2}}function MO(T,S,$,f,M=T){const J=new f$(T,f,M),F=typeof S==="function"?S(q2()):S,W=Object.fromEntries(Object.entries(F).map(([w,K])=>{const O=K;O.setName(w);const H=O.build(J);return J[U1].push(...O.buildForeignKeys(H,J)),[w,H]})),k=Object.fromEntries(Object.entries(F).map(([w,K])=>{const O=K;O.setName(w);const H=O.buildExtraConfigColumn(J);return[w,H]})),X=Object.assign(J,W);if(X[g.Symbol.Columns]=W,X[g.Symbol.ExtraConfigColumns]=k,$)X[f$.Symbol.ExtraConfigBuilder]=$;return X}var U1=Symbol.for("drizzle:PgInlineForeignKeys");class f$ extends g{static[Y]="PgTable";static Symbol=Object.assign({},g.Symbol,{InlineForeignKeys:U1});[U1]=[];[g.Symbol.ExtraConfigBuilder]=void 0}var g$=(T,S,$)=>{return MO(T,S,$,void 0)};function Z2(...T){if(T[0].columns)return new bJ(T[0].columns,T[0].name);return new bJ(T)}class bJ{static[Y]="PgPrimaryKeyBuilder";columns;name;constructor(T,S){this.columns=T,this.name=S}build(T){return new m2(T,this.columns,this.name)}}class m2{constructor(T,S,$){this.table=T,this.columns=S,this.name=$}static[Y]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[f$.Symbol.Name]}_${this.columns.map((T)=>T.name).join("_")}_pk`}}function v2(){return{and:jJ,between:bK,eq:sF,exists:jK,gt:TW,gte:UK,ilike:hK,inArray:BK,isNull:CK,isNotNull:xK,like:ZK,lt:VK,lte:LK,ne:DK,not:QK,notBetween:qK,notExists:IK,notLike:mK,notIlike:vK,notInArray:NK,or:yK,sql:R}}function P2(){return{sql:R,asc:PK,desc:nK}}function n2(T,S){if(Object.keys(T).length===1&&"default"in T&&!L(T.default,g))T=T.default;const $={},f={},M={};for(let[J,F]of Object.entries(T))if(L(F,g)){const W=Qf(F),k=f[W];$[W]=J,M[J]={tsName:J,dbName:F[g.Symbol.Name],schema:F[g.Symbol.Schema],columns:F[g.Symbol.Columns],relations:k?.relations??{},primaryKey:k?.primaryKey??[]};for(let w of Object.values(F[g.Symbol.Columns]))if(w.primary)M[J].primaryKey.push(w);const X=F[g.Symbol.ExtraConfigBuilder]?.(F[g.Symbol.ExtraConfigColumns]);if(X){for(let w of Object.values(X))if(L(w,bJ))M[J].primaryKey.push(...w.columns)}}else if(L(F,h2)){const W=Qf(F.table),k=$[W],X=F.config(S(F.table));let w;for(let[K,O]of Object.entries(X))if(k){const H=M[k];if(H.relations[K]=O,w)H.primaryKey.push(...w)}else{if(!(W in f))f[W]={relations:{},primaryKey:w};f[W].relations[K]=O}}return{tables:M,tableNamesMap:$}}function JO(T){return function S($,f){return new o$(T,$,f,f?.fields.reduce((M,J)=>M&&J.notNull,!0)??!1)}}function FO(T){return function S($,f){return new qJ(T,$,f)}}function c2(T,S,$){if(L($,o$)&&$.config)return{fields:$.config.fields,references:$.config.references};const f=S[Qf($.referencedTable)];if(!f)throw new Error(`Table "${$.referencedTable[g.Symbol.Name]}" not found in schema`);const M=T[f];if(!M)throw new Error(`Table "${f}" not found in schema`);const J=$.sourceTable,F=S[Qf(J)];if(!F)throw new Error(`Table "${J[g.Symbol.Name]}" not found in schema`);const W=[];for(let k of Object.values(M.relations))if($.relationName&&$!==k&&k.relationName===$.relationName||!$.relationName&&k.referencedTable===$.sourceTable)W.push(k);if(W.length>1)throw $.relationName?new Error(`There are multiple relations with name "${$.relationName}" in table "${f}"`):new Error(`There are multiple relations between "${f}" and "${$.sourceTable[g.Symbol.Name]}". Please specify relation name`);if(W[0]&&L(W[0],o$)&&W[0].config)return{fields:W[0].config.references,references:W[0].config.fields};throw new Error(`There is not enough information to infer relation "${F}.${$.fieldName}"`)}function g2(T){return{one:JO(T),many:FO(T)}}function AW(T,S,$,f,M=(J)=>J){const J={};for(let[F,W]of f.entries())if(W.isJson){const k=S.relations[W.tsKey],X=$[F],w=typeof X==="string"?JSON.parse(X):X;J[W.tsKey]=L(k,o$)?w&&AW(T,T[W.relationTableTsKey],w,W.selection,M):w.map((K)=>AW(T,T[W.relationTableTsKey],K,W.selection,M))}else{const k=M($[F]),X=W.field;let w;if(L(X,BT))w=X;else if(L(X,t))w=X.decoder;else w=X.sql.decoder;J[W.tsKey]=k===null?null:w.mapFromDriverValue(k)}return J}class V1{constructor(T,S,$){this.sourceTable=T,this.referencedTable=S,this.relationName=$,this.referencedTableName=S[g.Symbol.Name]}static[Y]="Relation";referencedTableName;fieldName}class h2{constructor(T,S){this.table=T,this.config=S}static[Y]="Relations"}class o$ extends V1{constructor(T,S,$,f){super(T,S,$?.relationName);this.config=$,this.isNullable=f}static[Y]="One";withFieldName(T){const S=new o$(this.sourceTable,this.referencedTable,this.config,this.isNullable);return S.fieldName=T,S}}class qJ extends V1{constructor(T,S,$){super(T,S,$?.relationName);this.config=$}static[Y]="Many";withFieldName(T){const S=new qJ(this.sourceTable,this.referencedTable,this.config);return S.fieldName=T,S}}import sO from"path";import xO from"os";import jO from"fs";function WO(T){if(YW.has(T))return YW.get(T);const S=Error.stackTraceLimit;return Error.stackTraceLimit=4,YW.set(T,new Error),Error.stackTraceLimit=S,YW.get(T)}var YW=new Map,L1=new Map,B1=Symbol("OriginError"),bM={};class cS extends Promise{constructor(T,S,$,f,M={}){let J,F;super((W,k)=>{J=W,F=k});this.tagged=Array.isArray(T.raw),this.strings=T,this.args=S,this.handler=$,this.canceller=f,this.options=M,this.state=null,this.statement=null,this.resolve=(W)=>(this.active=!1,J(W)),this.reject=(W)=>(this.active=!1,F(W)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[B1]=this.handler.debug?new Error:this.tagged&&WO(this.strings)}get origin(){return(this.handler.debug?this[B1].stack:this.tagged&&L1.has(this.strings)?L1.get(this.strings):L1.set(this.strings,this[B1].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(T=1,S){if(this.options.simple=!1,typeof T==="function")S=T,T=1;if(this.cursorRows=T,typeof S==="function")return this.cursorFn=S,this;let $;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};$&&$();const f=new Promise((M,J)=>{this.cursorFn=(F)=>{return M({value:F,done:!1}),new Promise((W)=>$=W)},this.resolve=()=>(this.active=!1,M({done:!0})),this.reject=(F)=>(this.active=!1,J(F))});return this.execute(),f},return(){return $&&$(bM),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw new Error(".stream has been renamed to .forEach")}forEach(T){return this.forEachFn=T,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}}function o2(T,S,$){const{host:f,port:M}=$||S,J=Object.assign(new Error("write "+T+" "+(S.path||f+":"+M)),{code:T,errno:T,address:S.path||f},S.path?{}:{port:M});return Error.captureStackTrace(J,o2),J}function t2(T){const S=new qM(T);return Error.captureStackTrace(S,t2),S}function i2(T,S){const $=Object.assign(new Error(T+": "+S),{code:T});return Error.captureStackTrace($,i2),$}function p2(T){const S=Object.assign(new Error(T+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:T});return Error.captureStackTrace(S,p2),S}class qM extends Error{constructor(T){super(T.message);this.name=this.constructor.name,Object.assign(this,T)}}var tT={connection:o2,postgres:t2,generic:i2,notSupported:p2};function HW(T,S,$,f){let M=T instanceof Y$?T.value:T;if(M===void 0){if(T instanceof Y$?T.value=f.transform.undefined:M=T=f.transform.undefined,M===void 0)throw tT.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+$.push(T instanceof Y$?(S.push(T.value),T.array?T.array[T.type||RW(T.value)]||T.type||r2(T.value):T.type):(S.push(T),RW(T)))}function j1(T,S,$,f,M,J){for(let F=1;F<T.strings.length;F++)S+=I1(S,$,f,M,J)+T.strings[F],$=T.args[F];return S}function I1(T,S,$,f,M){return S instanceof zW?S.build(T,$,f,M):S instanceof cS?x1(S,$,f,M):S instanceof vJ?S.value:S&&S[0]instanceof cS?S.reduce((J,F)=>J+" "+x1(F,$,f,M),""):HW(S,$,f,M)}function x1(T,S,$,f){return T.fragment=!0,j1(T,T.strings[0],T.args[0],S,$,f)}function d2(T,S,$,f,M){return T.map((J)=>"("+f.map((F)=>I1("values",J[F],S,$,M)).join(",")+")").join(",")}function u2(T,S,$,f,M){const J=Array.isArray(T[0]),F=S.length?S.flat():Object.keys(J?T[0]:T);return d2(J?T:[T],$,f,F,M)}function OW(T,S,$,f,M){if(typeof T==="string"&&(T=[T].concat(S)),Array.isArray(T))return b1(T,M);let J;return(S.length?S.flat():Object.keys(T)).map((W)=>{return J=T[W],(J instanceof cS?x1(J,$,f,M):J instanceof vJ?J.value:HW(J,$,f,M))+" as "+_W(M.transform.column.to?M.transform.column.to(W):W)}).join(",")}function N1(){throw tT.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}function r2(T){if(Array.isArray(T))return r2(T[0]);return typeof T==="string"?1009:0}function e2(T){return Object.keys(T).reduce((S,$)=>{if(T[$].from&&[].concat(T[$].from).forEach((f)=>S.parsers[f]=T[$].parse),T[$].serialize)S.serializers[T[$].to]=T[$].serialize,T[$].from&&[].concat(T[$].from).forEach((f)=>S.serializers[f]=T[$].serialize);return S},{parsers:{},serializers:{}})}function b1(T,{transform:{column:S}}){return T.map(($)=>_W(S.to?S.to($):$)).join(",")}function OO(T){return T.replace(AO,"\\\\").replace(YO,'\\"')}function S8(T,S,$,f){const M=[],J=f===1020?";":",";for(;T.i<S.length;T.i++){if(T.char=S[T.i],T.quoted)if(T.char==="\\")T.str+=S[++T.i];else if(T.char==='"')M.push($?$(T.str):T.str),T.str="",T.quoted=S[T.i+1]==='"',T.last=T.i+2;else T.str+=T.char;else if(T.char==='"')T.quoted=!0;else if(T.char==="{")T.last=++T.i,M.push(S8(T,S,$,f));else if(T.char==="}"){T.quoted=!1,T.last<T.i&&M.push($?$(S.slice(T.last,T.i)):S.slice(T.last,T.i)),T.last=T.i+1;break}else if(T.char===J&&T.p!=="}"&&T.p!=='"')M.push($?$(S.slice(T.last,T.i)):S.slice(T.last,T.i)),T.last=T.i+1;T.p=T.char}return T.last<T.i&&M.push($?$(S.slice(T.last,T.i+1)):S.slice(T.last,T.i+1)),M}function q1(T){return function S($,f){return typeof $==="object"&&$!==null&&(f.type===114||f.type===3802)?Array.isArray($)?$.map((M)=>S(M,f)):Object.entries($).reduce((M,[J,F])=>Object.assign(M,{[T(J)]:S(F,f)}),{}):$}}var kO={string:{to:25,from:null,serialize:(T)=>""+T},number:{to:0,from:[21,23,26,700,701],serialize:(T)=>""+T,parse:(T)=>+T},json:{to:114,from:[114,3802],serialize:(T)=>JSON.stringify(T),parse:(T)=>JSON.parse(T)},boolean:{to:16,from:16,serialize:(T)=>T===!0?"t":"f",parse:(T)=>T==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(T)=>(T instanceof Date?T:new Date(T)).toISOString(),parse:(T)=>new Date(T)},bytea:{to:17,from:17,serialize:(T)=>"\\x"+Buffer.from(T).toString("hex"),parse:(T)=>Buffer.from(T.slice(2),"hex")}};class GW{then(){N1()}catch(){N1()}finally(){N1()}}class vJ extends GW{constructor(T){super();this.value=_W(T)}}class Y$ extends GW{constructor(T,S,$){super();this.value=T,this.type=S,this.array=$}}class zW extends GW{constructor(T,S){super();this.first=T,this.rest=S}build(T,S,$,f){const M=XO.map(([J,F])=>({fn:F,i:T.search(J)})).sort((J,F)=>J.i-F.i).pop();return M.i===-1?b1(this.first,f):M.fn(this.first,this.rest,S,$,f)}}var l2=e2(kO),XO=Object.entries({values:u2,in:(...T)=>{const S=u2(...T);return S==="()"?"(null)":S},select:OW,as:OW,returning:OW,"\\(":OW,update(T,S,$,f,M){return(S.length?S.flat():Object.keys(T)).map((J)=>_W(M.transform.column.to?M.transform.column.to(J):J)+"="+I1("values",T[J],$,f,M))},insert(T,S,$,f,M){const J=S.length?S.flat():Object.keys(Array.isArray(T)?T[0]:T);return"("+b1(J,M)+")values"+d2(Array.isArray(T)?T:[T],$,f,J,M)}}).map(([T,S])=>[new RegExp("((?:^|[\\s(])"+T+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),S]),wO=l2.serializers,KO=l2.parsers;var a2=function(T){const S=e2(T||{});return{serializers:Object.assign({},wO,S.serializers),parsers:Object.assign({},KO,S.parsers)}},_W=function T(S){return'"'+S.replace(/"/g,'""').replace(/\./g,'"."')+'"'},RW=function T(S){return S instanceof Y$?S.type:S instanceof Date?1184:S instanceof Uint8Array?17:S===!0||S===!1?16:typeof S==="bigint"?20:Array.isArray(S)?T(S[0]):0},AO=/\\/g,YO=/"/g,s2=function T(S,$,f,M){if(Array.isArray(S)===!1)return S;if(!S.length)return"{}";const J=S[0],F=M===1020?";":",";if(Array.isArray(J)&&!J.type)return"{"+S.map((W)=>T(W,$,f,M)).join(F)+"}";return"{"+S.map((W)=>{if(W===void 0){if(W=f.transform.undefined,W===void 0)throw tT.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return W===null?"null":'"'+OO($?$(W.type?W.value:W):""+W)+'"'}).join(F)+"}"},C1={i:0,char:null,str:"",quoted:!1,last:0},T8=function T(S,$,f){return C1.i=C1.last=0,S8(C1,S,$,f)},Uf=(T)=>{let S=T[0];for(let $=1;$<T.length;$++)S+=T[$]==="_"?T[++$].toUpperCase():T[$];return S},Vf=(T)=>{let S=T[0].toUpperCase();for(let $=1;$<T.length;$++)S+=T[$]==="_"?T[++$].toUpperCase():T[$];return S},Lf=(T)=>T.replace(/_/g,"-"),ZJ=(T)=>T.replace(/([A-Z])/g,"_$1").toLowerCase(),mJ=(T)=>(T.slice(0,1)+T.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),hJ=(T)=>T.replace(/-/g,"_");Uf.column={from:Uf};Uf.value={from:q1(Uf)};ZJ.column={to:ZJ};var Z1={...Uf};Z1.column.to=ZJ;Vf.column={from:Vf};Vf.value={from:q1(Vf)};mJ.column={to:mJ};var m1={...Vf};m1.column.to=mJ;Lf.column={from:Lf};Lf.value={from:q1(Lf)};hJ.column={to:hJ};var h1={...Lf};h1.column.to=hJ;import $8 from"net";import HO from"tls";import PJ from"crypto";import v1 from"stream";import{performance as f8}from"perf_hooks";class Bf extends Array{constructor(){super();Object.defineProperties(this,{count:{value:null,writable:!0},state:{value:null,writable:!0},command:{value:null,writable:!0},columns:{value:null,writable:!0},statement:{value:null,writable:!0}})}static get[Symbol.species](){return Array}}function RO(T=[]){let S=T.slice(),$=0;return{get length(){return S.length-$},remove:(f)=>{const M=S.indexOf(f);return M===-1?null:(S.splice(M,1),f)},push:(f)=>(S.push(f),f),shift:()=>{const f=S[$++];if($===S.length)$=0,S=[];else S[$-1]=void 0;return f}}}var qS=RO;function EW(T){if(AS.length-ET.i<T){const S=AS,$=S.length;AS=Buffer.allocUnsafe($+($>>1)+T),S.copy(AS)}}function zO(){return ET.i=0,ET}var AS=Buffer.allocUnsafe(256),GO="BCcDdEFfHPpQSX".split("").reduce((T,S)=>{const $=S.charCodeAt(0);return T[S]=()=>{return AS[0]=$,ET.i=5,ET},T},{}),ET=Object.assign(zO,GO,{N:String.fromCharCode(0),i:0,inc(T){return ET.i+=T,ET},str(T){const S=Buffer.byteLength(T);return EW(S),ET.i+=AS.write(T,ET.i,S,"utf8"),ET},i16(T){return EW(2),AS.writeUInt16BE(T,ET.i),ET.i+=2,ET},i32(T,S){if(S||S===0)return AS.writeUInt32BE(T,S),ET;return EW(4),AS.writeUInt32BE(T,ET.i),ET.i+=4,ET},z(T){return EW(T),AS.fill(0,ET.i,ET.i+T),ET.i+=T,ET},raw(T){return AS=Buffer.concat([AS.subarray(0,ET.i),T]),ET.i=AS.length,ET},end(T=1){AS.writeUInt32BE(ET.i-T,T);const S=AS.subarray(0,ET.i);return ET.i=0,AS=Buffer.allocUnsafe(256),S}}),r=ET;function F8(T,S={},{onopen:$=ZM,onend:f=ZM,onclose:M=ZM}={}){const{ssl:J,max:F,user:W,host:k,port:X,database:w,parsers:K,transform:O,onnotice:H,onnotify:_,onparameter:Q,max_pipeline:N,keep_alive:V,backoff:U,target_session_attrs:C}=T,B=qS(),D=_O++,z={pid:null,secret:null},y=n1(qW,T.idle_timeout),j=n1(qW,T.max_lifetime),v=n1(j8,T.connect_timeout);let G=null,m,q=new Bf,d=Buffer.alloc(0),MT=T.fetch_types,JT={},yT={},VS=Math.random().toString(36).slice(2),x=1,i=0,XT=0,HT=0,iT=0,kT=0,QT=0,cT=0,IT=null,NT=null,JS=!1,UT=null,gS=null,FS=null,L$=null,pT=null,CT=null,oS=null,M$=null,P=null,PM=null;const WS={queue:S.closed,idleTimer:y,connect(A){FS=A||!0,Kk()},terminate:cM,execute:nM,cancel:B8,end:qW,count:0,id:D};return S.closed&&S.closed.push(WS),WS;async function L8(){let A;try{A=T.socket?await Promise.resolve(T.socket(T)):new $8.Socket}catch(E){If(E);return}return A.on("error",If),A.on("close",Ak),A.on("drain",Xk),A}async function B8({pid:A,secret:E},a,zT){try{m=r().i32(16).i32(80877102).i32(A).i32(E).end(16),await wk(),G.once("error",zT),G.once("close",a)}catch(mT){zT(mT)}}function nM(A){if(JS)return iJ(A,tT.connection("CONNECTION_DESTROYED",T));if(A.cancelled)return;try{return A.state=z,P?B.push(A):(P=A,P.active=!0),x8(A),TS(N8(A))&&!A.describeFirst&&!A.cursorFn&&B.length<N&&(!A.options.onexecute||A.options.onexecute(WS))}catch(E){return B.length===0&&TS(t$),J$(E),!0}}function N8(A){if(A.parameters.length>=65534)throw tT.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return A.options.simple?r().Q().str(A.statement.string+r.N).end():A.describeFirst?Buffer.concat([Fk(A),M8]):A.prepare?A.prepared?tJ(A):Buffer.concat([Fk(A),tJ(A)]):C8(A)}function Fk(A){return Buffer.concat([Ok(A.statement.string,A.parameters,A.statement.types,A.statement.name),R4("S",A.statement.name)])}function tJ(A){return Buffer.concat([O4(A.parameters,A.statement.types,A.statement.name,A.cursorName),A.cursorFn?Rk("",A.cursorRows):DO])}function C8(A){return Buffer.concat([Ok(A.statement.string,A.parameters,A.statement.types),yO,tJ(A)])}function x8(A){const E=[],a=[],zT=j1(A,A.strings[0],A.args[0],E,a,T);!A.tagged&&A.args.forEach((mT)=>HW(mT,E,a,T)),A.prepare=T.prepare&&("prepare"in A.options?A.options.prepare:!0),A.string=zT,A.signature=A.prepare&&a+zT,A.onlyDescribe&&delete yT[A.signature],A.parameters=A.parameters||E,A.prepared=A.prepare&&A.signature in yT,A.describeFirst=A.onlyDescribe||E.length&&!A.prepared,A.statement=A.prepared?yT[A.signature]:{string:zT,types:a,name:A.prepare?VS+x++:""},typeof T.debug==="function"&&T.debug(D,zT,E,a)}function TS(A,E){if(CT=CT?Buffer.concat([CT,A]):Buffer.from(A),E||CT.length>=1024)return Wk(E);return NT===null&&(NT=setImmediate(Wk)),!0}function Wk(A){const E=G.write(CT,A);return NT!==null&&clearImmediate(NT),CT=NT=null,E}function j8(){J$(tT.connection("CONNECT_TIMEOUT",T,G)),G.destroy()}async function kk(){if(TS(EO),!await new Promise((E)=>G.once("data",(a)=>E(a[0]===83)))&&J==="prefer")return jf();G.removeAllListeners(),G=HO.connect({socket:G,servername:$8.isIP(G.host)?void 0:G.host,...J==="require"||J==="allow"||J==="prefer"?{rejectUnauthorized:!1}:J==="verify-full"?{}:typeof J==="object"?J:{}}),G.on("secureConnect",jf),G.on("error",If),G.on("close",Ak),G.on("drain",Xk)}function Xk(){!P&&$(WS)}function bW(A){if(UT){if(UT.push(A),XT-=A.length,XT>=0)return}d=UT?Buffer.concat(UT,kT-XT):d.length===0?A:Buffer.concat([d,A],d.length+A.length);while(d.length>4){if(kT=d.readUInt32BE(1),kT>=d.length){XT=kT-d.length,UT=[d];break}try{I8(d.subarray(0,kT+1))}catch(E){P&&(P.cursorFn||P.describeFirst)&&TS(t$),J$(E)}d=d.subarray(kT+1),XT=0,UT=null}}async function wk(){if(JS=!1,JT={},G||(G=await L8()),!G)return;if(v.start(),T.socket)return J?kk():jf();if(G.on("connect",J?kk:jf),T.path)return G.connect(T.path);G.ssl=J,G.connect(X[HT],k[HT]),G.host=k[HT],G.port=X[HT],HT=(HT+1)%X.length}function Kk(){setTimeout(wk,i?i+QT-f8.now():0)}function jf(){try{yT={},MT=T.fetch_types,VS=Math.random().toString(36).slice(2),x=1,j.start(),G.on("data",bW),V&&G.setKeepAlive&&G.setKeepAlive(!0,1000*V);const A=z4();TS(A)}catch(A){If(A)}}function If(A){if(WS.queue===S.connecting&&T.host[iT+1])return;J$(A);while(B.length)iJ(B.shift(),A)}function J$(A){pT&&(pT.destroy(A),pT=null),P&&iJ(P,A),FS&&(iJ(FS,A),FS=null)}function iJ(A,E){Object.defineProperties(E,{stack:{value:E.stack+A.origin.replace(/.*\n/,"\n"),enumerable:T.debug},query:{value:A.string,enumerable:T.debug},parameters:{value:A.parameters,enumerable:T.debug},args:{value:A.args,enumerable:T.debug},types:{value:A.statement&&A.statement.types,enumerable:T.debug}}),A.reject(E)}function qW(){return L$||(!WS.reserved&&f(WS),!WS.reserved&&!FS&&!P&&B.length===0?(cM(),new Promise((A)=>G&&G.readyState!=="closed"?G.once("close",A):A())):L$=new Promise((A)=>oS=A))}function cM(){if(JS=!0,pT||P||FS||B.length)If(tT.connection("CONNECTION_DESTROYED",T));if(clearImmediate(NT),G)G.removeListener("data",bW),G.removeListener("connect",jf),G.readyState==="open"&&G.end(r().X().end());oS&&(oS(),L$=oS=null)}async function Ak(A){if(d=Buffer.alloc(0),XT=0,UT=null,clearImmediate(NT),G.removeListener("data",bW),G.removeListener("connect",jf),y.cancel(),j.cancel(),v.cancel(),G.removeAllListeners(),G=null,FS)return Kk();!A&&(P||B.length)&&If(tT.connection("CONNECTION_CLOSED",T,G)),i=f8.now(),A&&T.shared.retries++,QT=(typeof U==="function"?U(T.shared.retries):U)*1000,M(WS,tT.connection("CONNECTION_CLOSED",T,G))}function I8(A,E=A[0]){(E===68?b8:E===100?F4:E===65?T4:E===83?q8:E===90?Z8:E===67?m8:E===50?Yk:E===49?h8:E===116?v8:E===84?P8:E===82?n8:E===110?p8:E===75?u8:E===69?e8:E===115?S4:E===51?$4:E===71?f4:E===78?k4:E===72?M4:E===99?W4:E===73?X4:E===86?w4:E===118?K4:E===87?J4:A4)(A)}function b8(A){let E=7,a,zT,mT;const kS=P.isRaw?new Array(P.statement.columns.length):{};for(let YS=0;YS<P.statement.columns.length;YS++)zT=P.statement.columns[YS],a=A.readInt32BE(E),E+=4,mT=a===-1?null:P.isRaw===!0?A.subarray(E,E+=a):zT.parser===void 0?A.toString("utf8",E,E+=a):zT.parser.array===!0?zT.parser(A.toString("utf8",E+1,E+=a)):zT.parser(A.toString("utf8",E,E+=a)),P.isRaw?kS[YS]=P.isRaw===!0?mT:O.value.from?O.value.from(mT,zT):mT:kS[zT.name]=O.value.from?O.value.from(mT,zT):mT;P.forEachFn?P.forEachFn(O.row.from?O.row.from(kS):kS,q):q[cT++]=O.row.from?O.row.from(kS):kS}function q8(A){const[E,a]=A.toString("utf8",5,A.length-1).split(r.N);if(JT[E]=a,T.parameters[E]!==a)T.parameters[E]=a,Q&&Q(E,a)}function Z8(A){if(P&&P.options.simple&&P.resolve(gS||q),P=gS=null,q=new Bf,v.cancel(),FS){if(C){if(!JT.in_hot_standby||!JT.default_transaction_read_only)return a8();else if(r8(C,JT))return cM()}if(MT)return FS===!0&&(FS=null),l8();FS!==!0&&nM(FS),T.shared.retries=iT=0,FS=null;return}while(B.length&&(P=B.shift())&&(P.active=!0,P.cancelled))F8(T).cancel(P.state,P.cancelled.resolve,P.cancelled.reject);if(P)return;WS.reserved?!WS.reserved.release&&A[5]===73?L$?cM():(WS.reserved=null,$(WS)):WS.reserved():L$?cM():$(WS)}function m8(A){cT=0;for(let E=A.length-1;E>0;E--){if(A[E]===32&&A[E+1]<58&&q.count===null)q.count=+A.toString("utf8",E+1,A.length-1);if(A[E-1]>=65){q.command=A.toString("utf8",5,E),q.state=z;break}}if(PM&&(PM(),PM=null),q.command==="BEGIN"&&F!==1&&!WS.reserved)return J$(tT.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(P.options.simple)return Yk();if(P.cursorFn)q.count&&P.cursorFn(q),TS(t$);P.resolve(q)}function h8(){P.parsing=!1}function Yk(){!q.statement&&(q.statement=P.statement),q.columns=P.statement.columns}function v8(A){const E=A.readUInt16BE(5);for(let a=0;a<E;++a)!P.statement.types[a]&&(P.statement.types[a]=A.readUInt32BE(7+a*4));P.prepare&&(yT[P.signature]=P.statement),P.describeFirst&&!P.onlyDescribe&&(TS(tJ(P)),P.describeFirst=!1)}function P8(A){if(q.command)gS=gS||[q],gS.push(q=new Bf),q.count=null,P.statement.columns=null;const E=A.readUInt16BE(5);let a=7,zT;P.statement.columns=Array(E);for(let mT=0;mT<E;++mT){zT=a;while(A[a++]!==0);const kS=A.readUInt32BE(a),YS=A.readUInt16BE(a+4),B$=A.readUInt32BE(a+6);P.statement.columns[mT]={name:O.column.from?O.column.from(A.toString("utf8",zT,a-1)):A.toString("utf8",zT,a-1),parser:K[B$],table:kS,number:YS,type:B$},a+=18}if(q.statement=P.statement,P.onlyDescribe)return P.resolve(P.statement),TS(t$)}async function n8(A,E=A.readUInt32BE(5)){(E===3?c8:E===5?g8:E===10?o8:E===11?t8:E===12?i8:E!==0?Y4:ZM)(A,E)}async function c8(){const A=await ZW();TS(r().p().str(A).z(1).end())}async function g8(A){const E="md5"+await J8(Buffer.concat([Buffer.from(await J8(await ZW()+W)),A.subarray(9)]));TS(r().p().str(E).z(1).end())}async function o8(){M$=(await PJ.randomBytes(18)).toString("base64"),r().p().str("SCRAM-SHA-256"+r.N);const A=r.i;TS(r.inc(4).str("n,,n=*,r="+M$).i32(r.i-A-4,A).end())}async function t8(A){const E=A.toString("utf8",9).split(",").reduce((YS,B$)=>(YS[B$[0]]=B$.slice(2),YS),{}),a=await PJ.pbkdf2Sync(await ZW(),Buffer.from(E.s,"base64"),parseInt(E.i),32,"sha256"),zT=await DW(a,"Client Key"),mT="n=*,r="+M$+",r="+E.r+",s="+E.s+",i="+E.i+",c=biws,r="+E.r;IT=(await DW(await DW(a,"Server Key"),mT)).toString("base64");const kS="c=biws,r="+E.r+",p="+LO(zT,Buffer.from(await DW(await VO(zT),mT))).toString("base64");TS(r().p().str(kS).end())}function i8(A){if(A.toString("utf8",9).split(r.N,1)[0].slice(2)===IT)return;J$(tT.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),G.destroy()}function ZW(){return Promise.resolve(typeof T.pass==="function"?T.pass():T.pass)}function p8(){if(q.statement=P.statement,q.statement.columns=[],P.onlyDescribe)return P.resolve(P.statement),TS(t$)}function u8(A){z.pid=A.readUInt32BE(5),z.secret=A.readUInt32BE(9)}async function l8(){MT=!1,(await new cS([`
13
+ select b.oid, b.typarray
14
+ from pg_catalog.pg_type a
15
+ left join pg_catalog.pg_type b on b.oid = a.typelem
16
+ where a.typcategory = 'A'
17
+ group by b.oid, b.typarray
18
+ order by b.oid
19
+ `],[],nM)).forEach(({oid:E,typarray:a})=>d8(E,a))}function d8(A,E){if(!!T.parsers[E]&&!!T.serializers[E])return;const a=T.parsers[A];T.shared.typeArrayMap[A]=E,T.parsers[E]=(zT)=>T8(zT,a,E),T.parsers[E].array=!0,T.serializers[E]=(zT)=>s2(zT,T.serializers[A],T,E)}function r8(A,E){return A==="read-write"&&E.default_transaction_read_only==="on"||A==="read-only"&&E.default_transaction_read_only==="off"||A==="primary"&&E.in_hot_standby==="on"||A==="standby"&&E.in_hot_standby==="off"||A==="prefer-standby"&&E.in_hot_standby==="off"&&T.host[iT]}function a8(){const A=new cS([`
20
+ show transaction_read_only;
21
+ select pg_catalog.pg_is_in_recovery()
22
+ `],[],nM,null,{simple:!0});A.resolve=([[E],[a]])=>{JT.default_transaction_read_only=E.transaction_read_only,JT.in_hot_standby=a.pg_is_in_recovery?"on":"off"},A.execute()}function e8(A){P&&(P.cursorFn||P.describeFirst)&&TS(t$);const E=tT.postgres(P1(A));P&&P.retried?J$(P.retried):P&&P.prepared&&QO.has(E.routine)?s8(P,E):J$(E)}function s8(A,E){delete yT[A.signature],A.retried=E,nM(A)}function T4(A){if(!_)return;let E=9;while(A[E++]!==0);_(A.toString("utf8",9,E-1),A.toString("utf8",E,A.length-1))}async function S4(){try{const A=await Promise.resolve(P.cursorFn(q));cT=0,A===bM?TS(G4(P.portal)):(q=new Bf,TS(Rk("",P.cursorRows)))}catch(A){TS(t$),P.reject(A)}}function $4(){q.count&&P.cursorFn(q),P.resolve(q)}function f4(){pT=new v1.Writable({autoDestroy:!0,write(A,E,a){G.write(r().d().raw(A).end(),a)},destroy(A,E){E(A),G.write(r().f().str(A+r.N).end()),pT=null},final(A){G.write(r().c().end()),PM=A}}),P.resolve(pT)}function M4(){pT=new v1.Readable({read(){G.resume()}}),P.resolve(pT)}function J4(){pT=new v1.Duplex({autoDestroy:!0,read(){G.resume()},write(A,E,a){G.write(r().d().raw(A).end(),a)},destroy(A,E){E(A),G.write(r().f().str(A+r.N).end()),pT=null},final(A){G.write(r().c().end()),PM=A}}),P.resolve(pT)}function F4(A){pT&&(pT.push(A.subarray(5))||G.pause())}function W4(){pT&&pT.push(null),pT=null}function k4(A){H?H(P1(A)):console.log(P1(A))}function X4(){}function w4(){J$(tT.notSupported("FunctionCallResponse"))}function K4(){J$(tT.notSupported("NegotiateProtocolVersion"))}function A4(A){console.error("Postgres.js : Unknown Message:",A[0])}function Y4(A,E){console.error("Postgres.js : Unknown Auth:",E)}function O4(A,E,a="",zT=""){let mT,kS;return r().B().str(zT+r.N).str(a+r.N).i16(0).i16(A.length),A.forEach((YS,B$)=>{if(YS===null)return r.i32(4294967295);kS=E[B$],A[B$]=YS=kS in T.serializers?T.serializers[kS](YS):""+YS,mT=r.i,r.inc(4).str(YS).i32(r.i-mT-4,mT)}),r.i16(0),r.end()}function Ok(A,E,a,zT=""){return r().P().str(zT+r.N).str(A+r.N).i16(E.length),E.forEach((mT,kS)=>r.i32(a[kS]||0)),r.end()}function R4(A,E=""){return r().D().str(A).str(E+r.N).end()}function Rk(A="",E=0){return Buffer.concat([r().E().str(A+r.N).i32(E).end(),M8])}function G4(A=""){return Buffer.concat([r().C().str("P").str(A+r.N).end(),r().S().end()])}function z4(){return m||r().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:W,database:w,client_encoding:"UTF8"},T.connection)).filter(([,A])=>A).map(([A,E])=>A+r.N+E).join(r.N)).z(2).end(0)}}function P1(T){const S={};let $=5;for(let f=5;f<T.length-1;f++)if(T[f]===0)S[UO[T[$]]]=T.toString("utf8",$+1,f),$=f+1;return S}function J8(T){return PJ.createHash("md5").update(T).digest("hex")}function DW(T,S){return PJ.createHmac("sha256",T).update(S).digest()}function VO(T){return PJ.createHash("sha256").update(T).digest()}function LO(T,S){const $=Math.max(T.length,S.length),f=Buffer.allocUnsafe($);for(let M=0;M<$;M++)f[M]=T[M]^S[M];return f}function n1(T,S){if(S=typeof S==="function"?S():S,!S)return{cancel:ZM,start:ZM};let $;return{cancel(){$&&(clearTimeout($),$=null)},start(){$&&clearTimeout($),$=setTimeout(f,S*1000,arguments)}};function f(M){T.apply(null,M),$=null}}var c1=F8,_O=1,t$=r().S().end(),M8=r().H().end(),EO=r().i32(8).i32(80877103).end(8),DO=Buffer.concat([r().E().str(r.N).i32(0).end(),t$]),yO=r().D().str("S").str(r.N).end(),ZM=()=>{},QO=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),UO={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 BO(T){return new Date(Date.UTC(2000,0,1)+Number(T/BigInt(1000)))}function NO(T,S,$,f,M){const J=(F,[W,k])=>(F[W.charCodeAt(0)]=k,F);Object.entries({R:(F)=>{let W=1;const k=S[F.readUInt32BE(W)]={schema:F.toString("utf8",W+=4,W=F.indexOf(0,W))||"pg_catalog",table:F.toString("utf8",W+1,W=F.indexOf(0,W+1)),columns:Array(F.readUInt16BE(W+=2)),keys:[]};W+=2;let X=0,w;while(W<F.length)w=k.columns[X++]={key:F[W++],name:M.column.from?M.column.from(F.toString("utf8",W,W=F.indexOf(0,W))):F.toString("utf8",W,W=F.indexOf(0,W)),type:F.readUInt32BE(W+=1),parser:$[F.readUInt32BE(W)],atttypmod:F.readUInt32BE(W+=4)},w.key&&k.keys.push(w),W+=4},Y:()=>{},O:()=>{},B:(F)=>{S.date=BO(F.readBigInt64BE(9)),S.lsn=F.subarray(1,9)},I:(F)=>{let W=1;const k=S[F.readUInt32BE(W)],{row:X}=yW(F,k.columns,W+=7,M);f(X,{command:"insert",relation:k})},D:(F)=>{let W=1;const k=S[F.readUInt32BE(W)];W+=4;const X=F[W]===75;f(X||F[W]===79?yW(F,k.columns,W+=3,M).row:null,{command:"delete",relation:k,key:X})},U:(F)=>{let W=1;const k=S[F.readUInt32BE(W)];W+=4;const X=F[W]===75,w=X||F[W]===79?yW(F,k.columns,W+=3,M):null;w&&(W=w.i);const{row:K}=yW(F,k.columns,W+3,M);f(K,{command:"update",relation:k,key:X,old:w&&w.row})},T:()=>{},C:()=>{}}).reduce(J,{})[T[0]](T)}function yW(T,S,$,f){let M,J,F;const W=f.raw?new Array(S.length):{};for(let k=0;k<S.length;k++)M=T[$++],J=S[k],F=M===110?null:M===117?void 0:J.parser===void 0?T.toString("utf8",$+4,$+=4+T.readUInt32BE($)):J.parser.array===!0?J.parser(T.toString("utf8",$+5,$+=4+T.readUInt32BE($))):J.parser(T.toString("utf8",$+4,$+=4+T.readUInt32BE($))),f.raw?W[k]=f.raw===!0?F:f.value.from?f.value.from(F,J):F:W[J.name]=f.value.from?f.value.from(F,J):F;return{i:$,row:f.row.from?f.row.from(W):W}}function CO(T){const S=T.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!S)throw new Error("Malformed subscribe pattern: "+T);const[,$,f,M]=S;return($||"*")+(f?":"+(f.indexOf(".")===-1?"public."+f:f):"")+(M?"="+M:"")}var W8=()=>{};function g1(T,S){const $=new Map,f="postgresjs_"+Math.random().toString(36).slice(2),M={};let J,F,W=!1;const k=K.sql=T({...S,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...S.connection,replication:"database"},onclose:async function(){if(W)return;F=null,M.pid=M.secret=void 0,O(await H(k,f,S.publications)),$.forEach((Q)=>Q.forEach(({onsubscribe:N})=>N()))},no_subscribe:!0}),X=k.end,w=k.close;return k.end=async()=>{return W=!0,F&&await new Promise((Q)=>(F.once("close",Q),F.end())),X()},k.close=async()=>{return F&&await new Promise((Q)=>(F.once("close",Q),F.end())),w()},K;async function K(Q,N,V=W8,U=W8){if(Q=CO(Q),!J)J=H(k,f,S.publications);const C={fn:N,onsubscribe:V},B=$.has(Q)?$.get(Q).add(C):$.set(Q,new Set([C])).get(Q),D=()=>{B.delete(C),B.size===0&&$.delete(Q)};return J.then((z)=>{return O(z),V(),F&&F.on("error",U),{unsubscribe:D,state:M,sql:k}})}function O(Q){F=Q.stream,M.pid=Q.state.pid,M.secret=Q.state.secret}async function H(Q,N,V){if(!V)throw new Error("Missing publication names");const U=await Q.unsafe(`CREATE_REPLICATION_SLOT ${N} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[C]=U,B=await Q.unsafe(`START_REPLICATION SLOT ${N} LOGICAL ${C.consistent_point} (proto_version '1', publication_names '${V}')`).writable(),D={lsn:Buffer.concat(C.consistent_point.split("/").map((G)=>Buffer.from(("00000000"+G).slice(-8),"hex")))};return B.on("data",y),B.on("error",z),B.on("close",Q.close),{stream:B,state:U.state};function z(G){console.error("Unexpected error during logical streaming - reconnecting",G)}function y(G){if(G[0]===119)NO(G.subarray(25),D,Q.options.parsers,j,S.transform);else if(G[0]===107&&G[17])D.lsn=G.subarray(1,9),v()}function j(G,m){const q=m.relation.schema+"."+m.relation.table;_("*",G,m),_("*:"+q,G,m),m.relation.keys.length&&_("*:"+q+"="+m.relation.keys.map((d)=>G[d.name]),G,m),_(m.command,G,m),_(m.command+":"+q,G,m),m.relation.keys.length&&_(m.command+":"+q+"="+m.relation.keys.map((d)=>G[d.name]),G,m)}function v(){const G=Buffer.alloc(34);G[0]="r".charCodeAt(0),G.fill(D.lsn,1),G.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),B.write(G)}}function _(Q,N,V){$.has(Q)&&$.get(Q).forEach(({fn:U})=>U(N,V,Q))}}import k8 from"stream";function o1(T,S,$=393216){return new Promise(async(f,M)=>{await T.begin(async(J)=>{let F;!S&&([{oid:S}]=await J`select lo_creat(-1) as oid`);const[{fd:W}]=await J`select lo_open(${S}, ${$}) as fd`,k={writable:w,readable:X,close:()=>J`select lo_close(${W})`.then(F),tell:()=>J`select lo_tell64(${W})`,read:(K)=>J`select loread(${W}, ${K}) as data`,write:(K)=>J`select lowrite(${W}, ${K})`,truncate:(K)=>J`select lo_truncate64(${W}, ${K})`,seek:(K,O=0)=>J`select lo_lseek64(${W}, ${K}, ${O})`,size:()=>J`
23
+ select
24
+ lo_lseek64(${W}, location, 0) as position,
25
+ seek.size
26
+ from (
27
+ select
28
+ lo_lseek64($1, 0, 2) as size,
29
+ tell.location
30
+ from (select lo_tell64($1) as location) tell
31
+ ) seek
32
+ `};return f(k),new Promise(async(K)=>F=K);async function X({highWaterMark:K=16384,start:O=0,end:H=1/0}={}){let _=H-O;return O&&await k.seek(O),new k8.Readable({highWaterMark:K,async read(Q){const N=Q>_?Q-_:Q;_-=Q;const[{data:V}]=await k.read(N);if(this.push(V),V.length<Q)this.push(null)}})}async function w({highWaterMark:K=16384,start:O=0}={}){return O&&await k.seek(O),new k8.Writable({highWaterMark:K,write(H,_,Q){k.write(H).then(()=>Q(),Q)}})}}).catch(M)})}function QW(T,S){const $=IO(T,S),f=$.no_subscribe||g1(QW,{...$});let M=!1;const J=qS(),F=qS(),W=qS(),k=qS(),X=qS(),w=qS(),K=qS(),O=qS(),H={connecting:F,reserved:W,closed:k,ended:X,open:w,busy:K,full:O},_=[...Array($.max)].map(()=>c1($,H,{onopen:yT,onend:JT,onclose:VS})),Q=N(j);return Object.assign(Q,{get parameters(){return $.parameters},largeObject:o1.bind(null,Q),subscribe:f,CLOSE:bM,END:bM,PostgresError:qM,options:$,reserve:C,listen:V,begin:B,close:q,end:m}),Q;function N(x){return x.debug=$.debug,Object.entries($.types).reduce((kT,[QT,cT])=>{return kT[QT]=(IT)=>new Y$(IT,cT.to),kT},i),Object.assign(XT,{types:i,typed:i,unsafe:HT,notify:U,array:y,json:z,file:iT}),XT;function i(kT,QT){return new Y$(kT,QT)}function XT(kT,...QT){return kT&&Array.isArray(kT.raw)?new cS(kT,QT,x,G):typeof kT==="string"&&!QT.length?new vJ($.transform.column.to?$.transform.column.to(kT):kT):new zW(kT,QT)}function HT(kT,QT=[],cT={}){return arguments.length===2&&!Array.isArray(QT)&&(cT=QT,QT=[]),new cS([kT],QT,x,G,{prepare:!1,...cT,simple:"simple"in cT?cT.simple:QT.length===0})}function iT(kT,QT=[],cT={}){return arguments.length===2&&!Array.isArray(QT)&&(cT=QT,QT=[]),new cS([],QT,(NT)=>{jO.readFile(kT,"utf8",(JS,UT)=>{if(JS)return NT.reject(JS);NT.strings=[UT],x(NT)})},G,{...cT,simple:"simple"in cT?cT.simple:QT.length===0})}}async function V(x,i,XT){const HT={fn:i,onlisten:XT},iT=V.sql||(V.sql=QW({...$,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(V.channels).forEach(([NT,{listeners:JS}])=>{delete V.channels[NT],Promise.all(JS.map((UT)=>V(NT,UT.fn,UT.onlisten).catch(()=>{})))})},onnotify(NT,JS){NT in V.channels&&V.channels[NT].listeners.forEach((UT)=>UT.fn(JS))}})),kT=V.channels||(V.channels={});if(x in kT){kT[x].listeners.push(HT);const NT=await kT[x].result;return HT.onlisten&&HT.onlisten(),{state:NT.state,unlisten:IT}}kT[x]={result:iT`listen ${iT.unsafe('"'+x.replace(/"/g,'""')+'"')}`,listeners:[HT]};const cT=await kT[x].result;return HT.onlisten&&HT.onlisten(),{state:cT.state,unlisten:IT};async function IT(){if(x in kT===!1)return;if(kT[x].listeners=kT[x].listeners.filter((NT)=>NT!==HT),kT[x].listeners.length)return;return delete kT[x],iT`unlisten ${iT.unsafe('"'+x.replace(/"/g,'""')+'"')}`}}async function U(x,i){return await Q`select pg_notify(${x}, ${""+i})`}async function C(){const x=qS(),i=w.length?w.shift():await new Promise((iT)=>{J.push({reserve:iT}),k.length&&MT(k.shift())});D(i,W),i.reserved=()=>x.length?i.execute(x.shift()):D(i,W),i.reserved.release=!0;const XT=N(HT);return XT.release=()=>{i.reserved=null,yT(i)},XT;function HT(iT){i.queue===O?x.push(iT):i.execute(iT)||D(i,O)}}async function B(x,i){!i&&(i=x,x="");const XT=qS();let HT=0,iT,kT=null;try{return await Q.unsafe("begin "+x.replace(/[^a-z ]/ig,""),[],{onexecute:cT}).execute(),await Promise.race([QT(iT,i),new Promise((IT,NT)=>iT.onclose=NT)])}catch(IT){throw IT}async function QT(IT,NT,JS){const UT=N(pT);UT.savepoint=L$,UT.prepare=(CT)=>kT=CT.replace(/[^a-z0-9$-_. ]/gi);let gS,FS;JS&&await UT`savepoint ${UT(JS)}`;try{if(FS=await new Promise((CT,oS)=>{const M$=NT(UT);Promise.resolve(Array.isArray(M$)?Promise.all(M$):M$).then(CT,oS)}),gS)throw gS}catch(CT){throw await(JS?UT`rollback to ${UT(JS)}`:UT`rollback`),CT instanceof qM&&CT.code==="25P02"&&gS||CT}if(!JS)kT?await UT`prepare transaction '${UT.unsafe(kT)}'`:await UT`commit`;return FS;function L$(CT,oS){if(CT&&Array.isArray(CT.raw))return L$((M$)=>M$.apply(M$,arguments));return arguments.length===1&&(oS=CT,CT=null),QT(IT,oS,"s"+HT+++(CT?"_"+CT:""))}function pT(CT){CT.catch((oS)=>gS||(gS=oS)),IT.queue===O?XT.push(CT):IT.execute(CT)||D(IT,O)}}function cT(IT){iT=IT,D(IT,W),IT.reserved=()=>XT.length?IT.execute(XT.shift()):D(IT,W)}}function D(x,i){return x.queue.remove(x),i.push(x),x.queue=i,i===w?x.idleTimer.start():x.idleTimer.cancel(),x}function z(x){return new Y$(x,3802)}function y(x,i){if(!Array.isArray(x))return y(Array.from(arguments));return new Y$(x,i||(x.length?RW(x)||25:0),$.shared.typeArrayMap)}function j(x){if(M)return x.reject(tT.connection("CONNECTION_ENDED",$,$));if(w.length)return v(w.shift(),x);if(k.length)return MT(k.shift(),x);K.length?v(K.shift(),x):J.push(x)}function v(x,i){return x.execute(i)?D(x,K):D(x,O)}function G(x){return new Promise((i,XT)=>{x.state?x.active?c1($).cancel(x.state,i,XT):x.cancelled={resolve:i,reject:XT}:(J.remove(x),x.cancelled=!0,x.reject(tT.generic("57014","canceling statement due to user request")),i())})}async function m({timeout:x=null}={}){if(M)return M;await 1;let i;return M=Promise.race([new Promise((XT)=>x!==null&&(i=setTimeout(d,x*1000,XT))),Promise.all(_.map((XT)=>XT.end()).concat(V.sql?V.sql.end({timeout:0}):[],f.sql?f.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(i))}async function q(){await Promise.all(_.map((x)=>x.end()))}async function d(x){await Promise.all(_.map((i)=>i.terminate()));while(J.length)J.shift().reject(tT.connection("CONNECTION_DESTROYED",$));x()}function MT(x,i){return D(x,F),x.connect(i),x}function JT(x){D(x,X)}function yT(x){if(J.length===0)return D(x,w);let i=Math.ceil(J.length/(F.length+1)),XT=!0;while(XT&&J.length&&i-- >0){const HT=J.shift();if(HT.reserve)return HT.reserve(x);XT=x.execute(HT)}XT?D(x,K):D(x,O)}function VS(x,i){D(x,k),x.reserved=null,x.onclose&&(x.onclose(i),x.onclose=null),$.onclose&&$.onclose(x.id),J.length&&MT(x,J.shift())}}function IO(T,S){if(T&&T.shared)return T;const $=process.env,f=(!T||typeof T==="string"?S:T)||{},{url:M,multihost:J}=hO(T),F=[...M.searchParams].reduce((O,[H,_])=>(O[H]=_,O),{}),W=f.hostname||f.host||J||M.hostname||$.PGHOST||"localhost",k=f.port||M.port||$.PGPORT||5432,X=f.user||f.username||M.username||$.PGUSERNAME||$.PGUSER||vO();f.no_prepare&&(f.prepare=!1),F.sslmode&&(F.ssl=F.sslmode,delete F.sslmode),"timeout"in f&&(console.log("The timeout option is deprecated, use idle_timeout instead"),f.idle_timeout=f.timeout),F.sslrootcert==="system"&&(F.ssl="verify-full");const w=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],K={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:ZO,max_pipeline:100,backoff:qO,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(W)?W:W.split(",").map((O)=>O.split(":")[0]),port:Array.isArray(k)?k:W.split(",").map((O)=>parseInt(O.split(":")[1]||k)),path:f.path||W.indexOf("/")>-1&&W+"/.s.PGSQL."+k,database:f.database||f.db||(M.pathname||"").slice(1)||$.PGDATABASE||X,user:X,pass:f.pass||f.password||M.password||$.PGPASSWORD||"",...Object.entries(K).reduce((O,[H,_])=>{const Q=H in f?f[H]:(H in F)?F[H]==="disable"||F[H]==="false"?!1:F[H]:$["PG"+H.toUpperCase()]||_;return O[H]=typeof Q==="string"&&w.includes(H)?+Q:Q,O},{}),connection:{application_name:"postgres.js",...f.connection,...Object.entries(F).reduce((O,[H,_])=>((H in K)||(O[H]=_),O),{})},types:f.types||{},target_session_attrs:bO(f,M,$),onnotice:f.onnotice,onnotify:f.onnotify,onclose:f.onclose,onparameter:f.onparameter,socket:f.socket,transform:mO(f.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...a2(f.types)}}function bO(T,S,$){const f=T.target_session_attrs||S.searchParams.get("target_session_attrs")||$.PGTARGETSESSIONATTRS;if(!f||["read-write","read-only","primary","standby","prefer-standby"].includes(f))return f;throw new Error("target_session_attrs "+f+" is not supported")}function qO(T){return(0.5+Math.random()/2)*Math.min(3**T/100,20)}function ZO(){return 60*(30+Math.random()*30)}function mO(T){return{undefined:T.undefined,column:{from:typeof T.column==="function"?T.column:T.column&&T.column.from,to:T.column&&T.column.to},value:{from:typeof T.value==="function"?T.value:T.value&&T.value.from,to:T.value&&T.value.to},row:{from:typeof T.row==="function"?T.row:T.row&&T.row.from,to:T.row&&T.row.to}}}function hO(T){if(!T||typeof T!=="string")return{url:{searchParams:new Map}};let S=T;S=S.slice(S.indexOf("://")+3).split(/[?/]/)[0],S=decodeURIComponent(S.slice(S.indexOf("@")+1));const $=new URL(T.replace(S,S.split(",")[0]));return{url:{username:decodeURIComponent($.username),password:decodeURIComponent($.password),host:$.host,hostname:$.hostname,port:$.port,pathname:$.pathname,searchParams:$.searchParams},multihost:S.indexOf(",")>-1&&S}}function vO(){try{return xO.userInfo().username}catch(T){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}Object.assign(QW,{PostgresError:qM,toPascal:Vf,pascal:m1,toCamel:Uf,camel:Z1,toKebab:Lf,kebab:h1,fromPascal:mJ,fromCamel:ZJ,fromKebab:hJ,BigInt:{to:20,from:[20],parse:(T)=>BigInt(T),serialize:(T)=>T.toString()}});var mM=QW;class UW extends zS{constructor(T,S,$,f){super();this.session=S,this.dialect=$,this.config={table:T,withList:f}}static[Y]="PgDelete";config;where(T){return this.config.where=T,this}returning(T=this.config.table[g.Symbol.Columns]){return this.config.returning=nS(T),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){const{typings:T,...S}=this.dialect.sqlToQuery(this.getSQL());return S}_prepare(T){return DT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0)})}prepare(T){return this._prepare(T)}execute=(T)=>{return DT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T)})};$dynamic(){return this}}class VW{constructor(T,S,$,f){this.table=T,this.session=S,this.dialect=$,this.withList=f}static[Y]="PgInsertBuilder";values(T){if(T=Array.isArray(T)?T:[T],T.length===0)throw new Error("values() must be called with at least one value");const S=T.map(($)=>{const f={},M=this.table[g.Symbol.Columns];for(let J of Object.keys($)){const F=$[J];f[J]=L(F,t)?F:new IS(F,M[J])}return f});return new X8(this.table,S,this.session,this.dialect,this.withList)}}class X8 extends zS{constructor(T,S,$,f,M){super();this.session=$,this.dialect=f,this.config={table:T,values:S,withList:M}}static[Y]="PgInsert";config;returning(T=this.config.table[g.Symbol.Columns]){return this.config.returning=nS(T),this}onConflictDoNothing(T={}){if(T.target===void 0)this.config.onConflict=R`do nothing`;else{let S="";S=Array.isArray(T.target)?T.target.map((f)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(f))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target));const $=T.where?R` where ${T.where}`:void 0;this.config.onConflict=R`(${R.raw(S)})${$} do nothing`}return this}onConflictDoUpdate(T){if(T.where&&(T.targetWhere||T.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');const S=T.where?R` where ${T.where}`:void 0,$=T.targetWhere?R` where ${T.targetWhere}`:void 0,f=T.setWhere?R` where ${T.setWhere}`:void 0,M=this.dialect.buildUpdateSet(this.config.table,SW(this.config.table,T.set));let J="";return J=Array.isArray(T.target)?T.target.map((F)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(F))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target)),this.config.onConflict=R`(${R.raw(J)})${$} do update set ${M}${S}${f}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){const{typings:T,...S}=this.dialect.sqlToQuery(this.getSQL());return S}_prepare(T){return DT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0)})}prepare(T){return this._prepare(T)}execute=(T)=>{return DT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T)})};$dynamic(){return this}}function PO(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(($)=>$.toLowerCase()).join("_")}function nO(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce(($,f,M)=>{const J=M===0?f.toLowerCase():`${f[0].toUpperCase()}${f.slice(1)}`;return $+J},"")}function cO(T){return T}class t1{static[Y]="CasingCache";cache={};cachedTables={};convert;constructor(T){this.convert=T==="snake_case"?PO:T==="camelCase"?nO:cO}getColumnCasing(T){if(!T.keyAsName)return T.name;const S=T.table[g.Symbol.Schema]??"public",$=T.table[g.Symbol.OriginalName],f=`${S}.${$}.${T.name}`;if(!this.cache[f])this.cacheTable(T.table);return this.cache[f]}cacheTable(T){const S=T[g.Symbol.Schema]??"public",$=T[g.Symbol.OriginalName],f=`${S}.${$}`;if(!this.cachedTables[f]){for(let M of Object.values(T[g.Symbol.Columns])){const J=`${f}.${M.name}`;this.cache[J]=this.convert(M.name)}this.cachedTables[f]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class nJ extends yS{static[Y]="PgViewBase"}class Nf{static[Y]="PgDialect";casing;constructor(T){this.casing=new t1(T?.casing)}async migrate(T,S,$){const f=typeof $==="string"?"__drizzle_migrations":$.migrationsTable??"__drizzle_migrations",M=typeof $==="string"?"drizzle":$.migrationsSchema??"drizzle",J=R`
33
+ CREATE TABLE IF NOT EXISTS ${R.identifier(M)}.${R.identifier(f)} (
34
+ id SERIAL PRIMARY KEY,
35
+ hash text NOT NULL,
36
+ created_at bigint
37
+ )
38
+ `;await S.execute(R`CREATE SCHEMA IF NOT EXISTS ${R.identifier(M)}`),await S.execute(J);const W=(await S.all(R`select id, hash, created_at from ${R.identifier(M)}.${R.identifier(f)} order by created_at desc limit 1`))[0];await S.transaction(async(k)=>{for await(let X of T)if(!W||Number(W.created_at)<X.folderMillis){for(let w of X.sql)await k.execute(R.raw(w));await k.execute(R`insert into ${R.identifier(M)}.${R.identifier(f)} ("hash", "created_at") values(${X.hash}, ${X.folderMillis})`)}})}escapeName(T){return`"${T}"`}escapeParam(T){return`\$${T+1}`}escapeString(T){return`'${T.replace(/'/g,"''")}'`}buildWithCTE(T){if(!T?.length)return;const S=[R`with `];for(let[$,f]of T.entries())if(S.push(R`${R.identifier(f._.alias)} as (${f._.sql})`),$<T.length-1)S.push(R`, `);return S.push(R` `),R.join(S)}buildDeleteQuery({table:T,where:S,returning:$,withList:f}){const M=this.buildWithCTE(f),J=$?R` returning ${this.buildSelection($,{isSingleTable:!0})}`:void 0,F=S?R` where ${S}`:void 0;return R`${M}delete from ${T}${F}${J}`}buildUpdateSet(T,S){const $=T[g.Symbol.Columns],f=Object.keys($).filter((J)=>S[J]!==void 0||$[J]?.onUpdateFn!==void 0),M=f.length;return R.join(f.flatMap((J,F)=>{const W=$[J],k=S[J]??R.param(W.onUpdateFn(),W),X=R`${R.identifier(this.casing.getColumnCasing(W))} = ${k}`;if(F<M-1)return[X,R.raw(", ")];return[X]}))}buildUpdateQuery({table:T,set:S,where:$,returning:f,withList:M}){const J=this.buildWithCTE(M),F=this.buildUpdateSet(T,S),W=f?R` returning ${this.buildSelection(f,{isSingleTable:!0})}`:void 0,k=$?R` where ${$}`:void 0;return R`${J}update ${T} set ${F}${k}${W}`}buildSelection(T,{isSingleTable:S=!1}={}){const $=T.length,f=T.flatMap(({field:M},J)=>{const F=[];if(L(M,t.Aliased)&&M.isSelectionField)F.push(R.identifier(M.fieldAlias));else if(L(M,t.Aliased)||L(M,t)){const W=L(M,t.Aliased)?M.sql:M;if(S)F.push(new t(W.queryChunks.map((k)=>{if(L(k,h))return R.identifier(this.casing.getColumnCasing(k));return k})));else F.push(W);if(L(M,t.Aliased))F.push(R` as ${R.identifier(M.fieldAlias)}`)}else if(L(M,BT))if(S)F.push(R.identifier(this.casing.getColumnCasing(M)));else F.push(M);if(J<$-1)F.push(R`, `);return F});return R.join(f)}buildSelectQuery({withList:T,fields:S,fieldsFlat:$,where:f,having:M,table:J,joins:F,orderBy:W,groupBy:k,limit:X,offset:w,lockingClause:K,distinct:O,setOperators:H}){const _=$??nS(S);for(let MT of _)if(L(MT.field,BT)&&PS(MT.field.table)!==(L(J,fS)?J._.alias:L(J,nJ)?J[ZT].name:L(J,t)?void 0:PS(J))&&!((JT)=>F?.some(({alias:yT})=>yT===(JT[g.Symbol.IsAlias]?PS(JT):JT[g.Symbol.BaseName])))(MT.field.table)){const JT=PS(MT.field.table);throw new Error(`Your "${MT.path.join("->")}" field references a column "${JT}"."${MT.field.name}", but the table "${JT}" is not part of the query! Did you forget to join it?`)}const Q=!F||F.length===0,N=this.buildWithCTE(T);let V;if(O)V=O===!0?R` distinct`:R` distinct on (${R.join(O.on,R`, `)})`;const U=this.buildSelection(_,{isSingleTable:Q}),C=(()=>{if(L(J,g)&&J[g.Symbol.OriginalName]!==J[g.Symbol.Name]){let MT=R`${R.identifier(J[g.Symbol.OriginalName])}`;if(J[g.Symbol.Schema])MT=R`${R.identifier(J[g.Symbol.Schema])}.${MT}`;return R`${MT} ${R.identifier(J[g.Symbol.Name])}`}return J})(),B=[];if(F)for(let[MT,JT]of F.entries()){if(MT===0)B.push(R` `);const yT=JT.table,VS=JT.lateral?R` lateral`:void 0;if(L(yT,f$)){const x=yT[f$.Symbol.Name],i=yT[f$.Symbol.Schema],XT=yT[f$.Symbol.OriginalName],HT=x===XT?void 0:JT.alias;B.push(R`${R.raw(JT.joinType)} join${VS} ${i?R`${R.identifier(i)}.`:void 0}${R.identifier(XT)}${HT&&R` ${R.identifier(HT)}`} on ${JT.on}`)}else if(L(yT,yS)){const x=yT[ZT].name,i=yT[ZT].schema,XT=yT[ZT].originalName,HT=x===XT?void 0:JT.alias;B.push(R`${R.raw(JT.joinType)} join${VS} ${i?R`${R.identifier(i)}.`:void 0}${R.identifier(XT)}${HT&&R` ${R.identifier(HT)}`} on ${JT.on}`)}else B.push(R`${R.raw(JT.joinType)} join${VS} ${yT} on ${JT.on}`);if(MT<F.length-1)B.push(R` `)}const D=R.join(B),z=f?R` where ${f}`:void 0,y=M?R` having ${M}`:void 0;let j;if(W&&W.length>0)j=R` order by ${R.join(W,R`, `)}`;let v;if(k&&k.length>0)v=R` group by ${R.join(k,R`, `)}`;const G=typeof X==="object"||typeof X==="number"&&X>=0?R` limit ${X}`:void 0,m=w?R` offset ${w}`:void 0,q=R.empty();if(K){const MT=R` for ${R.raw(K.strength)}`;if(K.config.of)MT.append(R` of ${R.join(Array.isArray(K.config.of)?K.config.of:[K.config.of],R`, `)}`);if(K.config.noWait)MT.append(R` no wait`);else if(K.config.skipLocked)MT.append(R` skip locked`);q.append(MT)}const d=R`${N}select${V} ${U} from ${C}${D}${z}${v}${y}${j}${G}${m}${q}`;if(H.length>0)return this.buildSetOperations(d,H);return d}buildSetOperations(T,S){const[$,...f]=S;if(!$)throw new Error("Cannot pass undefined values to any set operator");if(f.length===0)return this.buildSetOperationQuery({leftSelect:T,setOperator:$});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:T,setOperator:$}),f)}buildSetOperationQuery({leftSelect:T,setOperator:{type:S,isAll:$,rightSelect:f,limit:M,orderBy:J,offset:F}}){const W=R`(${T.getSQL()}) `,k=R`(${f.getSQL()})`;let X;if(J&&J.length>0){const H=[];for(let _ of J)if(L(_,h))H.push(R.identifier(_.name));else if(L(_,t)){for(let Q=0;Q<_.queryChunks.length;Q++){const N=_.queryChunks[Q];if(L(N,h))_.queryChunks[Q]=R.identifier(N.name)}H.push(R`${_}`)}else H.push(R`${_}`);X=R` order by ${R.join(H,R`, `)} `}const w=typeof M==="object"||typeof M==="number"&&M>=0?R` limit ${M}`:void 0,K=R.raw(`${S} ${$?"all ":""}`),O=F?R` offset ${F}`:void 0;return R`${W}${K}${k}${X}${w}${O}`}buildInsertQuery({table:T,values:S,onConflict:$,returning:f,withList:M}){const J=[],F=T[g.Symbol.Columns],W=Object.entries(F).filter(([H,_])=>!_.shouldDisableInsert()),k=W.map(([,H])=>R.identifier(this.casing.getColumnCasing(H)));for(let[H,_]of S.entries()){const Q=[];for(let[N,V]of W){const U=_[N];if(U===void 0||L(U,IS)&&U.value===void 0)if(V.defaultFn!==void 0){const C=V.defaultFn(),B=L(C,t)?C:R.param(C,V);Q.push(B)}else if(!V.default&&V.onUpdateFn!==void 0){const C=V.onUpdateFn(),B=L(C,t)?C:R.param(C,V);Q.push(B)}else Q.push(R`default`);else Q.push(U)}if(J.push(Q),H<S.length-1)J.push(R`, `)}const X=this.buildWithCTE(M),w=R.join(J),K=f?R` returning ${this.buildSelection(f,{isSingleTable:!0})}`:void 0,O=$?R` on conflict ${$}`:void 0;return R`${X}insert into ${T} ${k} values ${w}${O}${K}`}buildRefreshMaterializedViewQuery({view:T,concurrently:S,withNoData:$}){const f=S?R` concurrently`:void 0,M=$?R` with no data`:void 0;return R`refresh materialized view${f} ${T}${M}`}prepareTyping(T){if(L(T,FW)||L(T,JW))return"json";else if(L(T,WW))return"decimal";else if(L(T,kW))return"time";else if(L(T,XW)||L(T,wW))return"timestamp";else if(L(T,$W)||L(T,fW))return"date";else if(L(T,KW))return"uuid";else return"none"}sqlToQuery(T,S){return T.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:S})}buildRelationalQueryWithoutPK({fullSchema:T,schema:S,tableNamesMap:$,table:f,tableConfig:M,queryConfig:J,tableAlias:F,nestedQueryRelation:W,joinOn:k}){let X=[],w,K,O=[],H;const _=[];if(J===!0)X=Object.entries(M.columns).map(([V,U])=>({dbKey:U.name,tsKey:V,field:A$(U,F),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{const N=Object.fromEntries(Object.entries(M.columns).map(([z,y])=>[z,A$(y,F)]));if(J.where){const z=typeof J.where==="function"?J.where(N,v2()):J.where;H=z&&xJ(z,F)}const V=[];let U=[];if(J.columns){let z=!1;for(let[y,j]of Object.entries(J.columns)){if(j===void 0)continue;if(y in M.columns){if(!z&&j===!0)z=!0;U.push(y)}}if(U.length>0)U=z?U.filter((y)=>J.columns?.[y]===!0):Object.keys(M.columns).filter((y)=>!U.includes(y))}else U=Object.keys(M.columns);for(let z of U){const y=M.columns[z];V.push({tsKey:z,value:y})}let C=[];if(J.with)C=Object.entries(J.with).filter((z)=>!!z[1]).map(([z,y])=>({tsKey:z,queryConfig:y,relation:M.relations[z]}));let B;if(J.extras){B=typeof J.extras==="function"?J.extras(N,{sql:R}):J.extras;for(let[z,y]of Object.entries(B))V.push({tsKey:z,value:z1(y,F)})}for(let{tsKey:z,value:y}of V)X.push({dbKey:L(y,t.Aliased)?y.fieldAlias:M.columns[z].name,tsKey:z,field:L(y,BT)?A$(y,F):y,relationTableTsKey:void 0,isJson:!1,selection:[]});let D=typeof J.orderBy==="function"?J.orderBy(N,P2()):J.orderBy??[];if(!Array.isArray(D))D=[D];O=D.map((z)=>{if(L(z,BT))return A$(z,F);return xJ(z,F)}),w=J.limit,K=J.offset;for(let{tsKey:z,queryConfig:y,relation:j}of C){const v=c2(S,$,j),G=Qf(j.referencedTable),m=$[G],q=`${F}_${z}`,d=jJ(...v.fields.map((yT,VS)=>sF(A$(v.references[VS],q),A$(yT,F)))),MT=this.buildRelationalQueryWithoutPK({fullSchema:T,schema:S,tableNamesMap:$,table:T[m],tableConfig:S[m],queryConfig:L(j,o$)?y===!0?{limit:1}:{...y,limit:1}:y,tableAlias:q,joinOn:d,nestedQueryRelation:j}),JT=R`${R.identifier(q)}.${R.identifier("data")}`.as(z);_.push({on:R`true`,table:new fS(MT.sql,{},q),alias:q,joinType:"left",lateral:!0}),X.push({dbKey:z,tsKey:z,field:JT,relationTableTsKey:m,isJson:!0,selection:MT.selection})}}if(X.length===0)throw new eF({message:`No fields selected for table "${M.tsName}" ("${F}")`});let Q;if(H=jJ(k,H),W){let N=R`json_build_array(${R.join(X.map(({field:C,tsKey:B,isJson:D})=>D?R`${R.identifier(`${F}_${B}`)}.${R.identifier("data")}`:L(C,t.Aliased)?C.sql:C),R`, `)})`;if(L(W,qJ))N=R`coalesce(json_agg(${N}${O.length>0?R` order by ${R.join(O,R`, `)}`:void 0}), '[]'::json)`;const V=[{dbKey:"data",tsKey:"data",field:N.as("data"),isJson:!0,relationTableTsKey:M.tsName,selection:X}];if(w!==void 0||K!==void 0||O.length>0)Q=this.buildSelectQuery({table:aF(f,F),fields:{},fieldsFlat:[{path:[],field:R.raw("*")}],where:H,limit:w,offset:K,orderBy:O,setOperators:[]}),H=void 0,w=void 0,K=void 0,O=[];else Q=aF(f,F);Q=this.buildSelectQuery({table:L(Q,f$)?Q:new fS(Q,{},F),fields:{},fieldsFlat:V.map(({field:C})=>({path:[],field:L(C,BT)?A$(C,F):C})),joins:_,where:H,limit:w,offset:K,orderBy:O,setOperators:[]})}else Q=this.buildSelectQuery({table:aF(f,F),fields:{},fieldsFlat:X.map(({field:N})=>({path:[],field:L(N,BT)?A$(N,F):N})),joins:_,where:H,limit:w,offset:K,orderBy:O,setOperators:[]});return{tableTsKey:M.tsName,sql:Q,selection:X}}}class US{static[Y]="SelectionProxyHandler";config;constructor(T){this.config={...T}}get(T,S){if(S==="_")return{...T._,selectedFields:new Proxy(T._.selectedFields,this)};if(S===ZT)return{...T[ZT],selectedFields:new Proxy(T[ZT].selectedFields,this)};if(typeof S==="symbol")return T[S];const f=(L(T,fS)?T._.selectedFields:L(T,yS)?T[ZT].selectedFields:T)[S];if(L(f,t.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!f.isSelectionField)return f.sql;const M=f.clone();return M.isSelectionField=!0,M}if(L(f,t)){if(this.config.sqlBehavior==="sql")return f;throw new Error(`You tried to reference "${S}" 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(L(f,BT)){if(this.config.alias)return new Proxy(f,new IM(new Proxy(f.table,new CJ(this.config.alias,this.config.replaceOriginalName??!1))));return f}if(typeof f!=="object"||f===null)return f;return new Proxy(f,new US(this.config))}}class i1{static[Y]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}function hM(T,S){return($,f,...M)=>{const J=[f,...M].map((F)=>({type:T,isAll:S,rightSelect:F}));for(let F of J)if(!D1($.getSelectedFields(),F.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return $.addSetOperators(J)}}class HS{static[Y]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(T){if(this.fields=T.fields,this.session=T.session,this.dialect=T.dialect,T.withList)this.withList=T.withList;this.distinct=T.distinct}from(T){const S=!!this.fields;let $;if(this.fields)$=this.fields;else if(L(T,fS))$=Object.fromEntries(Object.keys(T._.selectedFields).map((f)=>[f,T[f]]));else if(L(T,nJ))$=T[ZT].selectedFields;else if(L(T,t))$={};else $=tK(T);return new p1({table:T,fields:$,isPartialSelect:S,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}}class w8 extends i1{static[Y]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:T,fields:S,isPartialSelect:$,session:f,dialect:M,withList:J,distinct:F}){super();this.config={withList:J,table:T,fields:{...S},distinct:F,setOperators:[]},this.isPartialSelect=$,this.session=f,this.dialect=M,this._={selectedFields:S},this.tableName=y1(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(T){return(S,$)=>{const f=this.tableName,M=y1(S);if(typeof M==="string"&&this.config.joins?.some((J)=>J.alias===M))throw new Error(`Alias "${M}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof f==="string")this.config.fields={[f]:this.config.fields};if(typeof M==="string"&&!L(S,t)){const J=L(S,fS)?S._.selectedFields:L(S,yS)?S[ZT].selectedFields:S[g.Symbol.Columns];this.config.fields[M]=J}}if(typeof $==="function")$=$(new Proxy(this.config.fields,new US({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:$,table:S,joinType:T,alias:M}),typeof M==="string")switch(T){case"left":{this.joinsNotNullableMap[M]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[M]=!0;break}case"inner":{this.joinsNotNullableMap[M]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[M]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");createSetOperator(T,S){return($)=>{const f=typeof $==="function"?$(gO()):$;if(!D1(this.getSelectedFields(),f.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:T,isAll:S,rightSelect:f}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);intersectAll=this.createSetOperator("intersect",!0);except=this.createSetOperator("except",!1);exceptAll=this.createSetOperator("except",!0);addSetOperators(T){return this.config.setOperators.push(...T),this}where(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new US({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=T,this}having(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new US({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=T,this}groupBy(...T){if(typeof T[0]==="function"){const S=T[0](new Proxy(this.config.fields,new US({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(S)?S:[S]}else this.config.groupBy=T;return this}orderBy(...T){if(typeof T[0]==="function"){const S=T[0](new Proxy(this.config.fields,new US({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),$=Array.isArray(S)?S:[S];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=$;else this.config.orderBy=$}else{const S=T;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=S;else this.config.orderBy=S}return this}limit(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=T;else this.config.limit=T;return this}offset(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=T;else this.config.offset=T;return this}for(T,S={}){return this.config.lockingClause={strength:T,config:S},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){const{typings:T,...S}=this.dialect.sqlToQuery(this.getSQL());return S}as(T){return new Proxy(new fS(this.getSQL(),this.config.fields,T),new US({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new US({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class p1 extends w8{static[Y]="PgSelect";_prepare(T){const{session:S,config:$,dialect:f,joinsNotNullableMap:M}=this;if(!S)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return DT.startActiveSpan("drizzle.prepareQuery",()=>{const J=nS($.fields),F=S.prepareQuery(f.sqlToQuery(this.getSQL()),J,T,!0);return F.joinsNotNullableMap=M,F})}prepare(T){return this._prepare(T)}execute=(T)=>{return DT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T)})}}oK(p1,[zS]);var gO=()=>({union:oO,unionAll:tO,intersect:iO,intersectAll:pO,except:uO,exceptAll:lO}),oO=hM("union",!1),tO=hM("union",!0),iO=hM("intersect",!1),pO=hM("intersect",!0),uO=hM("except",!1),lO=hM("except",!0);class u1{static[Y]="PgQueryBuilder";dialect;dialectConfig;constructor(T){this.dialect=L(T,Nf)?T:void 0,this.dialectConfig=L(T,Nf)?void 0:T}$with(T){const S=this;return{as($){if(typeof $==="function")$=$(S);return new Proxy(new NJ($.getSQL(),$.getSelectedFields(),T,!0),new US({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}with(...T){const S=this;function $(J){return new HS({fields:J??void 0,session:void 0,dialect:S.getDialect(),withList:T})}function f(J){return new HS({fields:J??void 0,session:void 0,dialect:S.getDialect(),distinct:!0})}function M(J,F){return new HS({fields:F??void 0,session:void 0,dialect:S.getDialect(),distinct:{on:J}})}return{select:$,selectDistinct:f,selectDistinctOn:M}}select(T){return new HS({fields:T??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(T){return new HS({fields:T??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(T,S){return new HS({fields:S??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:T}})}getDialect(){if(!this.dialect)this.dialect=new Nf(this.dialectConfig);return this.dialect}}class l1 extends zS{constructor(T,S,$){super();this.session=S,this.dialect=$,this.config={view:T}}static[Y]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){const{typings:T,...S}=this.dialect.sqlToQuery(this.getSQL());return S}_prepare(T){return DT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,T,!0)})}prepare(T){return this._prepare(T)}execute=(T)=>{return DT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T)})}}class LW{constructor(T,S,$,f){this.table=T,this.session=S,this.dialect=$,this.withList=f}static[Y]="PgUpdateBuilder";set(T){return new K8(this.table,SW(this.table,T),this.session,this.dialect,this.withList)}}class K8 extends zS{constructor(T,S,$,f,M){super();this.session=$,this.dialect=f,this.config={set:S,table:T,withList:M}}static[Y]="PgUpdate";config;where(T){return this.config.where=T,this}returning(T=this.config.table[g.Symbol.Columns]){return this.config.returning=nS(T),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){const{typings:T,...S}=this.dialect.sqlToQuery(this.getSQL());return S}_prepare(T){return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0)}prepare(T){return this._prepare(T)}execute=(T)=>{return this._prepare().execute(T)};$dynamic(){return this}}class cJ extends t{constructor(T){super(cJ.buildEmbeddedCount(T.source,T.filters).queryChunks);this.params=T,this.mapWith(Number),this.session=T.session,this.sql=cJ.buildCount(T.source,T.filters)}sql;static[Y]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(T,S){return R`(select count(*) from ${T}${R.raw(" where ").if(S)}${S})`}static buildCount(T,S){return R`select count(*) as count from ${T}${R.raw(" where ").if(S)}${S};`}then(T,S){return Promise.resolve(this.session.count(this.sql)).then(T,S)}catch(T){return this.then(void 0,T)}finally(T){return this.then((S)=>{return T?.(),S},(S)=>{throw T?.(),S})}}class r1{constructor(T,S,$,f,M,J,F){this.fullSchema=T,this.schema=S,this.tableNamesMap=$,this.table=f,this.tableConfig=M,this.dialect=J,this.session=F}static[Y]="PgRelationalQueryBuilder";findMany(T){return new d1(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?T:{},"many")}findFirst(T){return new d1(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?{...T,limit:1}:{limit:1},"first")}}class d1 extends zS{constructor(T,S,$,f,M,J,F,W,k){super();this.fullSchema=T,this.schema=S,this.tableNamesMap=$,this.table=f,this.tableConfig=M,this.dialect=J,this.session=F,this.config=W,this.mode=k}static[Y]="PgRelationalQuery";_prepare(T){return DT.startActiveSpan("drizzle.prepareQuery",()=>{const{query:S,builtQuery:$}=this._toSQL();return this.session.prepareQuery($,void 0,T,!0,(f,M)=>{const J=f.map((F)=>AW(this.schema,this.tableConfig,F,S.selection,M));if(this.mode==="first")return J[0];return J})})}prepare(T){return this._prepare(T)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){const T=this._getQuery(),S=this.dialect.sqlToQuery(T.sql);return{query:T,builtQuery:S}}toSQL(){return this._toSQL().builtQuery}execute(){return DT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute()})}}class a1 extends zS{constructor(T,S,$,f){super();this.execute=T,this.sql=S,this.query=$,this.mapBatchResult=f}static[Y]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(T,S){return S?this.mapBatchResult(T):T}_prepare(){return this}isResponseInArrayMode(){return!1}}class gJ{constructor(T,S,$){if(this.dialect=T,this.session=S,this._=$?{schema:$.schema,fullSchema:$.fullSchema,tableNamesMap:$.tableNamesMap,session:S}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:S},this.query={},this._.schema)for(let[f,M]of Object.entries(this._.schema))this.query[f]=new r1($.fullSchema,this._.schema,this._.tableNamesMap,$.fullSchema[f],M,T,S)}static[Y]="PgDatabase";query;$with(T){const S=this;return{as($){if(typeof $==="function")$=$(new u1(S.dialect));return new Proxy(new NJ($.getSQL(),$.getSelectedFields(),T,!0),new US({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}$count(T,S){return new cJ({source:T,filters:S,session:this.session})}with(...T){const S=this;function $(k){return new HS({fields:k??void 0,session:S.session,dialect:S.dialect,withList:T})}function f(k){return new HS({fields:k??void 0,session:S.session,dialect:S.dialect,withList:T,distinct:!0})}function M(k,X){return new HS({fields:X??void 0,session:S.session,dialect:S.dialect,withList:T,distinct:{on:k}})}function J(k){return new LW(k,S.session,S.dialect,T)}function F(k){return new VW(k,S.session,S.dialect,T)}function W(k){return new UW(k,S.session,S.dialect,T)}return{select:$,selectDistinct:f,selectDistinctOn:M,update:J,insert:F,delete:W}}select(T){return new HS({fields:T??void 0,session:this.session,dialect:this.dialect})}selectDistinct(T){return new HS({fields:T??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(T,S){return new HS({fields:S??void 0,session:this.session,dialect:this.dialect,distinct:{on:T}})}update(T){return new LW(T,this.session,this.dialect)}insert(T){return new VW(T,this.session,this.dialect)}delete(T){return new UW(T,this.session,this.dialect)}refreshMaterializedView(T){return new l1(T,this.session,this.dialect)}execute(T){const S=typeof T==="string"?R.raw(T):T.getSQL(),$=this.dialect.sqlToQuery(S),f=this.session.prepareQuery($,void 0,void 0,!1);return new a1(()=>f.execute(),S,$,(M)=>f.mapResult(M,!0))}transaction(T,S){return this.session.transaction(T,S)}}function e1(T){return new A8(!0,T)}class A8{constructor(T,S){this.unique=T,this.name=S}static[Y]="PgIndexBuilderOn";on(...T){return new BW(T.map((S)=>{if(L(S,t))return S;S=S;const $=new BJ(S.name,!!S.keyAsName,S.columnType,S.indexConfig);return S.indexConfig=JSON.parse(JSON.stringify(S.defaultConfig)),$}),this.unique,!1,this.name)}onOnly(...T){return new BW(T.map((S)=>{if(L(S,t))return S;S=S;const $=new BJ(S.name,!!S.keyAsName,S.columnType,S.indexConfig);return S.indexConfig=S.defaultConfig,$}),this.unique,!0,this.name)}using(T,...S){return new BW(S.map(($)=>{if(L($,t))return $;$=$;const f=new BJ($.name,!!$.keyAsName,$.columnType,$.indexConfig);return $.indexConfig=JSON.parse(JSON.stringify($.defaultConfig)),f}),this.unique,!0,this.name,T)}}class BW{static[Y]="PgIndexBuilder";config;constructor(T,S,$,f,M="btree"){this.config={name:f,columns:T,unique:S,only:$,method:M}}concurrently(){return this.config.concurrently=!0,this}with(T){return this.config.with=T,this}where(T){return this.config.where=T,this}build(T){return new Y8(this.config,T)}}class Y8{static[Y]="PgIndex";config;constructor(T,S){this.config={...T,table:S}}}class s1{constructor(T){this.query=T}getQuery(){return this.query}mapResult(T,S){return T}static[Y]="PgPreparedQuery";joinsNotNullableMap}class Tk{constructor(T){this.dialect=T}static[Y]="PgSession";execute(T){return DT.startActiveSpan("drizzle.operation",()=>{return DT.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1)}).execute()})}all(T){return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1).all()}async count(T){const S=await this.execute(T);return Number(S[0].count)}}class Sk extends gJ{constructor(T,S,$,f=0){super(T,S,$);this.schema=$,this.nestedIndex=f}static[Y]="PgTransaction";rollback(){throw new H1}getTransactionConfigSQL(T){const S=[];if(T.isolationLevel)S.push(`isolation level ${T.isolationLevel}`);if(T.accessMode)S.push(T.accessMode);if(typeof T.deferrable==="boolean")S.push(T.deferrable?"deferrable":"not deferrable");return R.raw(S.join(" "))}setTransaction(T){return this.session.execute(R`set transaction ${this.getTransactionConfigSQL(T)}`)}}class O8 extends s1{constructor(T,S,$,f,M,J,F){super({sql:S,params:$});this.client=T,this.queryString=S,this.params=$,this.logger=f,this.fields=M,this._isResponseInArrayMode=J,this.customResultMapper=F}static[Y]="PostgresJsPreparedQuery";async execute(T={}){return DT.startActiveSpan("drizzle.execute",async(S)=>{const $=G1(this.params,T);S?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify($)}),this.logger.logQuery(this.queryString,$);const{fields:f,queryString:M,client:J,joinsNotNullableMap:F,customResultMapper:W}=this;if(!f&&!W)return DT.startActiveSpan("drizzle.driver.execute",()=>{return J.unsafe(M,$)});const k=await DT.startActiveSpan("drizzle.driver.execute",()=>{return S?.setAttributes({"drizzle.query.text":M,"drizzle.query.params":JSON.stringify($)}),J.unsafe(M,$).values()});return DT.startActiveSpan("drizzle.mapResponse",()=>{return W?W(k):k.map((X)=>gK(f,X,F))})})}all(T={}){return DT.startActiveSpan("drizzle.execute",async(S)=>{const $=G1(this.params,T);return S?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify($)}),this.logger.logQuery(this.queryString,$),DT.startActiveSpan("drizzle.driver.execute",()=>{return S?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify($)}),this.client.unsafe(this.queryString,$)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class oJ extends Tk{constructor(T,S,$,f={}){super(S);this.client=T,this.schema=$,this.options=f,this.logger=f.logger??new E1}static[Y]="PostgresJsSession";logger;prepareQuery(T,S,$,f,M){return new O8(this.client,T.sql,T.params,this.logger,S,f,M)}query(T,S){return this.logger.logQuery(T,S),this.client.unsafe(T,S).values()}queryObjects(T,S){return this.client.unsafe(T,S)}transaction(T,S){return this.client.begin(async($)=>{const f=new oJ($,this.dialect,this.schema,this.options),M=new $k(this.dialect,f,this.schema);if(S)await M.setTransaction(S);return T(M)})}}class $k extends Sk{constructor(T,S,$,f=0){super(T,S,$,f);this.session=S}static[Y]="PostgresJsTransaction";transaction(T){return this.session.client.savepoint((S)=>{const $=new oJ(S,this.dialect,this.schema,this.session.options),f=new $k(this.dialect,$,this.schema);return T(f)})}}function vM(T,S={}){const $=(k)=>k;for(let k of["1184","1082","1083","1114"])T.options.parsers[k]=$,T.options.serializers[k]=$;T.options.serializers["114"]=$,T.options.serializers["3802"]=$;const f=new Nf({casing:S.casing});let M;if(S.logger===!0)M=new _1;else if(S.logger!==!1)M=S.logger;let J;if(S.schema){const k=n2(S.schema,g2);J={fullSchema:S.schema,schema:k.tables,tableNamesMap:k.tableNamesMap}}const F=new oJ(T,f,J,{logger:M}),W=new R8(f,F,J);return W.$client=T,W}function NW(...T){if(typeof T[0]==="function")return vM(T[0],T[1]);if(typeof T[0]==="object"){const{connection:$,client:f,...M}=T[0];if(f)return vM(f,M);if(typeof $==="object"&&$.url!==void 0){const{url:F,...W}=$,k=mM(F,W);return vM(k,M)}const J=mM($);return vM(J,M)}const S=mM(T[0]);return vM(S,T[1])}class R8 extends gJ{static[Y]="PostgresJsDatabase"}((T)=>{function S($){return vM({},$)}T.mock=S})(NW||(NW={}));function G8(T){const S=T.runtimeEnvStrict??T.runtimeEnv??process.env;if(T.emptyStringAsUndefined??!1){for(let[z,y]of Object.entries(S))if(y==="")delete S[z]}if(!!T.skipValidation)return S;const M=typeof T.client==="object"?T.client:{},J=typeof T.server==="object"?T.server:{},F=typeof T.shared==="object"?T.shared:{},W=wJ(M),k=wJ(J),X=wJ(F),w=T.isServer??(typeof window==="undefined"||("Deno"in window)),K=W.merge(X),O=k.merge(X).merge(W),H=w?O.safeParse(S):K.safeParse(S),_=T.onValidationError??((z)=>{throw console.error("\u274C Invalid environment variables:",z.flatten().fieldErrors),new Error("Invalid environment variables")}),Q=T.onInvalidAccess??((z)=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(H.success===!1)return _(H.error);const N=(z)=>{if(!T.clientPrefix)return!0;return!z.startsWith(T.clientPrefix)&&!(z in X.shape)},V=(z)=>{return w||!N(z)},U=(z)=>{return z==="__esModule"||z==="$$typeof"},C=(T.extends??[]).reduce((z,y)=>{return Object.assign(z,y)},{}),B=Object.assign(H.data,C);return new Proxy(B,{get(z,y){if(typeof y!=="string")return;if(U(y))return;if(!V(y))return Q(y);return Reflect.get(z,y)}})}var V$=G8({isServer:typeof window==="undefined",server:{POSTGRES_USER:VT.string(),POSTGRES_PASSWORD:VT.string(),POSTGRES_DATABASE:VT.string(),POSTGRES_HOST:VT.string(),POSTGRES_PORT:VT.string().transform((T)=>Number.parseInt(T,10)),BACKEND_PORT:VT.string().transform((T)=>Number.parseInt(T,10)),RUN_WORKERS_FROM_SOURCE:VT.union([VT.literal("true"),VT.literal("false")]).optional().transform((T)=>T==="true"),FRONTEND_PORT:VT.string().transform((T)=>Number.parseInt(T,10)),FRONTEND_ORIGINS:VT.string().transform((T)=>JSON.parse(T)).pipe(VT.array(VT.string())),OPENAI_API_KEY:VT.string().optional()},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:VT.string()},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var Mk={};y4(Mk,{users:()=>Cf,userChanges:()=>rO,untrackedUserColumnNames:()=>dO,twoFactorMethod:()=>E8,trackedUserColumnName:()=>_8,trackableUserColumnNames:()=>H8,role:()=>z8,players:()=>fk,passwordResetAttempts:()=>eO,loginHistory:()=>aO,games:()=>CW,banishedIps:()=>xW});var z8=lF("role",["admin","user"]),Cf=g$("users",{id:bS().primaryKey().defaultRandom(),username:MS({length:16}).notNull(),email:MS({length:254}).notNull(),hash:MS({length:64}).notNull(),salt:MS({length:36}).notNull(),createdAt:$$({withTimezone:!0}).notNull().defaultNow(),createdIp:MS({length:45}).notNull(),isActive:IJ().notNull().default(!1),verifiedAt:$$({withTimezone:!0}),userRole:z8().default("user")},(T)=>({usersUsernameUnique:e1().on(T.username),usersEmailUnique:e1().on(T.email)})),dO=["id","createdAt","createdIp","isActive","salt","verifiedAt"],H8=["username","email","hash","userRole"],_8=lF("trackedUserColumnName",H8),rO=g$("userChanges",{id:bS().primaryKey().defaultRandom(),userId:bS().notNull().references(()=>Cf.id),changedAt:$$({withTimezone:!0}).notNull().defaultNow(),changedIp:MS({length:45}).notNull(),changedColumn:_8().notNull(),oldValue:MS({length:255}),newValue:MS({length:255})}),CW=g$("games",{id:bS("id").primaryKey().defaultRandom()}),fk=g$("players",{userId:bS().notNull().references(()=>Cf.id),gameId:bS().notNull().references(()=>CW.id),score:MW().notNull()},(T)=>({pk:Z2({columns:[T.userId,T.gameId]})})),aO=g$("loginHistory",{id:bS().primaryKey().defaultRandom(),userId:bS().references(()=>Cf.id),loginTime:$$({withTimezone:!0}).notNull().defaultNow(),ipAddress:MS({length:45}).notNull(),userAgent:MS({length:1024}),successful:IJ().notNull().default(!1)}),E8=lF("twoFactorMethod",["email","phone"]),eO=g$("passwordResetAttempts",{id:bS().primaryKey().defaultRandom(),userId:bS().notNull().references(()=>Cf.id),requestedIp:MS({length:45}).notNull(),requestedAt:$$({withTimezone:!0}).notNull().defaultNow(),succeededIp:MS({length:45}),succeededAt:$$({withTimezone:!0}),verificationMethod:E8().notNull()}),xW=g$("banishedIps",{ip:MS({length:45}).primaryKey(),reason:MS({length:2048}).notNull(),banishedAt:$$({withTimezone:!0}).notNull().defaultNow(),banishedUntil:$$({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class Jk{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(sO.resolve(__dirname,"notify_update.sql"));const T=[PS(Cf),PS(CW),PS(fk)];await this.sql`SELECT create_notify_triggers(${this.sql.array(T)})`,await this.sql.listen("table_update",(S)=>{const $=S.split(","),f=$[0],M=$[1],J=`${f}("${M}")`;if(this.observers.has(J))this.observers.get(J).next(J)})}constructor(T={host:V$.POSTGRES_HOST,port:V$.POSTGRES_PORT,user:V$.POSTGRES_USER,password:V$.POSTGRES_PASSWORD,database:V$.POSTGRES_DATABASE}){this.options=T,this.sql=mM(T),this.drizzle=NW(this.sql,{schema:Mk})}observe(T,S){if(!this.observers.has(T))this.observers.set(T,new fT);this.observers.get(T).subscribe("SINGLETON",S)}}import*as jW from"fs";import*as D8 from"readline";function T7(T){const $=T.replace(":","T").replace(" ","").replace(/(\d{2})\/(\w{3})\/(\d{4})T(.+)/,(f,M,J,F,W)=>{const X={Jan:"01",Feb:"02",Mar:"03",Apr:"04",May:"05",Jun:"06",Jul:"07",Aug:"08",Sep:"09",Oct:"10",Nov:"11",Dec:"12"}[J];return`${F}-${X}-${M}T${W}`});return new Date($)}async function y8(T,S="/var/log/nginx/access.log",$=new Date){const f=new Map;if(!jW.existsSync(S))return T.error(`Log file not found: ${S}`),f;const M=jW.createReadStream(S),J=D8.createInterface({input:M,crlfDelay:Number.POSITIVE_INFINITY}),F=new Date($.getTime()-3600000);return J.on("line",(W)=>{const k=/^(?<ip>\S+) \S+ \S+ \[(?<dateTime>.*?)\]/,X=W.match(k);if(X?.groups){const w=X.groups.ip,K=X.groups.dateTime,O=T7(K);if(!Number.isNaN(O.getTime())){if(O>=F&&O<=$){let H=f.get(w);if(!H)H=[],f.set(w,H);H.push(W)}}else T.error(`Failed to parse date: ${K}`)}}),new Promise((W,k)=>{J.on("error",(X)=>{k(X)}),J.on("close",()=>{W(f)})})}function Q8(T){return S7+T.join("\n\n")}var S7=["Network security adjudicator, your job is to determine if an IP address should be banned.","The IP address in question created the following logs on our server today:","```nginx.log\n"].join("\n"),U8={schema:VT.union([VT.object({shouldBanIp:VT.literal(!1)}),VT.object({shouldBanIp:VT.literal(!0),veryConciseReason:VT.string()})]),fallback:{shouldBanIp:!1}};async function V8({generator:T,logFilePath:S,logger:$,now:f}){const M=T.usdBudget,J=new Jk,F=await y8($,S,f),W=[],k=T.from(U8);let X=0,w=0;for(let[B,D]of F){$.info(`\uD83D\uDD0D ruling on ${B}. logs:`),$.info(D.map((y)=>`\t${y}`).join("\n"));let z=!1;for(let y of W7)if(D.some((j)=>j.includes(y))){W.push({ip:B,reason:`Always ban ${y}`}),$.info(` \uD83E\uDDD1\u200D\u2696\uFE0F banning ${B}--always ban ${y}\n`),z=!0;break}if(z)continue;if(T.usdBudget>T.usdFloor){const y=Q8(D),j=await k(y);if(j.shouldBanIp)W.push({ip:B,reason:j.veryConciseReason}),$.info(` \uD83E\uDDD1\u200D\u2696\uFE0F banning ${B}--${j.veryConciseReason}\n`);else w++,$.info(` \uD83D\uDD4A\uFE0F not banning ${B}\n`);X++}else{$.warn("\uD83D\uDCB0 insufficient funds to process all logs"),$.warn(`\uD83D\uDCB0 got through ${X}/${F.size} ips\n`);break}}const K=W.length;if(W.length>0)await J.drizzle.insert(xW).values(W);const O=[],H=VT.object({lastDay:VT.string()}),_=F7(import.meta.dirname,"tribunal.cache.json");if(f7(_)){const B=await M7(_,"utf-8");try{const D=JSON.parse(B),{lastDay:z}=H.parse(D);if(z){const y=new Date(z);O.push(...await J.drizzle.query.banishedIps.findMany({columns:{ip:!0},where:TW(xW.banishedAt,y)}))}}catch(D){$.error(D)}}try{await Promise.all(O.map((B)=>new Promise((D,z)=>$7(`iptables -D INPUT -s ${B.ip} -j DROP`).on("exit",(y)=>{if(y===0)$.info(`\uD83E\uDDD1\u200D\u2696\uFE0F banned ${B.ip}`),D();else z(new Error(`iptables exited with code ${y}`))}))))}catch(B){if(B instanceof Error)$.error(B.message);else{const D=jM(B);$.error("iptables exited with error",D)}}await J7(_,JSON.stringify({lastDay:f}),"utf-8"),$.info(`\u2728 banned ${K} ips, didn't ban ${w} ips`);const N=M-T.usdBudget,V=N.toLocaleString("en",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:6}),U=M.toLocaleString("en",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:6}),C=Math.round(N/M*100);$.info(`\uD83D\uDCB8 spent ${V}, ${C}% of ${U} budget`)}var W7=[".env","php"];function IW(){xf.logger.info("\uD83D\uDEEC tribunal server exiting"),process.exit(0)}var xf=new M0;process.on("SIGINT",()=>{xf.logger.info("\u2757 received SIGINT; exiting gracefully"),IW()});process.on("SIGTERM",()=>{xf.logger.info("\u2757 received SIGTERM; exiting gracefully"),IW()});process.on("exit",()=>{xf.logger.info("\u2757 received exit; exiting gracefully"),IW()});xf.logger.info("\uD83D\uDEEB tribunal worker ready");var k7=new sw({usdBudget:0.01,usdMinimum:0,model:"gpt-4o-mini",apiKey:V$.OPENAI_API_KEY,logger:xf.logger});if(V$.OPENAI_API_KEY===void 0&&!("VITEST"in import.meta.env))throw new Error("OPENAI_API_KEY is not set and vitest is not running.");await V8({generator:k7,logFilePath:"/var/log/nginx/access.log",logger:xf.logger});IW();export{k7 as gpt4Gen};