tempest.games 0.1.46 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,37 +1,26 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var rU=Object.create;var{getPrototypeOf:aU,defineProperty:$F,getOwnPropertyNames:sU}=Object;var eU=Object.prototype.hasOwnProperty;var T_=(T,$,J)=>{J=T!=null?rU(aU(T)):{};let W=$||!T||!T.__esModule?$F(J,"default",{value:T,enumerable:!0}):J;for(let X of sU(T))if(!eU.call(W,X))$F(W,X,{get:()=>T[X],enumerable:!0});return W};var $_=(T,$)=>()=>($||T(($={exports:{}}).exports,$),$.exports);var J_=(T,$)=>{for(var J in $)$F(T,J,{get:$[J],enumerable:!0,configurable:!0,set:(W)=>$[J]=()=>W})};var Y7=import.meta.require;var a3=$_((Vp,r3)=>{var B2=Y7("os"),f2=Y7("path");function t3(T){let $=process.env.XDG_CACHE_HOME||f2.join(B2.homedir(),".cache");return f2.join($,T)}function GK(T){return f2.join(B2.homedir(),"Library","Caches",T)}function HK(T){let $=process.env.LOCALAPPDATA||f2.join(B2.homedir(),"AppData","Local");return f2.join($,T,"Cache")}var MK=function(){switch(B2.platform()){case"darwin":return GK;case"win32":return HK;case"aix":case"android":case"freebsd":case"linux":case"netbsd":case"openbsd":case"sunos":return t3;default:return console.error(`(node:${process.pid}) [cachedir] Warning: the platform "${B2.platform()}" is not currently supported by node-cachedir, falling back to "posix". Please file an issue with your platform here: https://github.com/LinusU/node-cachedir/issues/new`),t3}}();r3.exports=function T($){if(typeof $!=="string")throw new TypeError("id is not a string");if($.length===0)throw new Error("id cannot be empty");if(/[^0-9a-zA-Z-]/.test($))throw new Error("id cannot contain special characters");return MK($)}});function B8(T=Math.random){return T().toString(36).slice(2)}class OX extends Promise{fate;resolve;reject;done=!1;constructor(T){let $,J;super((W,X)=>{$=W,J=X});this.resolve=$,this.reject=J,this.use(T instanceof Promise?T:new Promise(T))}pass(T,$){if(T===this.fate)this.resolve($),this.done=!0}fail(T,$){if(T===this.fate)this.reject($),this.done=!0}use(T){if(T instanceof Promise){let $=T;this.fate=$,$.then((J)=>{this.pass($,J)},(J)=>{this.fail($,J)})}else this.resolve(T),this.fate=void 0}}var G7=(T,$,J=KT.STORE)=>{return W1(J,{key:`${T.key}:JSON`,get:({get:W})=>$.toJson(W(T)),set:({set:W},X)=>{W(T,$.fromJson(X))}})};function g(T){while(T.child!==null)T=T.child;return T}class QT{Subscriber;subscribers=new Map;subscribe(T,$){return this.subscribers.set(T,$),()=>{this.unsubscribe(T)}}unsubscribe(T){this.subscribers.delete(T)}next(T){let $=this.subscribers.values();for(let J of $)J(T)}}class JF extends QT{state;constructor(T){super();this.state=T}next(T){this.state=T,super.next(T)}}function X1(T,$,J){let W={key:$.key,type:"atom_family"},X=T.families.get($.key);if(X)T.logger.error("\u2757","atom_family",$.key,`Overwriting an existing ${cJ(X)} "${X.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let F=new QT,G=Object.assign((H)=>{let M=_T(H),z={key:$.key,subKey:M},A=`${$.key}(${M})`,w=g(T),_=$.default,D={key:A,default:_ instanceof Function?_(H):_};if($.effects)D.effects=$.effects(H);let S=XJ(w,D,z);return F.next({type:"state_creation",token:S}),S},W,{subject:F,install:(H)=>X1(H,$),internalRoles:J});return T.families.set($.key,G),T.defaults.set($.key,$.default),W}function H7(T,$){if("mutable"in $)return UX(T,$);return X1(T,$)}function F1(T,$,J){let W={key:$.key,type:"readonly_selector_family"},X=T.families.get($.key);if(X)T.logger.error("\u2757","readonly_selector_family",$.key,`Overwriting an existing ${cJ(X)} "${X.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let F=new QT,G=Object.assign((H)=>{let M=_T(H),z={key:$.key,subKey:M},A=`${$.key}(${M})`,w=g(T),_=_X(w,{key:A,get:$.get(H)},z);return F.next({type:"state_creation",token:_}),_},W,{internalRoles:J,subject:F,install:(H)=>F1(H,$),default:(H)=>{return $.get(H)({get:(...z)=>ZT(T,...z),find:(...z)=>JT(T,...z),json:(z)=>A$(T,z)})}});return T.families.set($.key,G),W}function f8(T,$){if("set"in $)return DX(T,$);return F1(T,$)}class N8{_buffer;_index=0;constructor(T){let $;if(typeof T==="number")$=T;else $=T.length;this._buffer=Array.from({length:$})}get buffer(){return this._buffer}get index(){return this._index}add(T){this._buffer[this._index]=T,this._index=(this._index+1)%this._buffer.length}copy(){let T=new N8([...this._buffer]);return T._index=this._index,T}}var W_={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function M7(T,$){let J=_T($),W=`${T.key}(${J})`,X=W_[T.type],F={key:W,type:X};return Object.assign(F,{family:{key:T.key,subKey:J}}),Object.assign(F,{counterfeit:!0}),F}function n$(T){let $={key:T.key,type:T.type};if("family"in T)$.family=T.family;return $}function e0(T){return z7(KT.STORE,T)}function H0(T){return H7(KT.STORE,T)}function WF(...T){if(T.length===2)return ZT(KT.STORE,...T);return ZT(KT.STORE,...T)}function C8(T,$,J=KT.STORE){return J.joins.set(T.key,new KX(T,$,J)),{key:T.key,type:"join",a:T.between[0],b:T.between[1],cardinality:T.cardinality}}function w7(T){return Q7(T,KT.STORE)}var XF=(T)=>($,J,W,X,...F)=>{console[T](`${$} ${J} "${W}" ${X}`,...F)},X_={error:XF("error"),info:XF("info"),warn:XF("warn")};class FF{logLevel;filter;logger;constructor(T,$,J=X_){this.logLevel=T,this.filter=$,this.logger=J}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)}}var wB=Symbol("claim");class O7{store;constructor(T=KT.STORE){this.store=T,U7("root",T)}allocate(T,$,J){return M0(this.store,T,$,J)}fuse(T,$,J){return _7(this.store,T,$,J)}deallocate(T){z0(this.store,T)}claim(T,$,J){return TW(this.store,T,$,J)}}class YF{store;realm;constructor(T=KT.STORE){this.store=T,this.realm=new O7(T)}allocate(T,$,J){M0(this.store,T,$,J)}deallocate(T){z0(this.store,T)}claim(T,$,J){TW(this.store,T,$,J)}}function q8(T){return f8(KT.STORE,T)}function N$(T){return"epoch"in T.transactionMeta}function yT(T){return"phase"in T.transactionMeta}var D7=(T)=>{let $=g(T);if(!yT($)){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",$.transactionMeta.update.key,"Aborting transaction"),$.parent.child=null};function IT(T){return T[0].toUpperCase()+T.slice(1)}function cJ(T){return T.type.split("_").map(IT).join(" ")}class A0 extends Error{constructor(T,$){super(`${cJ(T)} ${_T(T.key)} not found in store "${$.config.name}".`)}}function $W(T,$,J){return(...W)=>{let X=fT(T,$);if(X)return X.run(W,J);throw new A0($,T)}}var k8=(T)=>($)=>T instanceof Function?T($):T;var b1=(T,$)=>{if(T.valueMap.has($.key))return T.logger.info("\uD83D\uDCD6",$.type,$.key,"reading cached value"),K7($,T);switch($.type){case"selector":case"readonly_selector":return T.logger.info("\uD83E\uDDEE",$.type,$.key,"computing value"),$.get();case"atom":case"mutable_atom":{let J=$.default,W;if(J instanceof Function)W=J();else W=J;return T.logger.info("\uD83D\uDC81","atom",$.key,"could not find cached value; using default",W),W}}};var S7=(T,$)=>{if(T.operation.open){let J=performance.now();return T.logger.info("\u2757",$.type,$.key,`deferring setState at T-${J} until setState for "${T.operation.token.key}" is done`),J}T.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:$},T.logger.info("\u2B55",$.type,$.key,`operation start in store "${T.config.name}"${!yT(T)?"":` ${T.transactionMeta.phase} "${T.transactionMeta.update.key}"`}`)},V7=(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)},E7=(T,$)=>{if(!T.operation.open)return T.logger.error("\uD83D\uDC1E","unknown",$,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return T.operation.done.has($)},JW=(T,$)=>{if(!T.operation.open){T.logger.error("\uD83D\uDC1E","unknown",$,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}T.operation.done.add($)};var R7=(T,$,J)=>{switch($.type){case"mutable_atom":T.logger.info("\uD83D\uDCE2",$.type,$.key,"is now (",J.newValue,") subscribers:",$.subject.subscribers);break;case"atom":case"selector":case"readonly_selector":T.logger.info("\uD83D\uDCE2",$.type,$.key,"went (",J.oldValue,"->",J.newValue,") subscribers:",$.subject.subscribers)}$.subject.next(J)};var GF=(T,$)=>{let J=g(T),W=J.selectorAtoms.getRelatedKeys($.key);if(J.logger.info("\uD83E\uDDF9",$.type,$.key,W?`evicting ${W.size} states downstream:`:"no downstream states",W??"to evict"),W){if(J.operation.open)J.logger.info("\uD83E\uDDF9",$.type,$.key,`[ ${[...J.operation.done].join(", ")} ] already done`);for(let X of W){if(E7(J,X))continue;L7(X,J),JW(J,X)}}};var B7=(T,$,J)=>{let W=b1(T,$),X=W;if($.type==="mutable_atom"&&yT(T)){let{parent:Y}=T;X=VX(T,$,Y)}if(X=k8(J)(X),T.logger.info("\uD83D\uDCDD","atom",$.key,"set to",X),X=UJ(T,$.key,X,$.subject),N7(T,$.key))C7(T,$.key);JW(T,$.key),GF(T,$);let F={oldValue:W,newValue:X};if(!yT(T)){R7(T,$,F);return}if(T.on.transactionApplying.state===null){let{key:Y}=$;if(f7(F.newValue))return;let G={type:"atom_update",key:Y,...F};if($.family)G.family=$.family;T.transactionMeta.update.updates.push(G),T.logger.info("\uD83D\uDCC1","atom",Y,"stowed (",F.oldValue,"->",F.newValue,")")}else if($.key.startsWith("*")){let Y=$.key.slice(1),G=T.atoms.get(Y),H=T.valueMap.get(Y);if(G.type==="mutable_atom"&&yT(T)){let{parent:z}=T;H=VX(T,G,z)}if(H.do(F.newValue)===null)GF(T,G)}};var y8=(T,$,J)=>{switch($.type){case"atom":case"mutable_atom":B7(T,$,J);break;case"selector":$.set(J);break}};function Z7(T,$){if($.family){let J=T.families.get($.family.key);if(J)return J}}function W$(T,...$){let J,W,X,F;if($.length===2){if(J=$[0],F=$[1],W=Z7(T,J)??null,W)X=J.family?R$(J.family.subKey):null,J=JT(T,W,X)}else W=$[0],X=$[1],F=$[2],J=JT(T,W,X);if("counterfeit"in J&&"family"in J){let H=J.family.subKey,M=T.disposalTraces.buffer.find((z)=>z?.key===H);T.logger.error("\u274C",J.type,J.key,`could not be set because it was not found in the store "${T.config.name}".`,M?`This state was previously disposed:
4
- ${M.trace}`:"No previous disposal trace was found.");return}let Y=S7(T,J);if(Y){let H=T.on.operationClose.subscribe(`waiting to set "${J.key}" at T-${Y}`,()=>{H(),T.logger.info("\uD83D\uDFE2",J.type,J.key,`resuming deferred setState from T-${Y}`),W$(T,J,F)});return}let G=fT(T,J);y8(T,G,F),V7(T)}function I8(T,$,J){let{key:W,newValue:X,oldValue:F}=$,Y=T==="newValue"?X:F,G={key:W,type:"atom"};if($.family)Object.assign(G,{family:$.family});W$(J,G,Y)}function q7(T){let{stack:$}=T;if($)return`
5
- `+$.split(`
6
- `)?.slice(1)?.join(`
7
- `);return""}function U7(T,$=KT.STORE){let J={key:T,stringKey:_T(T),dependsOn:"any"};return $.molecules.set(_T(T),J),T}function M0(T,$,J,W="any"){let X=$,F=_T(J),Y=[],G=g(T);if(Array.isArray(X))for(let z of X){let A=_T(z);if(G.molecules.get(A))T.moleculeGraph.set(A,F,{source:A});else Y.push(A)}else{let z=_T(X);if(G.molecules.get(z))T.moleculeGraph.set(z,F,{source:z});else Y.push(z)}if(Y.length===0)G.molecules.set(F,{key:J,stringKey:F,dependsOn:W});let H={type:"molecule_creation",key:J,provenance:X};if(yT(G)&&G.transactionMeta.phase==="building")G.transactionMeta.update.updates.push(H);else G.on.moleculeCreation.next(H);for(let z of Y){let A=T.disposalTraces.buffer.find((w)=>w?.key===z);T.logger.error("\u274C","molecule",J,"allocation failed:",`Could not allocate to ${z} in store "${T.config.name}".`,A?`
8
- ${z} was most recently disposed
9
- ${A.trace}`:`No previous disposal trace for ${z} was found.`)}return J}function _7(T,$,J,W){let X=`T$--${$}==${J}++${W}`;return M0(T,[J,W],X,"all"),X}function z0(T,$){let J=_T($),W=T.molecules.get(J);if(!W){let _=T.disposalTraces.buffer.find((D)=>D?.key===J);T.logger.error("\u274C","molecule",$,"deallocation failed:",`Could not find allocation for ${J} in store "${T.config.name}".`,_?`
10
- This state was most recently deallocated
11
- ${_.trace}`:`No previous disposal trace for ${J} was found.`);return}let X=T.moleculeJoins.getRelatedKeys(W.key);if(X)for(let _ of X){let D=T.joins.get(_);if(D)D.relations.delete(W.key),D.molecules.delete(W.stringKey)}T.moleculeJoins.delete(W.stringKey);let F=[],Y=[],G={type:"molecule_disposal",key:W.key,values:Y,provenance:F},H=g(T);H.molecules.delete(J);let M=yT(H)&&H.transactionMeta.phase==="building";if(M)H.transactionMeta.update.updates.push(G);let z=T.moleculeGraph.getRelationEntries({downstreamMoleculeKey:W.stringKey});if(z)for(let[_,{source:D}]of z)if(D===W.stringKey){let S=R$(_);z0(T,S)}else F.push(D);let A=H.moleculeData.getRelatedKeys(W.stringKey);if(A)for(let _ of A){let D=H.families.get(_),S=JT(T,D,W.key);Y.push([D.key,S]),w0(T,S)}if(H.moleculeGraph.delete(W.stringKey),H.moleculeJoins.delete(W.stringKey),H.moleculeData.delete(W.stringKey),!M)H.on.moleculeDisposal.next(G);H.molecules.delete(W.stringKey);let w=q7(new Error);T.disposalTraces.add({key:J,trace:w})}function TW(T,$,J,W){let X=_T(J),F=g(T),Y=F.molecules.get(X);if(!Y){let w=T.disposalTraces.buffer.find((_)=>_?.key===X);return T.logger.error("\u274C","molecule",J,"claim failed:",`Could not allocate to ${X} in store "${T.config.name}".`,w?`
12
- ${X} was most recently disposed
13
- ${w.trace}`:`No previous disposal trace for ${X} was found.`),J}let G=_T($),H=F.molecules.get(G);if(!H){let w=T.disposalTraces.buffer.find((_)=>_?.key===G);return T.logger.error("\u274C","molecule",J,"claim failed:",`Could not allocate to ${G} in store "${T.config.name}".`,w?`
14
- ${G} was most recently disposed
15
- ${w.trace}`:`No previous disposal trace for ${G} was found.`),J}let M=T.moleculeGraph.getRelationEntries({downstreamMoleculeKey:Y.stringKey}).filter(([,{source:w}])=>w!==X).map(([w])=>R$(w));if(W)F.moleculeGraph.delete(X);F.moleculeGraph.set({upstreamMoleculeKey:H.stringKey,downstreamMoleculeKey:Y.stringKey},{source:H.stringKey});let z={type:"molecule_transfer",key:Y.key,from:M,to:[H.key]};if(yT(F)&&F.transactionMeta.phase==="building")F.transactionMeta.update.updates.push(z);return J}function HF(T,$,J){switch($){case"newValue":{k7(T,J);break}case"oldValue":{w0(J,T.token);break}}}function MF(T,$,J){switch($){case"newValue":{w0(J,T.token);break}case"oldValue":{if(k7(T,J),T.subType==="atom")J.valueMap.set(T.token.key,T.value);break}}}function k7(T,$){let{family:J}=T.token;if(J){let W=$.families.get(J.key);if(W)JT($,W,R$(J.subKey))}}function y7(T,$,J){switch($){case"newValue":M0(J,T.provenance,T.key);break;case"oldValue":z0(J,T.key);break}}function I7(T,$,J){switch($){case"newValue":z0(J,T.key);break;case"oldValue":{let W=T.provenance.map(R$);M0(J,W,T.key);for(let[X,F]of T.values){let Y=J.families.get(X);if(Y){JT(J,Y,T.key);let G=`${X}(${_T(T.key)})`;J.valueMap.set(G,F)}}}break}}function j7(T,$,J){switch($){case"newValue":{let W=T.to.length===1?T.to[0]:T.to;TW(J,W,T.key,"exclusive")}break;case"oldValue":{let W=T.from.length===1?T.from[0]:T.from;TW(J,W,T.key,"exclusive")}break}}function j8(T,$,J){let W=T==="newValue"?$.updates:[...$.updates].reverse();for(let X of W)switch(X.type){case"atom_update":case"selector_update":I8(T,X,J);break;case"state_creation":HF(X,T,J);break;case"state_disposal":MF(X,T,J);break;case"molecule_creation":y7(X,T,J);break;case"molecule_disposal":I7(X,T,J);break;case"molecule_transfer":j7(X,T,J);break;case"transaction_update":j8(T,X,J);break}}function zF(T,$){return T.transactionMeta.actionContinuities.getRelatedKey($)}function F_(T,$){return T.transactionMeta.epoch.get($)}function x7(T,$){if(!N$(T))return;let W=zF(T,$);if(W===void 0)return;return F_(T,W)}function P7(T,$,J){if(N$(T)&&$)T.transactionMeta.epoch.set($,J)}function b7(T,$,J){if(!N$(T))return;let X=zF(T,$);if(X!==void 0)T.transactionMeta.epoch.set(X,J)}var v7=(T,$)=>{let J=g($),{parent:W}=J;if(W===null||!yT(J)||J.transactionMeta?.phase!=="building"){$.logger.warn("\uD83D\uDC1E","transaction","???","applyTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}J.transactionMeta.phase="applying",J.transactionMeta.update.output=T,W.child=null,W.on.transactionApplying.next(J.transactionMeta);let{updates:X}=J.transactionMeta.update;if($.logger.info("\uD83D\uDEC4","transaction",J.transactionMeta.update.key,`Applying transaction with ${X.length} updates:`,X),j8("newValue",J.transactionMeta.update,W),N$(W))b7(W,J.transactionMeta.update.key,J.transactionMeta.update.epoch),fT($,{key:J.transactionMeta.update.key,type:"transaction"})?.subject.next(J.transactionMeta.update),$.logger.info("\uD83D\uDEEC","transaction",J.transactionMeta.update.key,"Finished applying transaction.");else if(yT(W))W.transactionMeta.update.updates.push(J.transactionMeta.update);W.on.transactionApplying.next(null)};function h7(T,$,J){if(!N$(T))return;let{epoch:X,actionContinuities:F}=T.transactionMeta;if(F.set($,J),!X.has($))X.set($,-1)}function m7(T){return{store:T}}function ZT(T,...$){let J,W,X;if($.length===1)J=$[0];else W=$[0],X=$[1],J=JT(T,W,X);if("counterfeit"in J&&"family"in J){W=T.families.get(J.family.key);let F=J.family.subKey,Y=T.disposalTraces.buffer.find((G)=>G?.key===F);switch(T.logger.error("\u274C",J.type,J.key,`could not be retrieved because it was not found in the store "${T.config.name}".`,Y?`This state was previously disposed:
16
- ${Y.trace}`:"No previous disposal trace was found."),W.type){case"atom_family":case"mutable_atom_family":return T.defaults.get(W.key);case"selector_family":case"readonly_selector_family":{if(T.defaults.has(W.key))return T.defaults.get(J.family.key);let G=fT(T,W).default(F);return T.defaults.set(W.key,G),G}}}return b1(T,fT(T,J))}class w${a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(T,$)=>`${T}:${$}`;warn;getRelatedKeys(T){return this.relations.get(T)}addRelation(T,$){let J=this.relations.get(T),W=this.relations.get($);if(J)J.add($);else J=new Set([$]),this.relations.set(T,J);if(W)W.add(T);else W=new Set([T]),this.relations.set($,W)}deleteRelation(T,$){let J=this.relations.get(T);if(J){if(J.delete($),J.size===0)this.relations.delete(T);let W=this.relations.get($);if(W){if(W.delete(T),W.size===0)this.relations.delete($)}}}replaceRelationsUnsafely(T,$){this.relations.set(T,new Set($));for(let J of $){let W=new Set().add(T);this.relations.set(J,W)}}replaceRelationsSafely(T,$){let J=this.relations.get(T),W=this.isAType?.(T)?T:void 0,X=W===void 0?T:void 0;if(J)for(let F of J){W??=F,X??=F;let Y=this.relations.get(F);if(Y){if(Y.size===1)this.relations.delete(F);else Y.delete(T);this.contents.delete(this.makeContentKey(W,X))}}this.relations.set(T,new Set($));for(let F of $){let Y=this.relations.get(F);if(Y)Y.add(T);else Y=new Set().add(T),this.relations.set(F,Y)}}getContentInternal(T){return this.contents.get(T)}setContent(T,$){this.contents.set(T,$)}deleteContent(T){this.contents.delete(T)}constructor(T,$){if(this.a=T.between[0],this.b=T.between[1],this.cardinality=T.cardinality,!$?.externalStore)this.relations=new Map(T.relations?.map(([J,W])=>[J,new Set(W)])),this.contents=new Map(T.contents);if(this.isAType=$?.isAType??null,this.isBType=$?.isBType??null,this.isContent=$?.isContent??null,$?.makeContentKey)this.makeContentKey=$.makeContentKey;if($?.externalStore){let J=$.externalStore;if(this.has=(W,X)=>J.has(W,X),this.addRelation=(W,X)=>{J.addRelation(W,X)},this.deleteRelation=(W,X)=>{J.deleteRelation(W,X)},this.replaceRelationsSafely=(W,X)=>{J.replaceRelationsSafely(W,X)},this.replaceRelationsUnsafely=(W,X)=>{J.replaceRelationsUnsafely(W,X)},this.getRelatedKeys=(W)=>J.getRelatedKeys(W),J.getContent)this.getContentInternal=(W)=>{return J.getContent(W)},this.setContent=(W,X)=>{J.setContent(W,X)},this.deleteContent=(W)=>{J.deleteContent(W)};for(let[W,X]of T.relations??[]){let F=this.isAType?.(W)?W:void 0,Y=F===void 0?W:void 0;for(let G of X)F??=G,Y??=G,this.addRelation(F,Y)}for(let[W,X]of T.contents??[])this.setContent(W,X)}if($?.warn)this.warn=$.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([T,$])=>[T,[...$]]),contents:[...this.contents.entries()]}}set(...T){let $,J,W;switch(T.length){case 1:{let X=T[0];$=X[this.a],J=X[this.b],W=void 0;break}case 2:{let X=T[0];if(typeof X==="string")[$,J]=T;else $=X[this.a],J=X[this.b],W=T[1];break}default:{$=T[0],J=T[1],W=T[2];break}}switch(this.cardinality){case"1:1":{let X=this.getRelatedKey($);if(X&&X!==J)this.delete($,X)}case"1:n":{let X=this.getRelatedKey(J);if(X&&X!==$)this.delete(X,J)}break;case"n:n":}if(W){let X=this.makeContentKey($,J);this.setContent(X,W)}return this.addRelation($,J),this}delete(T,$){$=typeof $==="string"?$:T[this.b];let J=typeof T==="string"?T:T[this.a];if(J===void 0&&typeof $==="string"){let W=this.getRelatedKeys($);if(W)for(let X of W)this.delete(X,$)}if(typeof J==="string"&&$===void 0){let W=this.getRelatedKeys(J);if(W)for(let X of W)this.delete(J,X)}if(typeof J==="string"&&typeof $==="string"){this.deleteRelation(J,$);let W=this.makeContentKey(J,$);this.deleteContent(W)}return this}getRelatedKey(T){let $=this.getRelatedKeys(T);if($){if($.size>1)this.warn?.(`${$.size} related keys were found for key "${T}": (${[...$].map((W)=>`"${W}"`).join(", ")}). Only one related key was expected.`);let J;for(let W of $){J=W;break}return J}}replaceRelations(T,$,J){let W=!Array.isArray($),X=W?Object.keys($):$;if(J?.reckless)this.replaceRelationsUnsafely(T,X);else this.replaceRelationsSafely(T,X);if(W)for(let F of X){let Y=this.makeContentKey(T,F),G=$[F];this.setContent(Y,G)}return this}getContent(T,$){let J=this.makeContentKey(T,$);return this.getContentInternal(J)}getRelationEntries(T){let $=T[this.a],J=T[this.b];if($!==void 0&&J===void 0){let W=this.getRelatedKeys($);if(W)return[...W].map((X)=>{return[X,this.getContent($,X)]})}if($===void 0&&J!==void 0){let W=this.getRelatedKeys(J);if(W)return[...W].map((X)=>{return[X,this.getContent(X,J)]})}return[]}has(T,$){if($)return this.getRelatedKeys(T)?.has($)??!1;return this.relations.has(T)}}class _J extends Map{deleted=new Set;source;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,$){return this.deleted.delete(T),super.set(T,$)}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 g7=(T,$,J,W)=>{let X=g(T),F={parent:X,child:null,on:X.on,loggers:X.loggers,logger:X.logger,config:X.config,atoms:new _J(X.atoms),atomsThatAreDefault:new Set(X.atomsThatAreDefault),families:new _J(X.families),joins:new _J(X.joins),operation:{open:!1},readonlySelectors:new _J(X.readonlySelectors),timelines:new _J(X.timelines),timelineTopics:new w$(X.timelineTopics.toJSON()),trackers:new Map,transactions:new _J(X.transactions),selectorAtoms:new w$(X.selectorAtoms.toJSON()),selectorGraph:new w$(X.selectorGraph.toJSON(),{makeContentKey:(...M)=>M.sort().join(":")}),selectors:new _J(X.selectors),valueMap:new _J(X.valueMap),defaults:X.defaults,disposalTraces:T.disposalTraces.copy(),molecules:new _J(X.molecules),moleculeGraph:new w$(X.moleculeGraph.toJSON(),{makeContentKey:X.moleculeGraph.makeContentKey}),moleculeData:new w$(X.moleculeData.toJSON(),{makeContentKey:X.moleculeData.makeContentKey}),moleculeJoins:new w$(X.moleculeJoins.toJSON(),{makeContentKey:X.moleculeJoins.makeContentKey}),miscResources:new _J(X.miscResources)},Y=x7(T,$),G={phase:"building",update:{type:"transaction_update",key:$,id:W,epoch:Y===void 0?Number.NaN:Y+1,updates:[],params:J,output:void 0},toolkit:{get:(...M)=>ZT(H,...M),set:(...M)=>{W$(H,...M)},run:(M,z=B8())=>$W(H,M,z),find:(...M)=>JT(T,...M),json:(M)=>A$(H,M),dispose:(...M)=>{w0(H,...M)},env:()=>m7(H)}},H=Object.assign(F,{transactionMeta:G});return X.child=H,T.logger.info("\uD83D\uDEEB","transaction",$,"Building transaction with params:",J),H};function AF(T,$){let J={key:$.key,type:"transaction",run:(F,Y)=>{let G=g7(T,$.key,F,Y);try{let H=g(T),{toolkit:M}=G.transactionMeta,z=$.do(M,...F);return v7(z,H),z}catch(H){throw D7(W),T.logger.warn("\uD83D\uDCA5","transaction",$.key,"caught:",H),H}},install:(F)=>AF(F,$),subject:new QT},W=g(T);W.transactions.set(J.key,J);let X=n$(J);return T.on.transactionCreation.next(X),X}function EX(T){return AF(KT.STORE,T)}class p7{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;selectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new w$({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new w$({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});trackers=new Map;families=new Map;joins=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new w$({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new w$({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new N8(100);molecules=new Map;moleculeJoins=new w$({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});moleculeGraph=new w$({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});moleculeData=new w$({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});miscResources=new Map;on={atomCreation:new QT,atomDisposal:new QT,selectorCreation:new QT,selectorDisposal:new QT,timelineCreation:new QT,transactionCreation:new QT,transactionApplying:new JF(null),operationClose:new QT,moleculeCreation:new QT,moleculeDisposal:new QT};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new FF("warn",(T,$,J)=>!v1(J))];logger={error:(...T)=>{for(let $ of this.loggers)$.error(...T)},info:(...T)=>{for(let $ of this.loggers)$.info(...T)},warn:(...T)=>{for(let $ of this.loggers)$.warn(...T)}};constructor(T,$=null){if(this.config={...$?.config,...T},$!==null){if(this.valueMap=new Map($?.valueMap),this.operation={...$?.operation},N$($))this.transactionMeta={epoch:new Map($?.transactionMeta.epoch),actionContinuities:new w$($?.transactionMeta.actionContinuities.toJSON())};for(let[,W]of $.families){if(W.internalRoles?.includes("mutable")||W.internalRoles?.includes("join"))continue;W.install(this)}let J=new Set;for(let[,W]of $.atoms){if(J.has(W.key))continue;if(W.install(this),W.type==="mutable_atom"){let X=A$($,W),F=Y1(W);J.add(X.key),J.add(F.key)}}for(let[,W]of $.readonlySelectors)W.install(this);for(let[,W]of $.selectors){if(J.has(W.key))continue;W.install(this)}for(let[,W]of $.transactions)W.install(this);for(let[,W]of $.timelines)W.install(this)}}}var KT={get STORE(){return globalThis.ATOM_IO_IMPLICIT_STORE??=new p7({name:"IMPLICIT_STORE",lifespan:"ephemeral"}),globalThis.ATOM_IO_IMPLICIT_STORE}};function fT(T,$){let J,W=T;while(W!==null){switch($.type){case"atom":case"mutable_atom":J=W.atoms.get($.key);break;case"selector":J=W.selectors.get($.key);break;case"readonly_selector":J=W.readonlySelectors.get($.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":J=W.families.get($.key);break;case"timeline":J=W.timelines.get($.key);break;case"transaction":J=W.transactions.get($.key);break}if(J)return J;W=W.child}throw new A0($,T)}function u7(T,$,J){let W=T.families.get($.key);if(W===void 0)throw new A0($,T);let X=W(J),F=g(T);if(X.family){if(N$(F))switch(X.type){case"atom":case"mutable_atom":T.on.atomCreation.next(X);break;case"selector":case"readonly_selector":T.on.selectorCreation.next(X);break}else if(yT(F)&&F.on.transactionApplying.state===null)F.transactionMeta.update.updates.push({type:"state_creation",token:X})}return X}function c7(T,$,J){let W=_T(J),X=`${$.key}(${W})`,F=g(T),Y;switch($.type){case"atom_family":case"mutable_atom_family":Y=F.atoms.get(X);break;case"selector_family":Y=F.selectors.get(X);break;case"readonly_selector_family":Y=F.readonlySelectors.get(X);break}if(Y)return n$(Y);return Y}function JT(T,$,J){let W=c7(T,$,J);if(W)return W;let X=_T(J),F=T.molecules.get(X);if(!F&&T.config.lifespan==="immortal"){let Y=M7($,J);return T.logger.error("\u274C",Y.type,Y.key,`was not found in store "${T.config.name}"; returned a counterfeit token.`),Y}if(W=u7(T,$,J),F)g(T).moleculeData.set(X,$.key);return W}function w0(T,...$){let J;if($.length===1)J=$[0];else{let W=$[0],X=$[1];J=JT(T,W,X)}try{fT(T,J)}catch(W){T.logger.error("\u274C",J.type,J.key,`could not be disposed because it was not found in the store "${T.config.name}".`);return}switch(J.type){case"atom":case"mutable_atom":wF(T,J);break;case"selector":case"readonly_selector":o7(T,J);break}}var x8=(T,$)=>g(T).atoms.has($),Y_=(T,$)=>g(T).selectors.has($),G_=(T,$)=>g(T).readonlySelectors.has($),d7=(T,$)=>x8(T,$)||Y_(T,$)||G_(T,$);var P8=(T,$)=>{return g($).selectorGraph.getRelationEntries({downstreamSelectorKey:T}).filter(([W,{source:X}])=>X!==T).map(([W,{source:X}])=>X).filter((W)=>d7($,W))};var QF=(T,$,J)=>{let W=[],X=P8(T,J);while(X.length>0){let F=X.shift();if($.has(F))continue;if($.add(F),!x8(J,F))X.push(...P8(F,J));else if(!W.includes(F))W.push(F)}return W},l7=(T,$)=>{let J=T.key,W=P8(J,$),X=new Set;return W.flatMap((F)=>x8($,F)?F:QF(F,X,$))};var n7=(T,$,J,W)=>{let X=g(W);if($.type==="atom"||$.type==="mutable_atom")X.selectorAtoms.set({selectorKey:T,atomKey:$.key}),W.logger.info("\uD83D\uDD0D","selector",T,`discovers root atom "${$.key}"`);else{let F=QF($.key,J,W);W.logger.info("\uD83D\uDD0D","selector",T,`discovers root atoms: [ ${F.map((Y)=>`"${Y}"`).join(", ")} ]`);for(let Y of F)X.selectorAtoms=X.selectorAtoms.set({selectorKey:T,atomKey:Y})}J.add($.key)};var b8=(T,$,J)=>({get:(...W)=>{let X=g(J),F;if(W.length===2){let[H,M]=W;F=JT(J,H,M)}else[F]=W;let Y=fT(J,F),G=b1(J,Y);return J.logger.info("\uD83D\uDD0C","selector",T,`registers dependency ( "${F.key}" =`,G,")"),X.selectorGraph.set({upstreamSelectorKey:F.key,downstreamSelectorKey:T},{source:F.key}),n7(T,F,$,J),G},set:(...W)=>{let X,F;if(W.length===2)X=W[0],F=W[1];else{let H=W[0],M=W[1];F=W[2],X=JT(J,H,M)}let Y=g(J),G=fT(Y,X);y8(Y,G,F)},find:(...W)=>JT(J,...W),json:(W)=>A$(J,W)});var _X=(T,$,J)=>{let W=g(T),X=new QT,F=new Set,{get:Y,find:G,json:H}=b8($.key,F,W),M=()=>{let _=$.get({get:Y,find:G,json:H});return UJ(g(T),$.key,_,X),F.clear(),_},z={...$,subject:X,install:(_)=>_X(_,$,J),get:M,type:"readonly_selector",...J&&{family:J}};W.readonlySelectors.set($.key,z);let A=M();T.logger.info("\u2728",z.type,z.key,"=",A);let w={key:$.key,type:"readonly_selector"};if(J)w.family=J;return w};var RX=(T,$,J)=>{let W=g(T),X=new QT,F=new Set,Y=b8($.key,F,W),{find:G,get:H,json:M}=Y,z={find:G,get:H,json:M},A=(Z=$.get,q=g(T))=>{let N=Z(z);return UJ(q,$.key,N,X),F.clear(),N},_={...$,subject:X,install:(Z)=>RX(Z,$,J),get:A,set:(Z)=>{let q=g(T),N=A($.get,q),y=k8(Z)(N);if(T.logger.info("\uD83D\uDCDD","selector",$.key,"set (",N,"->",y,")"),UJ(q,$.key,y,X),JW(q,$.key),N$(q))X.next({newValue:y,oldValue:N});$.set(Y,y)},type:"selector",...J&&{family:J}};W.selectors.set($.key,_);let D=A();T.logger.info("\u2728",_.type,_.key,"=",D);let S={key:$.key,type:"selector"};if(J)S.family=J;return S};function W1(T,$){if("set"in $){let X=RX(T,$,void 0);return T.on.selectorCreation.next(X),X}let W=_X(T,$,void 0);return T.on.selectorCreation.next(W),W}function o7(T,$){let J=g(T),{key:W}=$,X=fT(J,$);if(!X.family)T.logger.error("\u274C","selector",W,"Standalone selectors cannot be disposed.");else{if(J.molecules.get(X.family.subKey))J.moleculeData.delete(X.family.subKey,X.family.key);let Y;switch($.type){case"selector":J.selectors.delete(W),Y={key:X.family.key,type:"selector_family"},fT(T,Y).subject.next({type:"state_disposal",subType:"selector",token:$});break;case"readonly_selector":J.readonlySelectors.delete(W),Y={key:X.family.key,type:"readonly_selector_family"},fT(T,Y).subject.next({type:"state_disposal",subType:"selector",token:$});break}if(J.valueMap.delete(W),J.selectorAtoms.delete(W),J.selectorGraph.delete(W),T.logger.info("\uD83D\uDD25",$.type,W,"deleted"),yT(J)&&J.transactionMeta.phase==="building")J.transactionMeta.update.updates.push({type:"state_disposal",subType:"selector",token:$});else T.on.selectorDisposal.next($)}}function DX(T,$,J){let W={key:$.key,type:"selector_family"},X=T.families.get($.key);if(X)T.logger.error("\u2757","selector_family",$.key,`Overwriting an existing ${cJ(X)} "${X.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let F=new QT,G=Object.assign((H)=>{let M=_T(H),z={key:$.key,subKey:M},A=`${$.key}(${M})`,w=g(T),_=RX(w,{key:A,get:$.get(H),set:$.set(H)},z);return F.next({type:"state_creation",token:_}),_},W,{internalRoles:J,subject:F,install:(H)=>DX(H,$),default:(H)=>{return $.get(H)({get:(...z)=>ZT(T,...z),find:(...z)=>JT(T,...z),json:(z)=>A$(T,z)})}});return T.families.set($.key,G),W}function i7(T,$,J){return DX(T,{key:`${$.key}:JSON`,get:(X)=>({get:F})=>{let Y=F($,X);return J.toJson(Y)},set:(X)=>({set:F},Y)=>{F($,X,J.fromJson(Y))}},["mutable","json"])}var R$=(T)=>JSON.parse(T),_T=(T)=>JSON.stringify(T),fZ=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var t7=(T,$)=>{let J=g(T);if(J.operation.open)return J.operation.prev.get($.key);return J.valueMap.get($.key)};var _F=(T,$)=>{let J=g(T);return l7($,T).map((X)=>{let F=J.atoms.get(X);if(F===void 0)throw new Error(`Atom "${X}", a dependency of selector "${$.key}", not found in store "${T.config.name}".`);return F.subject.subscribe(`${$.type}:${$.key}`,(Y)=>{T.logger.info("\uD83D\uDCE2",$.type,$.key,"root",X,"went",Y.oldValue,"->",Y.newValue);let G=t7(J,$),H=b1(J,$);T.logger.info("\u2728",$.type,$.key,"went",G,"->",H),$.subject.next({newValue:H,oldValue:G})})})};function j$(T,$,J,W){function X(A){if(T.operation.open){let w=T.on.operationClose.subscribe(`state subscription ${J}`,()=>{w(),W(A)})}else W(A)}let F=fT(T,$);T.logger.info("\uD83D\uDC40",F.type,F.key,`Adding subscription "${J}"`);let Y=F.type==="selector"||F.type==="readonly_selector",G=null,H=X;if(Y)G=_F(T,F),H=(A)=>{if(G)G.length=0,G.push(..._F(T,F));X(A)};let M=F.subject.subscribe(J,H);return()=>{if(T.logger.info("\uD83D\uDE48",F.type,F.key,`Removing subscription "${J}"`),M(),G)for(let A of G)A()}}var OF=(T,$,J,W)=>{let X=fT(T,$);T.logger.info("\uD83D\uDC40","timeline",$.key,`Adding subscription "${J}"`);let F=X.subject.subscribe(J,W);return()=>{T.logger.info("\uD83D\uDE48","timeline",$.key,`Removing subscription "${J}" from timeline`),F()}};var UF=(T,$,J,W)=>{let X=fT(T,$);T.logger.info("\uD83D\uDC40","transaction",$.key,`Adding subscription "${J}"`);let F=X.subject.subscribe(J,W);return()=>{T.logger.info("\uD83D\uDE48","transaction",$.key,`Removing subscription "${J}"`),F()}};class Q0{Update;initializeState(T,$){let J=`*${T.key}`;$.atoms.delete(J),$.valueMap.delete(J);let W=T.family?{key:`*${T.family.key}`,subKey:T.family.subKey}:void 0,X=XJ($,{key:J,default:null},W);if($.parent?.valueMap.has(J)){let F=$.parent.valueMap.get(J);$.valueMap.set(J,F)}return X}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(T,$,J){let W=`tracker:${J.config.name}:${yT(J)?J.transactionMeta.update.key:"main"}:${T.key}`,X=ZT(J,T);this.unsubscribeFromInnerValue=X.subscribe(W,(F)=>{W$(J,$,F)}),this.unsubscribeFromState=j$(J,T,W,(F)=>{if(F.newValue!==F.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=F.newValue.subscribe(W,(Y)=>{W$(J,$,Y)})})}updateCore(T,$,J){let W=`tracker:${J.config.name}:${yT(J)?J.transactionMeta.update.key:"main"}:${T.key}`;j$(J,$,W,({newValue:X,oldValue:F})=>{let Y=J.timelineTopics.getRelatedKey($.key);if(Y){if(J.timelines.get(Y)?.timeTraveling){let M=OF(J,{key:Y,type:"timeline"},W,(z)=>{M(),W$(J,T,(A)=>{if(z==="redo"&&X)A.do(X);else if(z==="undo"&&F)A.undo(F);return A})});return}}let G=J.on.operationClose.subscribe(W,()=>{G();let H=ZT(J,T),M=X===null?-1:H.getUpdateNumber(X),z=M-H.cacheUpdateNumber;if(X&&z===1)W$(J,T,(A)=>(A.do(X),A));else J.logger.info("\u274C","mutable_atom",T.key,`could not be updated. Expected update number ${H.cacheUpdateNumber+1}, but got ${M}`)})})}mutableState;latestUpdateState;[Symbol.dispose];constructor(T,$){this.mutableState=T;let J=g($);this.latestUpdateState=this.initializeState(T,J),this.observeCore(T,this.latestUpdateState,J),this.updateCore(T,this.latestUpdateState,J),J.trackers.set(T.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),J.trackers.delete(T.key)}}}function LX(T,$,J){T.logger.info("\uD83D\uDD28","atom",$.key,`creating in store "${T.config.name}"`);let W=g(T),X=W.atoms.get($.key);if(X&&X.type==="mutable_atom")return T.logger.error("\u274C","atom",$.key,"Tried to create atom, but it already exists in the store."),n$(X);let F=new QT,Y={...$,type:"mutable_atom",install:(M)=>{return M.logger.info("\uD83D\uDEE0\uFE0F","atom",$.key,`installing in store "${M.config.name}"`),LX(M,$,J)},subject:F};if(J)Y.family=J;let G=$.default();W.atoms.set(Y.key,Y),v8(T,$.key),UJ(W,$.key,G,F);let H=n$(Y);if($.effects){let M=0,z=[];for(let A of $.effects){let w=A({setSelf:(_)=>{W$(T,H,_)},onSet:(_)=>j$(T,H,`effect[${M}]`,_)});if(w)z.push(w);++M}Y.cleanup=()=>{for(let A of z)A()}}if(new Q0(H,T),!J)G7(H,$,T);return H}class DF{trackers=new Map;Update;latestUpdateAtoms;mutableAtoms;constructor(T,$){let J=X1($,{key:`*${T.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=fT($,J),this.mutableAtoms=T,this.mutableAtoms.subject.subscribe(`store=${$.config.name}::tracker-atom-family`,(W)=>{let{type:X,token:F}=W;if(F.family){let Y=R$(F.family.subKey);switch(X){case"state_creation":this.trackers.set(Y,new Q0(F,$));break;case"state_disposal":{let G=this.trackers.get(Y);if(G)G[Symbol.dispose](),this.trackers.delete(Y)}break}}})}}function UX(T,$,J){let W={key:$.key,type:"mutable_atom_family"},X=T.families.get($.key);if(X)T.logger.error("\u2757","mutable_atom_family",$.key,`Overwriting an existing ${cJ(X)} "${X.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let F=new QT,G=Object.assign((H)=>{let M=_T(H),z={key:$.key,subKey:M},A=`${$.key}(${M})`,w=g(T),_={key:A,default:()=>$.default(H),toJson:$.toJson,fromJson:$.fromJson,mutable:!0};if($.effects)_.effects=$.effects(H);let D=LX(w,_,z);return F.next({type:"state_creation",token:D}),D},W,{subject:F,install:(H)=>UX(H,$),toJson:$.toJson,fromJson:$.fromJson,internalRoles:J});return T.families.set($.key,G),i7(T,G,$),new DF(G,T),W}var KF=(T,$)=>{let J=g($),W=`${T.key}:JSON`;return J.families.get(W)};var A$=(T,$)=>{if($.family){let W=g(T),F={key:`${$.family.key}:JSON`,type:"selector_family"},Y=fT(W,F),G=JSON.parse($.family.subKey);return JT(T,Y,G)}return{type:"selector",key:`${$.key}:JSON`}};var Y1=(T)=>{let J={type:"atom",key:`*${T.key}`};if(T.family)J.family={key:`*${T.family.key}`,subKey:T.family.subKey};return J};function f7(T){return typeof T==="object"&&T!==null&&"do"in T&&"undo"in T&&"subscribe"in T}function VX(T,$,J){let W=J.valueMap.get($.key),X=T.valueMap.get($.key);if(W!==X)return X;if(W===void 0)return $.default();J.logger.info("\uD83D\uDCC3","atom",$.key,"copying");let F=$.toJson(W),Y=$.fromJson(F);return T.valueMap.set($.key,Y),new Q0($,J),Y}function UJ(T,$,J,W){let X=T.valueMap.get($);if(X instanceof OX)X.use(J);if(J instanceof Promise){let F=new OX(J);return T.valueMap.set($,F),F.then((Y)=>{UJ(T,$,Y,W),W.next({newValue:Y,oldValue:F})}).catch((Y)=>{T.logger.error("\uD83D\uDCA5","state",$,"rejected:",Y)}),F}return T.valueMap.set($,J),J}var K7=(T,$)=>{let J=$.valueMap.get(T.key);if(T.type==="mutable_atom"&&yT($)){let{parent:W}=$;J=VX($,T,W)}return J},L7=(T,$)=>{let J=$.valueMap.get(T);if(J instanceof OX){let W=J,X=$.selectors.get(T)??$.readonlySelectors.get(T);if(X)W.use(X.get());return}if($.operation.open)$.operation.prev.set(T,J);$.valueMap.delete(T),$.logger.info("\uD83D\uDDD1","state",T,"evicted")};var N7=(T,$)=>{return g(T).atomsThatAreDefault.has($)},v8=(T,$)=>{let J=g(T);J.atomsThatAreDefault=new Set(J.atomsThatAreDefault).add($)},C7=(T,$)=>{let J=g(T);J.atomsThatAreDefault=new Set(g(T).atomsThatAreDefault),J.atomsThatAreDefault.delete($)};function XJ(T,$,J){T.logger.info("\uD83D\uDD28","atom",$.key,`creating in store "${T.config.name}"`);let W=g(T),X=W.atoms.get($.key);if(X&&X.type==="atom")return T.logger.error("\u274C","atom",$.key,"Tried to create atom, but it already exists in the store."),n$(X);let F=new QT,Y={...$,type:"atom",install:(M)=>{return M.logger.info("\uD83D\uDEE0\uFE0F","atom",$.key,`installing in store "${M.config.name}"`),XJ(M,$,J)},subject:F};if(J)Y.family=J;let G=$.default;if($.default instanceof Function)G=$.default();W.atoms.set(Y.key,Y),v8(T,$.key),UJ(W,$.key,G,F);let H=n$(Y);if($.effects){let M=0,z=[];for(let A of $.effects){let w=A({setSelf:(_)=>{W$(T,H,_)},onSet:(_)=>j$(T,H,`effect[${M}]`,_)});if(w)z.push(w);++M}Y.cleanup=()=>{for(let A of z)A()}}return H}function z7(T,$){if("mutable"in $){let X=LX(T,$,void 0);return T.on.atomCreation.next(X),X}let W=XJ(T,$,void 0);return T.on.atomCreation.next(W),W}function wF(T,$){let J=g(T),{key:W,family:X}=$,F=fT(J,$);if(!X)T.logger.error("\u274C","atom",W,"Standalone atoms cannot be disposed.");else{F.cleanup?.();let Y=T.valueMap.get(F.key),G=fT(T,{key:X.key,type:"atom_family"}),H={type:"state_disposal",subType:"atom",token:$,value:Y};G.subject.next(H);let M=yT(J);if(J.atoms.delete(W),J.valueMap.delete(W),J.selectorAtoms.delete(W),J.atomsThatAreDefault.delete(W),T.timelineTopics.delete(W),$.type==="mutable_atom"){let z=Y1($);wF(T,z),T.trackers.delete(W)}if(T.logger.info("\uD83D\uDD25","atom",W,"deleted"),M&&J.transactionMeta.phase==="building"){let z=J.transactionMeta.update.updates.at(-1);if(!(z?.type==="molecule_disposal"&&z.values.some(([_])=>_===F.family?.key)))J.transactionMeta.update.updates.push(H)}else T.on.atomDisposal.next($)}}class Q$ extends Set{mode="record";subject=new QT;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(T,$=0){super(T);if(T instanceof Q$)this.parent=T,this.cacheUpdateNumber=T.cacheUpdateNumber;if($)this.cacheLimit=$,this.cache=new Array($),this.subscribe("auto cache",(J)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=J})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(T){let $=new Q$(T.members,T.cacheLimit);return $.cache=T.cache,$.cacheIdx=T.cacheIdx,$.cacheUpdateNumber=T.cacheUpdateNumber,$}add(T){let $=super.add(T);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${_T(T)}`);return $}clear(){let T=this.mode==="record"?[...this]:null;if(super.clear(),T)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(T)}`)}delete(T){let $=super.delete(T);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${_T(T)}`);return $}parent;child=null;transactionUpdates=null;transaction(T){this.mode="transaction",this.transactionUpdates=[],this.child=new Q$(this);let $=this.child._subscribe("transaction",(J)=>{this.transactionUpdates?.push(J)});try{if(T(this.child)){for(let W of this.transactionUpdates)this.doStep(W);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(J){throw console.warn("Did not apply transaction to SetRTX; this error was thrown:",J),J}finally{$(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(T,$){return this.subject.subscribe(T,$)}subscribe(T,$){return this.subject.subscribe(T,(J)=>{$(`${this.cacheUpdateNumber}=${J}`)})}emit(T){this.subject.next(T)}doStep(T){let $=T.indexOf(":"),J=T.substring(0,$),W=T.substring($+1);switch(J){case"add":this.add(JSON.parse(W));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(W));break;case"tx":for(let X of W.split(";"))this.doStep(X)}}getUpdateNumber(T){let $=T.indexOf("=");return Number(T.substring(0,$))}do(T){let $=T.indexOf("="),J=Number(T.substring(0,$)),W=J-this.cacheUpdateNumber;if(W>0){if(W===1){this.mode="playback";let F=T.substring($+1);return this.doStep(F),this.mode="record",this.cacheUpdateNumber=J,null}return this.cacheUpdateNumber+1}if(Math.abs(W)<this.cacheLimit){let F=this.cacheIdx+W;if(this.cache[F]===T)return null;this.mode="playback";let G=!1;while(!G){this.cacheIdx%=this.cacheLimit;let M=this.cache[this.cacheIdx];if(this.cacheIdx--,!M)return"OUT_OF_RANGE";this.undo(M),G=this.cacheIdx===F-1}let H=T.substring($+1);return this.doStep(H),this.mode="record",this.cacheUpdateNumber=J,null}return"OUT_OF_RANGE"}undoStep(T){let $=T.indexOf(":"),J=T.substring(0,$),W=T.substring($+1);switch(J){case"add":this.delete(JSON.parse(W));break;case"del":this.add(JSON.parse(W));break;case"clear":{let X=JSON.parse(W);for(let F of X)this.add(F);break}case"tx":{let X=W.split(";");for(let F=X.length-1;F>=0;F--)this.undoStep(X[F])}}}undo(T){let $=T.indexOf("=");if(Number(T.substring(0,$))===this.cacheUpdateNumber){this.mode="playback";let W=T.substring($+1);return this.undoStep(W),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}class KX{toolkit;options;defaultContent;molecules=new Map;relations;states;core;transact(T,$){let J=this.toolkit;this.toolkit=T,$(this),this.toolkit=J}store;realm;[Symbol.dispose](){}constructor(T,$,J=KT.STORE){this.store=J,this.realm=new YF(J),this.options=T,this.defaultContent=$,this.store.miscResources.set(`join:${T.key}`,this),this.realm.allocate("root",T.key),this.toolkit={get:(...V)=>ZT(J,...V),set:(...V)=>{W$(J,...V)},find:(...V)=>JT(J,...V),json:(V)=>A$(J,V)};let W=T.between[0],X=T.between[1],F=UX(J,{key:`${T.key}/relatedKeys`,default:()=>new Q$,mutable:!0,fromJson:(V)=>Q$.fromJSON(V),toJson:(V)=>V.toJSON()},["join","relations"]);this.core={relatedKeysAtoms:F};let Y=({get:V},f)=>V(F,f),G=({set:V},f,C)=>{if(!this.store.molecules.has(_T(f)))this.realm.allocate(T.key,f);V(F,f,(B)=>B.add(C)),V(F,C,(B)=>B.add(f))},H=({set:V},f,C)=>{V(F,f,(B)=>{return B.delete(C),B}),V(F,C,(B)=>{return B.delete(f),B})},M=(V,f,C)=>{let{find:B,get:m,set:$T}=V,E=B(F,f),XT=m(E);for(let n of XT){if(C.includes(n))continue;$T(F,n,(kT)=>{return kT.delete(f),kT})}$T(E,(n)=>{return n.transaction((MT)=>{MT.clear();for(let kT of C){let eT=Y(V,kT),l$=eT.has(f);if(this.relations.cardinality==="1:n"){let J1=[];for(let I of eT){if(I===f)continue;let a=Y(V,I);if(a.delete(kT),a.size===0)J1.push(I)}if(!l$&&eT.size>0)eT.clear();for(let I of J1){let a=[kT,I].sort(),NT=`"${a[0]}:${a[1]}"`;this.molecules.delete(NT)}}if(!l$)eT.add(f);MT.add(kT)}return!0}),n})},z=(V,f,C)=>{let{set:B}=V;B(F,f,(m)=>{return m.transaction(($T)=>{for(let E of C)$T.add(E);return!0}),m});for(let m of C)B(F,m,($T)=>{return $T.add(f),$T});return!0},A=(V,f,C)=>{let B=Y(V,f);return C?B.has(C):B.size>0},w={getRelatedKeys:(V)=>Y(this.toolkit,V),addRelation:(V,f)=>{this.store.moleculeJoins.set(V,T.key),this.store.moleculeJoins.set(f,T.key),G(this.toolkit,V,f)},deleteRelation:(V,f)=>{H(this.toolkit,V,f)},replaceRelationsSafely:(V,f)=>{M(this.toolkit,V,f)},replaceRelationsUnsafely:(V,f)=>{z(this.toolkit,V,f)},has:(V,f)=>A(this.toolkit,V,f)},_,D;if($){D=X1(J,{key:`${T.key}/content`,default:$},["join","content"]);let V=({get:B},m)=>B(D,m),f=({set:B},m,$T)=>{B(D,m,$T)};_=Object.assign(w,{getContent:(B)=>{return V(this.toolkit,B)},setContent:(B,m)=>{f(this.toolkit,B,m)},deleteContent:(B)=>{this.realm.deallocate(B)}})}else _=w;let S=new w$(T,{externalStore:_,isAType:T.isAType,isBType:T.isBType,makeContentKey:(...V)=>{let[f,C]=V,B=V.sort(),m=`${B[0]}:${B[1]}`,$T=J.molecules.get(_T(f)),E=J.molecules.get(_T(C));if(!$T)this.realm.allocate(T.key,f);if(!E)this.realm.allocate(T.key,C);return this.realm.allocate(f,m,"all"),this.realm.claim(C,m),this.store.moleculeJoins.set(m,T.key),m}}),Z=()=>F1(J,{key:`${T.key}/singleRelatedKey`,get:(V)=>({get:f})=>{let C=f(F,V);for(let B of C)return B;return null}},["join","keys"]),q=()=>{return F1(J,{key:`${T.key}/multipleRelatedKeys`,get:(V)=>({get:f})=>{let C=KF(F,J);return f(C,V).members}},["join","keys"])},N=()=>F1(J,{key:`${T.key}/singleRelatedEntry`,get:(V)=>({get:f})=>{let C=f(F,V);for(let B of C){let m=S.isAType?.(V)?V:void 0,$T=m===void 0?V:void 0;m??=B,$T??=B;let E=S.makeContentKey(m,$T),XT=f(D,E);return[B,XT]}return null}},["join","entries"]),y=()=>F1(J,{key:`${T.key}/multipleRelatedEntries`,get:(V)=>({get:f})=>{let C=KF(F,J);return f(C,V).members.map((m)=>{let $T=S.isAType?.(V)?V:void 0,E=$T===void 0?V:void 0;$T??=m,E??=m;let XT=S.makeContentKey($T,E),n=f(D,XT);return[m,n]})}},["join","entries"]);switch(T.cardinality){case"1:1":{let V=Z(),f=`${W}KeyOf${IT(X)}`,C=`${X}KeyOf${IT(W)}`,B={[f]:V,[C]:V},m;if($){let $T=N(),E=`${W}EntryOf${IT(X)}`,XT=`${X}EntryOf${IT(W)}`,n={[E]:$T,[XT]:$T};m=Object.assign(B,n)}else m=B;this.relations=S,this.states=m;break}case"1:n":{let V=Z(),f=q(),C=`${W}KeyOf${IT(X)}`,B=`${X}KeysOf${IT(W)}`,m={[C]:V,[B]:f},$T;if($){let E=N(),XT=y(),n=`${W}EntryOf${IT(X)}`,MT=`${X}EntriesOf${IT(W)}`,kT={[n]:E,[MT]:XT};$T=Object.assign(m,kT)}else $T=m;this.relations=S,this.states=$T;break}case"n:n":{let V=q(),f=`${W}KeysOf${IT(X)}`,C=`${X}KeysOf${IT(W)}`,B={[f]:V,[C]:V},m;if($){let $T=y(),E=`${W}EntriesOf${IT(X)}`,XT=`${X}EntriesOf${IT(W)}`,n={[E]:$T,[XT]:$T};m=Object.assign(B,n)}else m=B;this.relations=S,this.states=m}}}}function WW(T,$){let J=$.joins.get(T.key);if(J===void 0){let X=KT.STORE.joins.get(T.key);if(X===void 0)throw new Error(`Join "${T.key}" not found in store "${$.config.name}"`);J=new KX(X.options,X.defaultContent,$),$.joins.set(T.key,J)}return J}function SX(T,$,J){let W=WW(T,J),X=g(J);if(yT(X)){let{toolkit:F}=X.transactionMeta;W.transact(F,({relations:Y})=>{$(Y)})}else $(W.relations)}function Z8(T,$,J){let W=WW(T,J),X;switch(T.cardinality){case"1:1":{let F=`${T.a}KeyOf${IT(T.b)}`,Y=`${T.b}KeyOf${IT(T.a)}`;X={get[F](){let H=W.states[F];return JT(J,H,$)},get[Y](){let H=W.states[Y];return JT(J,H,$)}};let G=`${T.a}EntryOf${IT(T.b)}`;if(G in W.states){let H=`${T.b}EntryOf${IT(T.a)}`;Object.assign(X,{get[G](){let M=W.states[G];return JT(J,M,$)},get[H](){let M=W.states[H];return JT(J,M,$)}})}break}case"1:n":{let F=`${T.a}KeyOf${IT(T.b)}`,Y=`${T.b}KeysOf${IT(T.a)}`;X={get[F](){let H=W.states[F];return JT(J,H,$)},get[Y](){let H=W.states[Y];return JT(J,H,$)}};let G=`${T.a}EntryOf${IT(T.b)}`;if(G in W.states){let H=`${T.b}EntriesOf${IT(T.a)}`;Object.assign(X,{get[G](){let M=W.states[G];return JT(J,M,$)},get[H](){let M=W.states[H];return JT(J,M,$)}})}break}case"n:n":{let F=`${T.a}KeysOf${IT(T.b)}`,Y=`${T.b}KeysOf${IT(T.a)}`;X={get[F](){let H=W.states[F];return JT(J,H,$)},get[Y](){let H=W.states[Y];return JT(J,H,$)}};let G=`${T.a}EntriesOf${IT(T.b)}`;if(G in W.states){let H=`${T.b}EntriesOf${IT(T.a)}`;Object.assign(X,{get[G](){let M=W.states[G];return JT(J,M,$)},get[H](){let M=W.states[H];return JT(J,M,$)}})}}}return X}function Q7(T,$){return WW(T,$).core.relatedKeysAtoms}function v1(T){return T.startsWith("\uD83D\uDD0D ")}class r7 extends Map{set(T,$){if(this.has(T))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:T,value:$}),this;return super.set(T,$)}clear(){throw new Error("Cannot clear an InvariantMap")}}class h8{type="continuity";globals=[];actions=[];perspectives=[];key;constructor(T){this.key=T}static existing=new r7;static create(T,$){let J=new h8(T),{type:W,globals:X,actions:F,perspectives:Y}=$(J),G={type:W,key:T,globals:X,actions:F,perspectives:Y};return h8.existing.set(T,G),G}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":case"mutable_atom_family":{let[J,W]=T;this.perspectives.push({type:"realtime_perspective",resourceAtoms:J,viewAtoms:W})}break}return this}}function py(T){let{key:$,config:J}=T,W=h8.create($,J),{actions:X}=W;for(let F of X)h7(KT.STORE,$,F.key);return P7(KT.STORE,$,-1),W}var dy=e0({key:"usersInRoomIndex",mutable:!0,default:()=>new Q$,toJson:(T)=>T.toJSON(),fromJson:(T)=>Q$.fromJSON(T)}),SF=e0({key:"roomIndex",default:()=>new Q$,mutable:!0,toJson:(T)=>T.toJSON(),fromJson:(T)=>Q$.fromJSON(T)}),H_={enteredAtEpoch:0},BX=C8({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(T)=>typeof T==="string",isBType:(T)=>typeof T==="string"},H_),ly=q8({key:"usersInMyRoomView",get:(T)=>({find:$})=>{let J=w7(BX);return[$(J,T)]}});import{spawn as M_}from"child_process";class XW{listeners;globalListeners;handleEvent(T,...$){for(let W of this.globalListeners)W(T,...$);let J=this.listeners.get(T);if(J)for(let W of J)W(...$)}id="no_id_retrieved";emit;constructor(T){this.emit=T,this.listeners=new Map,this.globalListeners=new Set}on(T,$){let J=this.listeners.get(T);if(J)J.add($);else this.listeners.set(T,new Set([$]));return this}onAny(T){return this.globalListeners.add(T),this}off(T,$){let J=this.listeners.get(T);if(J)if($)J.delete($);else this.listeners.delete(T);return this}offAny(T){return this.globalListeners.delete(T),this}}class VF extends XW{incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";process;key;logger;handleLog(T){if(Array.isArray(T)){let[$,...J]=T;switch($){case"i":this.logger.info(...J);break;case"w":this.logger.warn(...J);break;case"e":this.logger.error(...J);break;default:return}}}constructor(T,$,J){super((W,...X)=>{let F=JSON.stringify([W,...X])+"\x03",Y=(G)=>{if(G.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",Y)};return this.process.stdin.once("error",Y),this.process.stdin.write(F),this});if(this.process=T,this.key=$,this.logger=J??{info:(...W)=>{console.info(this.id,this.key,...W)},warn:(...W)=>{console.warn(this.id,this.key,...W)},error:(...W)=>{console.error(this.id,this.key,...W)}},this.process.stdout.on("data",(W)=>{let X=W.toString();if(X==="ALIVE")return;this.unprocessedEvents.push(...X.split("\x03"));let F=this.unprocessedEvents.shift();this.incompleteData+=F??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let Y=R$(this.incompleteData);this.handleEvent(...Y);while(this.unprocessedEvents.length>0){let G=this.unprocessedEvents.shift();if(G){if(this.unprocessedEvents.length===0)this.incompleteData=G;Y=R$(G),this.handleEvent(...Y)}}this.incompleteData=""}catch(Y){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error(Y)}}),this.process.stderr.on("data",(W)=>{let X=W.toString();this.unprocessedLogs.push(...X.split("\x03"));let F=this.unprocessedLogs.shift();this.incompleteLog+=F??"";try{let Y=R$(this.incompleteLog);this.handleLog(Y);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)Y=R$(this.incompleteLog),this.handleLog(Y)}catch(Y){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error(Y),console.error("\u274C\u274C\u274C\uFE0F")}}),T.pid)this.id=T.pid.toString()}}class a7 extends XW{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(T){super((...$)=>{return this.out.next($),this});this.id=T,this.in=new QT,this.out=new QT,this.in.subscribe("socket",($)=>{this.handleEvent(...$)})}dispose(){for(let T of this.disposalFunctions)T()}}class EF extends XW{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...T){this.process.stderr.write(_T(T.map(($)=>$ instanceof Q$?`{ ${$.toJSON().members.join(" | ")} }`:$))+"\x03")}logger={info:(...T)=>{this.log("i",...T)},warn:(...T)=>{this.log("w",...T)},error:(...T)=>{this.log("e",...T)}};constructor(){super((T,...$)=>{let J=JSON.stringify([T,...$]);return this.process.stdout.write(J+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(T)=>{let $=T.toString();this.unprocessedEvents.push(...$.split("\x03"));let J=this.unprocessedEvents.shift();this.incompleteData+=J??"";try{let W=R$(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",W),this.handleEvent(...W);while(this.unprocessedEvents.length>0){let X=this.unprocessedEvents.shift();if(X){if(this.unprocessedEvents.length===0)this.incompleteData=X;let F=R$(X);this.handleEvent(...F)}}this.incompleteData=""}catch(W){if(W instanceof Error)this.logger.error("\u2757",W.message,W.cause,W.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(T)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${T}`)}),process.on("end",()=>{this.logger.info("\uD83D\uDD25",this.id,"ended"),process.exit(0)}),process.on("SIGTERM",()=>{this.logger.error("\uD83D\uDD25",this.id,"terminated"),process.exit(0)}),process.on("SIGINT",()=>{this.logger.error("\uD83D\uDD25",this.id,"interrupted"),process.exit(0)}),process.pid)this.id=process.pid?.toString();this.on("user-joins",(T)=>{this.logger.info("\uD83D\uDC64","user",T,"joined");let $=new a7(`user:${T}`);this.relays.set(T,$),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let J of this.relayServices){let W=J($);if(W)$.disposalFunctions.push(W)}this.on(`user:${T}`,(...J)=>{$.in.next(J)}),$.out.subscribe("socket",(J)=>{this.emit(...J)})}),this.on("user-leaves",(T)=>{let $=this.relays.get(T);if(this.off(`relay:${T}`),$)$.dispose(),this.relays.delete(T)}),process.stdout.write("ALIVE")}relay(T){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(T)}}var RF=H0({key:"roomArguments",default:["echo",["Hello World!"]]}),s7=q8({key:"room",get:(T)=>async({get:$,find:J})=>{let W=J(RF,T),X=$(W),[F,Y]=X,G=await new Promise((H)=>{let M=M_(F,Y,{env:process.env}),z=(A)=>{if(A.toString()==="ALIVE")M.stdout.off("data",z),H(M)};M.stdout.on("data",z)});return new VF(G,T)}});var SI=EX({key:"createRoom",do:({get:T,set:$,find:J},W,X,F)=>{let Y=F?[X,F]:[X],G=J(RF,W);$(G,Y),$(SF,(z)=>z.add(W));let H=J(s7,W);return T(H)}}),VI=EX({key:"joinRoom",do:(T,$,J,W)=>{let X={enteredAtEpoch:W};return SX(BX,(F)=>{F.set({room:$,user:J},X)},T.env().store),X}}),EI=EX({key:"leaveRoom",do:(T,$,J)=>{SX(BX,(W)=>{W.delete({room:$,user:J})},T.env().store)}}),RI=EX({key:"destroyRoom",do:(T,$)=>{SX(BX,(J)=>{J.delete({room:$})},T.env().store),T.set(SF,(J)=>(J.delete($),J))}});function LF(T,$){return $.map((J)=>{switch(J.type){case"transaction_update":{let W=LF(T,J.updates);return{...J,updates:W}}case"atom_update":case"selector_update":case"molecule_creation":case"molecule_disposal":case"molecule_transfer":case"state_creation":case"state_disposal":return J}}).filter((J)=>{switch(J.type){case"atom_update":case"selector_update":return T.includes(J.key);case"state_creation":case"state_disposal":return T.includes(J.token.key);case"molecule_creation":case"transaction_update":case"molecule_disposal":case"molecule_transfer":return!0}})}var fI=H0({key:"redactor",default:{occlude:(T)=>T}}),FW=H0({key:"unacknowledgedUpdates",default:()=>[]});var e7=H0({key:"sockets",default:null}),qI=e0({key:"socketsIndex",mutable:!0,default:()=>new Q$,toJson:(T)=>T.toJSON(),fromJson:(T)=>Q$.fromJSON(T)}),kI=e0({key:"usersIndex",mutable:!0,default:()=>new Q$,toJson:(T)=>T.toJSON(),fromJson:(T)=>Q$.fromJSON(T)}),BF=C8({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(T)=>T.startsWith("user::"),isBType:(T)=>T.startsWith("socket::")});function TG(T,$,J,W){let X=$.key;return function F(){let Y=[];for(let H of $.globals){let M=H.type==="mutable_atom"?A$(T,H):H,z=ZT(T,M);Y.push(M,z)}for(let H of $.perspectives){let{viewAtoms:M,resourceAtoms:z}=H,A=JT(T,M,J),w=ZT(T,A);T.logger.info("\uD83D\uDC41","atom",z.key,`${J} can see`,{viewAtoms:M,resourceAtoms:z,userView:w});for(let _ of w){let D=_.type==="mutable_atom"?A$(T,_):_,S=ZT(T,D);Y.push(D,S)}}let G=N$(T)?T.transactionMeta.epoch.get(X)??null:null;W?.emit(`continuity-init:${X}`,G,Y)}}function $G(T,$,J){let W=$.key;return function X(F){T.logger.info("\uD83D\uDECE\uFE0F","continuity",W,"received",F);let{key:Y,id:G}=F,H=`tx-run:${Y}:${G}`,M=`${H}:start`,z=`${H}:end`;performance.mark(M);try{$W(T,{type:"transaction",key:Y},G)(...F.params)}catch(w){if(w instanceof Error)T.logger.error("\u274C","continuity",W,`failed to run transaction ${Y} from ${J} with update ${G}`,w.message)}performance.mark(z);let A=performance.measure(H,M,z);T?.logger.info("\uD83D\uDE80","transaction",Y,G,J,A.duration)}}function JG(T,$,J,W){let X=$.key;return function F(Y){if(T.logger.info("\uD83D\uDC4D","continuity",X,`${J} acknowledged epoch ${Y}`),W[0]?.epoch===Y)W$(T,FW,J,(H)=>{return H.shift(),T.logger.info("\uD83D\uDC4D","continuity",X,`${J} unacknowledged update queue now has`,H.length,"items"),H})}}function WG(T,$,J,W){let X=$.key,F=[];for(let Y of $.actions){let G=UF(T,Y,`sync-continuity:${X}:${J}`,(H)=>{try{let M=$.globals.map((w)=>{if(w.type==="atom")return w.key;return Y1(w).key}).concat($.perspectives.flatMap((w)=>{let{viewAtoms:_}=w,D=JT(T,_,J);return ZT(T,D).map((Z)=>{return Z.type==="mutable_atom"?"*"+Z.key:Z.key})})),z=LF(M,H.updates),A={...H,updates:z};W$(T,FW,J,(w)=>{if(A)w.push(A),w.sort((_,D)=>_.epoch-D.epoch),T.logger.info("\uD83D\uDC4D","continuity",X,`${J} unacknowledged update queue now has`,w.length,"items");return w}),W?.emit(`tx-new:${X}`,A)}catch(M){if(M instanceof Error)T.logger.error("\u274C","continuity",X,`${J} failed to send update from transaction ${Y.key} to ${J}`,M.message)}});F.push(G)}return F}function XG(T,$,J,W){let X=$.key,F=[];for(let Y of $.perspectives){let{viewAtoms:G}=Y,H=JT(T,G,J),M=j$(T,H,`sync-continuity:${X}:${J}:perspective:${Y.resourceAtoms.key}`,({oldValue:z,newValue:A})=>{let w=z.map((Z)=>Z.key),_=A.map((Z)=>Z.key),D=z.filter((Z)=>!_.includes(Z.key)),S=A.filter((Z)=>!w.includes(Z.key)).flatMap((Z)=>{let q=Z.type==="mutable_atom"?A$(T,Z):Z,N=ZT(T,q);return[q,N]});if(T.logger.info("\uD83D\uDC41","atom",Y.resourceAtoms.key,`${J} has a new perspective`,{oldKeys:w,newKeys:_,revealed:S,concealed:D}),S.length>0)W?.emit(`reveal:${X}`,S);if(D.length>0)W?.emit(`conceal:${X}`,D)});F.push(M)}return F}function Fj({socket:T,store:$=KT.STORE}){return function J(W){let X=T,F=W.key,Y=Z8(BF,`socket::${X.id}`,$).userKeyOfSocket,G=ZT($,Y);if(!G)return $.logger.error("\u274C","continuity",F,`Tried to create a synchronizer for a socket (${X.id}) that is not connected to a user.`),()=>{};let H=Z8(BF,G,$).socketKeyOfUser,M=j$($,H,`sync-continuity:${F}:${G}`,({newValue:q})=>{if($.logger.info("\uD83D\uDC4B","continuity",F,`seeing ${G} on new socket ${q}`),q===null){$.logger.warn("\u274C","continuity",F,`User (${G}) is not connected to a socket, waiting for them to reappear.`);return}let N=JT($,e7,q);X=ZT($,N);for(let V of z)X?.emit(`tx-new:${F}`,V)}),z=ZT($,FW,G),A=[],w=XG($,W,G,X),_=WG($,W,G,X);A.push(...w,..._);let D=TG($,W,G,T);X.off(`get:${F}`,D),X.on(`get:${F}`,D);let S=$G($,W,G);X.off(`tx-run:${F}`,S),X.on(`tx-run:${F}`,S);let Z=JG($,W,G,z);return X?.on(`ack:${F}`,Z),()=>{for(let q of A)q();X?.off(`ack:${F}`,Z),X?.off(`get:${F}`,D),X?.off(`tx-run:${F}`,S)}}}var YG=Symbol("Let zodToJsonSchema decide on which parser to use");var FG={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},GG=(T)=>typeof T==="string"?{...FG,name:T}:{...FG,...T};var HG=(T)=>{let $=GG(T),J=$.name!==void 0?[...$.basePath,$.definitionPath,$.name]:$.basePath;return{...$,currentPath:J,propertyPath:void 0,seen:new Map(Object.entries($.definitions).map(([W,X])=>[X._def,{def:X._def,path:[...$.basePath,$.definitionPath,W],jsonSchema:void 0}]))}};function fF(T,$,J,W){if(!W?.errorMessages)return;if(J)T.errorMessage={...T.errorMessage,[$]:J}}function ET(T,$,J,W,X){T[$]=J,fF(T,$,W,X)}var LT;(function(T){T.assertEqual=(X)=>X;function $(X){}T.assertIs=$;function J(X){throw new Error}T.assertNever=J,T.arrayToEnum=(X)=>{let F={};for(let Y of X)F[Y]=Y;return F},T.getValidEnumValues=(X)=>{let F=T.objectKeys(X).filter((G)=>typeof X[X[G]]!=="number"),Y={};for(let G of F)Y[G]=X[G];return T.objectValues(Y)},T.objectValues=(X)=>{return T.objectKeys(X).map(function(F){return X[F]})},T.objectKeys=typeof Object.keys==="function"?(X)=>Object.keys(X):(X)=>{let F=[];for(let Y in X)if(Object.prototype.hasOwnProperty.call(X,Y))F.push(Y);return F},T.find=(X,F)=>{for(let Y of X)if(F(Y))return Y;return},T.isInteger=typeof Number.isInteger==="function"?(X)=>Number.isInteger(X):(X)=>typeof X==="number"&&isFinite(X)&&Math.floor(X)===X;function W(X,F=" | "){return X.map((Y)=>typeof Y==="string"?`'${Y}'`:Y).join(F)}T.joinValues=W,T.jsonStringifyReplacer=(X,F)=>{if(typeof F==="bigint")return F.toString();return F}})(LT||(LT={}));var MG;(function(T){T.mergeShapes=($,J)=>{return{...$,...J}}})(MG||(MG={}));var o=LT.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),h1=(T)=>{switch(typeof T){case"undefined":return o.undefined;case"string":return o.string;case"number":return isNaN(T)?o.nan:o.number;case"boolean":return o.boolean;case"function":return o.function;case"bigint":return o.bigint;case"symbol":return o.symbol;case"object":if(Array.isArray(T))return o.array;if(T===null)return o.null;if(T.then&&typeof T.then==="function"&&T.catch&&typeof T.catch==="function")return o.promise;if(typeof Map!=="undefined"&&T instanceof Map)return o.map;if(typeof Set!=="undefined"&&T instanceof Set)return o.set;if(typeof Date!=="undefined"&&T instanceof Date)return o.date;return o.object;default:return o.unknown}},j=LT.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"]);class DJ extends Error{get errors(){return this.issues}constructor(T){super();this.issues=[],this.addIssue=(J)=>{this.issues=[...this.issues,J]},this.addIssues=(J=[])=>{this.issues=[...this.issues,...J]};let $=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,$);else this.__proto__=$;this.name="ZodError",this.issues=T}format(T){let $=T||function(X){return X.message},J={_errors:[]},W=(X)=>{for(let F of X.issues)if(F.code==="invalid_union")F.unionErrors.map(W);else if(F.code==="invalid_return_type")W(F.returnTypeError);else if(F.code==="invalid_arguments")W(F.argumentsError);else if(F.path.length===0)J._errors.push($(F));else{let Y=J,G=0;while(G<F.path.length){let H=F.path[G];if(G!==F.path.length-1)Y[H]=Y[H]||{_errors:[]};else Y[H]=Y[H]||{_errors:[]},Y[H]._errors.push($(F));Y=Y[H],G++}}};return W(this),J}static assert(T){if(!(T instanceof DJ))throw new Error(`Not a ZodError: ${T}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,LT.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(T=($)=>$.message){let $={},J=[];for(let W of this.issues)if(W.path.length>0)$[W.path[0]]=$[W.path[0]]||[],$[W.path[0]].push(T(W));else J.push(T(W));return{formErrors:J,fieldErrors:$}}get formErrors(){return this.flatten()}}DJ.create=(T)=>{return new DJ(T)};var qX=(T,$)=>{let J;switch(T.code){case j.invalid_type:if(T.received===o.undefined)J="Required";else J=`Expected ${T.expected}, received ${T.received}`;break;case j.invalid_literal:J=`Invalid literal value, expected ${JSON.stringify(T.expected,LT.jsonStringifyReplacer)}`;break;case j.unrecognized_keys:J=`Unrecognized key(s) in object: ${LT.joinValues(T.keys,", ")}`;break;case j.invalid_union:J="Invalid input";break;case j.invalid_union_discriminator:J=`Invalid discriminator value. Expected ${LT.joinValues(T.options)}`;break;case j.invalid_enum_value:J=`Invalid enum value. Expected ${LT.joinValues(T.options)}, received '${T.received}'`;break;case j.invalid_arguments:J="Invalid function arguments";break;case j.invalid_return_type:J="Invalid function return type";break;case j.invalid_date:J="Invalid date";break;case j.invalid_string:if(typeof T.validation==="object")if("includes"in T.validation){if(J=`Invalid input: must include "${T.validation.includes}"`,typeof T.validation.position==="number")J=`${J} at one or more positions greater than or equal to ${T.validation.position}`}else if("startsWith"in T.validation)J=`Invalid input: must start with "${T.validation.startsWith}"`;else if("endsWith"in T.validation)J=`Invalid input: must end with "${T.validation.endsWith}"`;else LT.assertNever(T.validation);else if(T.validation!=="regex")J=`Invalid ${T.validation}`;else J="Invalid";break;case j.too_small:if(T.type==="array")J=`Array must contain ${T.exact?"exactly":T.inclusive?"at least":"more than"} ${T.minimum} element(s)`;else if(T.type==="string")J=`String must contain ${T.exact?"exactly":T.inclusive?"at least":"over"} ${T.minimum} character(s)`;else if(T.type==="number")J=`Number must be ${T.exact?"exactly equal to ":T.inclusive?"greater than or equal to ":"greater than "}${T.minimum}`;else if(T.type==="date")J=`Date must be ${T.exact?"exactly equal to ":T.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(T.minimum))}`;else J="Invalid input";break;case j.too_big:if(T.type==="array")J=`Array must contain ${T.exact?"exactly":T.inclusive?"at most":"less than"} ${T.maximum} element(s)`;else if(T.type==="string")J=`String must contain ${T.exact?"exactly":T.inclusive?"at most":"under"} ${T.maximum} character(s)`;else if(T.type==="number")J=`Number must be ${T.exact?"exactly":T.inclusive?"less than or equal to":"less than"} ${T.maximum}`;else if(T.type==="bigint")J=`BigInt must be ${T.exact?"exactly":T.inclusive?"less than or equal to":"less than"} ${T.maximum}`;else if(T.type==="date")J=`Date must be ${T.exact?"exactly":T.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(T.maximum))}`;else J="Invalid input";break;case j.custom:J="Invalid input";break;case j.invalid_intersection_types:J="Intersection results could not be merged";break;case j.not_multiple_of:J=`Number must be a multiple of ${T.multipleOf}`;break;case j.not_finite:J="Number must be finite";break;default:J=$.defaultError,LT.assertNever(T)}return{message:J}},z_=qX;function CF(){return z_}var ZF=(T)=>{let{data:$,path:J,errorMaps:W,issueData:X}=T,F=[...J,...X.path||[]],Y={...X,path:F};if(X.message!==void 0)return{...X,path:F,message:X.message};let G="",H=W.filter((M)=>!!M).slice().reverse();for(let M of H)G=M(Y,{data:$,defaultError:G}).message;return{...X,path:F,message:G}};function p(T,$){let J=CF(),W=ZF({issueData:$,data:T.data,path:T.path,errorMaps:[T.common.contextualErrorMap,T.schemaErrorMap,J,J===qX?void 0:qX].filter((X)=>!!X)});T.common.issues.push(W)}class g${constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(T,$){let J=[];for(let W of $){if(W.status==="aborted")return FT;if(W.status==="dirty")T.dirty();J.push(W.value)}return{status:T.value,value:J}}static async mergeObjectAsync(T,$){let J=[];for(let W of $){let X=await W.key,F=await W.value;J.push({key:X,value:F})}return g$.mergeObjectSync(T,J)}static mergeObjectSync(T,$){let J={};for(let W of $){let{key:X,value:F}=W;if(X.status==="aborted")return FT;if(F.status==="aborted")return FT;if(X.status==="dirty")T.dirty();if(F.status==="dirty")T.dirty();if(X.value!=="__proto__"&&(typeof F.value!=="undefined"||W.alwaysSet))J[X.value]=F.value}return{status:T.value,value:J}}}var FT=Object.freeze({status:"aborted"}),fX=(T)=>({status:"dirty",value:T}),i$=(T)=>({status:"valid",value:T}),zG=(T)=>T.status==="aborted",AG=(T)=>T.status==="dirty",GW=(T)=>T.status==="valid",m8=(T)=>typeof Promise!=="undefined"&&T instanceof Promise;function g8(T,$,J,W){if(J==="a"&&!W)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?T!==$||!W:!$.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return J==="m"?W:J==="a"?W.call(T):W?W.value:$.get(T)}function QG(T,$,J,W,X){if(W==="m")throw new TypeError("Private method is not writable");if(W==="a"&&!X)throw new TypeError("Private accessor was defined without a setter");if(typeof $==="function"?T!==$||!X:!$.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return W==="a"?X.call(T,J):X?X.value=J:$.set(T,J),J}var i;(function(T){T.errToObj=($)=>typeof $==="string"?{message:$}:$||{},T.toString=($)=>typeof $==="string"?$:$===null||$===void 0?void 0:$.message})(i||(i={}));var NX,CX;class qJ{constructor(T,$,J,W){this._cachedPath=[],this.parent=T,this.data=$,this._path=J,this._key=W}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 wG=(T,$)=>{if(GW($))return{success:!0,data:$.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;let J=new DJ(T.common.issues);return this._error=J,this._error}}}};function zT(T){if(!T)return{};let{errorMap:$,invalid_type_error:J,required_error:W,description:X}=T;if($&&(J||W))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if($)return{errorMap:$,description:X};return{errorMap:(Y,G)=>{var H,M;let{message:z}=T;if(Y.code==="invalid_enum_value")return{message:z!==null&&z!==void 0?z:G.defaultError};if(typeof G.data==="undefined")return{message:(H=z!==null&&z!==void 0?z:W)!==null&&H!==void 0?H:G.defaultError};if(Y.code!=="invalid_type")return{message:G.defaultError};return{message:(M=z!==null&&z!==void 0?z:J)!==null&&M!==void 0?M:G.defaultError}},description:X}}class DT{get description(){return this._def.description}_getType(T){return h1(T.data)}_getOrReturnCtx(T,$){return $||{common:T.parent.common,data:T.data,parsedType:h1(T.data),schemaErrorMap:this._def.errorMap,path:T.path,parent:T.parent}}_processInputParams(T){return{status:new g$,ctx:{common:T.parent.common,data:T.data,parsedType:h1(T.data),schemaErrorMap:this._def.errorMap,path:T.path,parent:T.parent}}}_parseSync(T){let $=this._parse(T);if(m8($))throw new Error("Synchronous parse encountered promise.");return $}_parseAsync(T){let $=this._parse(T);return Promise.resolve($)}parse(T,$){let J=this.safeParse(T,$);if(J.success)return J.data;throw J.error}safeParse(T,$){var J;let W={common:{issues:[],async:(J=$===null||$===void 0?void 0:$.async)!==null&&J!==void 0?J:!1,contextualErrorMap:$===null||$===void 0?void 0:$.errorMap},path:($===null||$===void 0?void 0:$.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:T,parsedType:h1(T)},X=this._parseSync({data:T,path:W.path,parent:W});return wG(W,X)}"~validate"(T){var $,J;let W={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:T,parsedType:h1(T)};if(!this["~standard"].async)try{let X=this._parseSync({data:T,path:[],parent:W});return GW(X)?{value:X.value}:{issues:W.common.issues}}catch(X){if((J=($=X===null||X===void 0?void 0:X.message)===null||$===void 0?void 0:$.toLowerCase())===null||J===void 0?void 0:J.includes("encountered"))this["~standard"].async=!0;W.common={issues:[],async:!0}}return this._parseAsync({data:T,path:[],parent:W}).then((X)=>GW(X)?{value:X.value}:{issues:W.common.issues})}async parseAsync(T,$){let J=await this.safeParseAsync(T,$);if(J.success)return J.data;throw J.error}async safeParseAsync(T,$){let J={common:{issues:[],contextualErrorMap:$===null||$===void 0?void 0:$.errorMap,async:!0},path:($===null||$===void 0?void 0:$.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:T,parsedType:h1(T)},W=this._parse({data:T,path:J.path,parent:J}),X=await(m8(W)?W:Promise.resolve(W));return wG(J,X)}refine(T,$){let J=(W)=>{if(typeof $==="string"||typeof $==="undefined")return{message:$};else if(typeof $==="function")return $(W);else return $};return this._refinement((W,X)=>{let F=T(W),Y=()=>X.addIssue({code:j.custom,...J(W)});if(typeof Promise!=="undefined"&&F instanceof Promise)return F.then((G)=>{if(!G)return Y(),!1;else return!0});if(!F)return Y(),!1;else return!0})}refinement(T,$){return this._refinement((J,W)=>{if(!T(J))return W.addIssue(typeof $==="function"?$(J,W):$),!1;else return!0})}_refinement(T){return new dJ({schema:this,typeName:x.ZodEffects,effect:{type:"refinement",refinement:T}})}superRefine(T){return this._refinement(T)}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),this["~standard"]={version:1,vendor:"zod",validate:($)=>this["~validate"]($)}}optional(){return KJ.create(this,this._def)}nullable(){return m1.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return oJ.create(this)}promise(){return AW.create(this,this._def)}or(T){return jX.create([this,T],this._def)}and(T){return xX.create(this,T,this._def)}transform(T){return new dJ({...zT(this._def),schema:this,typeName:x.ZodEffects,effect:{type:"transform",transform:T}})}default(T){let $=typeof T==="function"?T:()=>T;return new hX({...zT(this._def),innerType:this,defaultValue:$,typeName:x.ZodDefault})}brand(){return new yF({typeName:x.ZodBranded,type:this,...zT(this._def)})}catch(T){let $=typeof T==="function"?T:()=>T;return new mX({...zT(this._def),innerType:this,catchValue:$,typeName:x.ZodCatch})}describe(T){return new this.constructor({...this._def,description:T})}pipe(T){return i8.create(this,T)}readonly(){return gX.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var A_=/^c[^\s-]{8,}$/i,w_=/^[0-9a-z]+$/,Q_=/^[0-9A-HJKMNP-TV-Z]{26}$/i,O_=/^[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,U_=/^[a-z0-9_-]{21}$/i,__=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,D_=/^[-+]?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)?)??$/,K_=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,S_="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",NF,V_=/^(?:(?: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])$/,E_=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,R_=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,L_=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,B_=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,f_=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,OG="((\\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])))",N_=new RegExp(`^${OG}$`);function UG(T){let $="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";if(T.precision)$=`${$}\\.\\d{${T.precision}}`;else if(T.precision==null)$=`${$}(\\.\\d+)?`;return $}function C_(T){return new RegExp(`^${UG(T)}$`)}function Z_(T){let $=`${OG}T${UG(T)}`,J=[];if(J.push(T.local?"Z?":"Z"),T.offset)J.push("([+-]\\d{2}:?\\d{2})");return $=`${$}(${J.join("|")})`,new RegExp(`^${$}$`)}function q_(T,$){if(($==="v4"||!$)&&V_.test(T))return!0;if(($==="v6"||!$)&&R_.test(T))return!0;return!1}function k_(T,$){if(!__.test(T))return!1;try{let[J]=T.split("."),W=J.replace(/-/g,"+").replace(/_/g,"/").padEnd(J.length+(4-J.length%4)%4,"="),X=JSON.parse(atob(W));if(typeof X!=="object"||X===null)return!1;if(!X.typ||!X.alg)return!1;if($&&X.alg!==$)return!1;return!0}catch(J){return!1}}function y_(T,$){if(($==="v4"||!$)&&E_.test(T))return!0;if(($==="v6"||!$)&&L_.test(T))return!0;return!1}class H1 extends DT{_parse(T){if(this._def.coerce)T.data=String(T.data);if(this._getType(T)!==o.string){let X=this._getOrReturnCtx(T);return p(X,{code:j.invalid_type,expected:o.string,received:X.parsedType}),FT}let J=new g$,W=void 0;for(let X of this._def.checks)if(X.kind==="min"){if(T.data.length<X.value)W=this._getOrReturnCtx(T,W),p(W,{code:j.too_small,minimum:X.value,type:"string",inclusive:!0,exact:!1,message:X.message}),J.dirty()}else if(X.kind==="max"){if(T.data.length>X.value)W=this._getOrReturnCtx(T,W),p(W,{code:j.too_big,maximum:X.value,type:"string",inclusive:!0,exact:!1,message:X.message}),J.dirty()}else if(X.kind==="length"){let F=T.data.length>X.value,Y=T.data.length<X.value;if(F||Y){if(W=this._getOrReturnCtx(T,W),F)p(W,{code:j.too_big,maximum:X.value,type:"string",inclusive:!0,exact:!0,message:X.message});else if(Y)p(W,{code:j.too_small,minimum:X.value,type:"string",inclusive:!0,exact:!0,message:X.message});J.dirty()}}else if(X.kind==="email"){if(!K_.test(T.data))W=this._getOrReturnCtx(T,W),p(W,{validation:"email",code:j.invalid_string,message:X.message}),J.dirty()}else if(X.kind==="emoji"){if(!NF)NF=new RegExp(S_,"u");if(!NF.test(T.data))W=this._getOrReturnCtx(T,W),p(W,{validation:"emoji",code:j.invalid_string,message:X.message}),J.dirty()}else if(X.kind==="uuid"){if(!O_.test(T.data))W=this._getOrReturnCtx(T,W),p(W,{validation:"uuid",code:j.invalid_string,message:X.message}),J.dirty()}else if(X.kind==="nanoid"){if(!U_.test(T.data))W=this._getOrReturnCtx(T,W),p(W,{validation:"nanoid",code:j.invalid_string,message:X.message}),J.dirty()}else if(X.kind==="cuid"){if(!A_.test(T.data))W=this._getOrReturnCtx(T,W),p(W,{validation:"cuid",code:j.invalid_string,message:X.message}),J.dirty()}else if(X.kind==="cuid2"){if(!w_.test(T.data))W=this._getOrReturnCtx(T,W),p(W,{validation:"cuid2",code:j.invalid_string,message:X.message}),J.dirty()}else if(X.kind==="ulid"){if(!Q_.test(T.data))W=this._getOrReturnCtx(T,W),p(W,{validation:"ulid",code:j.invalid_string,message:X.message}),J.dirty()}else if(X.kind==="url")try{new URL(T.data)}catch(F){W=this._getOrReturnCtx(T,W),p(W,{validation:"url",code:j.invalid_string,message:X.message}),J.dirty()}else if(X.kind==="regex"){if(X.regex.lastIndex=0,!X.regex.test(T.data))W=this._getOrReturnCtx(T,W),p(W,{validation:"regex",code:j.invalid_string,message:X.message}),J.dirty()}else if(X.kind==="trim")T.data=T.data.trim();else if(X.kind==="includes"){if(!T.data.includes(X.value,X.position))W=this._getOrReturnCtx(T,W),p(W,{code:j.invalid_string,validation:{includes:X.value,position:X.position},message:X.message}),J.dirty()}else if(X.kind==="toLowerCase")T.data=T.data.toLowerCase();else if(X.kind==="toUpperCase")T.data=T.data.toUpperCase();else if(X.kind==="startsWith"){if(!T.data.startsWith(X.value))W=this._getOrReturnCtx(T,W),p(W,{code:j.invalid_string,validation:{startsWith:X.value},message:X.message}),J.dirty()}else if(X.kind==="endsWith"){if(!T.data.endsWith(X.value))W=this._getOrReturnCtx(T,W),p(W,{code:j.invalid_string,validation:{endsWith:X.value},message:X.message}),J.dirty()}else if(X.kind==="datetime"){if(!Z_(X).test(T.data))W=this._getOrReturnCtx(T,W),p(W,{code:j.invalid_string,validation:"datetime",message:X.message}),J.dirty()}else if(X.kind==="date"){if(!N_.test(T.data))W=this._getOrReturnCtx(T,W),p(W,{code:j.invalid_string,validation:"date",message:X.message}),J.dirty()}else if(X.kind==="time"){if(!C_(X).test(T.data))W=this._getOrReturnCtx(T,W),p(W,{code:j.invalid_string,validation:"time",message:X.message}),J.dirty()}else if(X.kind==="duration"){if(!D_.test(T.data))W=this._getOrReturnCtx(T,W),p(W,{validation:"duration",code:j.invalid_string,message:X.message}),J.dirty()}else if(X.kind==="ip"){if(!q_(T.data,X.version))W=this._getOrReturnCtx(T,W),p(W,{validation:"ip",code:j.invalid_string,message:X.message}),J.dirty()}else if(X.kind==="jwt"){if(!k_(T.data,X.alg))W=this._getOrReturnCtx(T,W),p(W,{validation:"jwt",code:j.invalid_string,message:X.message}),J.dirty()}else if(X.kind==="cidr"){if(!y_(T.data,X.version))W=this._getOrReturnCtx(T,W),p(W,{validation:"cidr",code:j.invalid_string,message:X.message}),J.dirty()}else if(X.kind==="base64"){if(!B_.test(T.data))W=this._getOrReturnCtx(T,W),p(W,{validation:"base64",code:j.invalid_string,message:X.message}),J.dirty()}else if(X.kind==="base64url"){if(!f_.test(T.data))W=this._getOrReturnCtx(T,W),p(W,{validation:"base64url",code:j.invalid_string,message:X.message}),J.dirty()}else LT.assertNever(X);return{status:J.value,value:T.data}}_regex(T,$,J){return this.refinement((W)=>T.test(W),{validation:$,code:j.invalid_string,...i.errToObj(J)})}_addCheck(T){return new H1({...this._def,checks:[...this._def.checks,T]})}email(T){return this._addCheck({kind:"email",...i.errToObj(T)})}url(T){return this._addCheck({kind:"url",...i.errToObj(T)})}emoji(T){return this._addCheck({kind:"emoji",...i.errToObj(T)})}uuid(T){return this._addCheck({kind:"uuid",...i.errToObj(T)})}nanoid(T){return this._addCheck({kind:"nanoid",...i.errToObj(T)})}cuid(T){return this._addCheck({kind:"cuid",...i.errToObj(T)})}cuid2(T){return this._addCheck({kind:"cuid2",...i.errToObj(T)})}ulid(T){return this._addCheck({kind:"ulid",...i.errToObj(T)})}base64(T){return this._addCheck({kind:"base64",...i.errToObj(T)})}base64url(T){return this._addCheck({kind:"base64url",...i.errToObj(T)})}jwt(T){return this._addCheck({kind:"jwt",...i.errToObj(T)})}ip(T){return this._addCheck({kind:"ip",...i.errToObj(T)})}cidr(T){return this._addCheck({kind:"cidr",...i.errToObj(T)})}datetime(T){var $,J;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:($=T===null||T===void 0?void 0:T.offset)!==null&&$!==void 0?$:!1,local:(J=T===null||T===void 0?void 0:T.local)!==null&&J!==void 0?J:!1,...i.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,...i.errToObj(T===null||T===void 0?void 0:T.message)})}duration(T){return this._addCheck({kind:"duration",...i.errToObj(T)})}regex(T,$){return this._addCheck({kind:"regex",regex:T,...i.errToObj($)})}includes(T,$){return this._addCheck({kind:"includes",value:T,position:$===null||$===void 0?void 0:$.position,...i.errToObj($===null||$===void 0?void 0:$.message)})}startsWith(T,$){return this._addCheck({kind:"startsWith",value:T,...i.errToObj($)})}endsWith(T,$){return this._addCheck({kind:"endsWith",value:T,...i.errToObj($)})}min(T,$){return this._addCheck({kind:"min",value:T,...i.errToObj($)})}max(T,$){return this._addCheck({kind:"max",value:T,...i.errToObj($)})}length(T,$){return this._addCheck({kind:"length",value:T,...i.errToObj($)})}nonempty(T){return this.min(1,i.errToObj(T))}trim(){return new H1({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new H1({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new H1({...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 isCIDR(){return!!this._def.checks.find((T)=>T.kind==="cidr")}get isBase64(){return!!this._def.checks.find((T)=>T.kind==="base64")}get isBase64url(){return!!this._def.checks.find((T)=>T.kind==="base64url")}get minLength(){let T=null;for(let $ of this._def.checks)if($.kind==="min"){if(T===null||$.value>T)T=$.value}return T}get maxLength(){let T=null;for(let $ of this._def.checks)if($.kind==="max"){if(T===null||$.value<T)T=$.value}return T}}H1.create=(T)=>{var $;return new H1({checks:[],typeName:x.ZodString,coerce:($=T===null||T===void 0?void 0:T.coerce)!==null&&$!==void 0?$:!1,...zT(T)})};function I_(T,$){let J=(T.toString().split(".")[1]||"").length,W=($.toString().split(".")[1]||"").length,X=J>W?J:W,F=parseInt(T.toFixed(X).replace(".","")),Y=parseInt($.toFixed(X).replace(".",""));return F%Y/Math.pow(10,X)}class HW extends DT{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)!==o.number){let X=this._getOrReturnCtx(T);return p(X,{code:j.invalid_type,expected:o.number,received:X.parsedType}),FT}let J=void 0,W=new g$;for(let X of this._def.checks)if(X.kind==="int"){if(!LT.isInteger(T.data))J=this._getOrReturnCtx(T,J),p(J,{code:j.invalid_type,expected:"integer",received:"float",message:X.message}),W.dirty()}else if(X.kind==="min"){if(X.inclusive?T.data<X.value:T.data<=X.value)J=this._getOrReturnCtx(T,J),p(J,{code:j.too_small,minimum:X.value,type:"number",inclusive:X.inclusive,exact:!1,message:X.message}),W.dirty()}else if(X.kind==="max"){if(X.inclusive?T.data>X.value:T.data>=X.value)J=this._getOrReturnCtx(T,J),p(J,{code:j.too_big,maximum:X.value,type:"number",inclusive:X.inclusive,exact:!1,message:X.message}),W.dirty()}else if(X.kind==="multipleOf"){if(I_(T.data,X.value)!==0)J=this._getOrReturnCtx(T,J),p(J,{code:j.not_multiple_of,multipleOf:X.value,message:X.message}),W.dirty()}else if(X.kind==="finite"){if(!Number.isFinite(T.data))J=this._getOrReturnCtx(T,J),p(J,{code:j.not_finite,message:X.message}),W.dirty()}else LT.assertNever(X);return{status:W.value,value:T.data}}gte(T,$){return this.setLimit("min",T,!0,i.toString($))}gt(T,$){return this.setLimit("min",T,!1,i.toString($))}lte(T,$){return this.setLimit("max",T,!0,i.toString($))}lt(T,$){return this.setLimit("max",T,!1,i.toString($))}setLimit(T,$,J,W){return new HW({...this._def,checks:[...this._def.checks,{kind:T,value:$,inclusive:J,message:i.toString(W)}]})}_addCheck(T){return new HW({...this._def,checks:[...this._def.checks,T]})}int(T){return this._addCheck({kind:"int",message:i.toString(T)})}positive(T){return this._addCheck({kind:"min",value:0,inclusive:!1,message:i.toString(T)})}negative(T){return this._addCheck({kind:"max",value:0,inclusive:!1,message:i.toString(T)})}nonpositive(T){return this._addCheck({kind:"max",value:0,inclusive:!0,message:i.toString(T)})}nonnegative(T){return this._addCheck({kind:"min",value:0,inclusive:!0,message:i.toString(T)})}multipleOf(T,$){return this._addCheck({kind:"multipleOf",value:T,message:i.toString($)})}finite(T){return this._addCheck({kind:"finite",message:i.toString(T)})}safe(T){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:i.toString(T)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:i.toString(T)})}get minValue(){let T=null;for(let $ of this._def.checks)if($.kind==="min"){if(T===null||$.value>T)T=$.value}return T}get maxValue(){let T=null;for(let $ of this._def.checks)if($.kind==="max"){if(T===null||$.value<T)T=$.value}return T}get isInt(){return!!this._def.checks.find((T)=>T.kind==="int"||T.kind==="multipleOf"&&LT.isInteger(T.value))}get isFinite(){let T=null,$=null;for(let J of this._def.checks)if(J.kind==="finite"||J.kind==="int"||J.kind==="multipleOf")return!0;else if(J.kind==="min"){if($===null||J.value>$)$=J.value}else if(J.kind==="max"){if(T===null||J.value<T)T=J.value}return Number.isFinite($)&&Number.isFinite(T)}}HW.create=(T)=>{return new HW({checks:[],typeName:x.ZodNumber,coerce:(T===null||T===void 0?void 0:T.coerce)||!1,...zT(T)})};class MW extends DT{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(T){if(this._def.coerce)try{T.data=BigInt(T.data)}catch(X){return this._getInvalidInput(T)}if(this._getType(T)!==o.bigint)return this._getInvalidInput(T);let J=void 0,W=new g$;for(let X of this._def.checks)if(X.kind==="min"){if(X.inclusive?T.data<X.value:T.data<=X.value)J=this._getOrReturnCtx(T,J),p(J,{code:j.too_small,type:"bigint",minimum:X.value,inclusive:X.inclusive,message:X.message}),W.dirty()}else if(X.kind==="max"){if(X.inclusive?T.data>X.value:T.data>=X.value)J=this._getOrReturnCtx(T,J),p(J,{code:j.too_big,type:"bigint",maximum:X.value,inclusive:X.inclusive,message:X.message}),W.dirty()}else if(X.kind==="multipleOf"){if(T.data%X.value!==BigInt(0))J=this._getOrReturnCtx(T,J),p(J,{code:j.not_multiple_of,multipleOf:X.value,message:X.message}),W.dirty()}else LT.assertNever(X);return{status:W.value,value:T.data}}_getInvalidInput(T){let $=this._getOrReturnCtx(T);return p($,{code:j.invalid_type,expected:o.bigint,received:$.parsedType}),FT}gte(T,$){return this.setLimit("min",T,!0,i.toString($))}gt(T,$){return this.setLimit("min",T,!1,i.toString($))}lte(T,$){return this.setLimit("max",T,!0,i.toString($))}lt(T,$){return this.setLimit("max",T,!1,i.toString($))}setLimit(T,$,J,W){return new MW({...this._def,checks:[...this._def.checks,{kind:T,value:$,inclusive:J,message:i.toString(W)}]})}_addCheck(T){return new MW({...this._def,checks:[...this._def.checks,T]})}positive(T){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:i.toString(T)})}negative(T){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:i.toString(T)})}nonpositive(T){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:i.toString(T)})}nonnegative(T){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:i.toString(T)})}multipleOf(T,$){return this._addCheck({kind:"multipleOf",value:T,message:i.toString($)})}get minValue(){let T=null;for(let $ of this._def.checks)if($.kind==="min"){if(T===null||$.value>T)T=$.value}return T}get maxValue(){let T=null;for(let $ of this._def.checks)if($.kind==="max"){if(T===null||$.value<T)T=$.value}return T}}MW.create=(T)=>{var $;return new MW({checks:[],typeName:x.ZodBigInt,coerce:($=T===null||T===void 0?void 0:T.coerce)!==null&&$!==void 0?$:!1,...zT(T)})};class p8 extends DT{_parse(T){if(this._def.coerce)T.data=Boolean(T.data);if(this._getType(T)!==o.boolean){let J=this._getOrReturnCtx(T);return p(J,{code:j.invalid_type,expected:o.boolean,received:J.parsedType}),FT}return i$(T.data)}}p8.create=(T)=>{return new p8({typeName:x.ZodBoolean,coerce:(T===null||T===void 0?void 0:T.coerce)||!1,...zT(T)})};class kX extends DT{_parse(T){if(this._def.coerce)T.data=new Date(T.data);if(this._getType(T)!==o.date){let X=this._getOrReturnCtx(T);return p(X,{code:j.invalid_type,expected:o.date,received:X.parsedType}),FT}if(isNaN(T.data.getTime())){let X=this._getOrReturnCtx(T);return p(X,{code:j.invalid_date}),FT}let J=new g$,W=void 0;for(let X of this._def.checks)if(X.kind==="min"){if(T.data.getTime()<X.value)W=this._getOrReturnCtx(T,W),p(W,{code:j.too_small,message:X.message,inclusive:!0,exact:!1,minimum:X.value,type:"date"}),J.dirty()}else if(X.kind==="max"){if(T.data.getTime()>X.value)W=this._getOrReturnCtx(T,W),p(W,{code:j.too_big,message:X.message,inclusive:!0,exact:!1,maximum:X.value,type:"date"}),J.dirty()}else LT.assertNever(X);return{status:J.value,value:new Date(T.data.getTime())}}_addCheck(T){return new kX({...this._def,checks:[...this._def.checks,T]})}min(T,$){return this._addCheck({kind:"min",value:T.getTime(),message:i.toString($)})}max(T,$){return this._addCheck({kind:"max",value:T.getTime(),message:i.toString($)})}get minDate(){let T=null;for(let $ of this._def.checks)if($.kind==="min"){if(T===null||$.value>T)T=$.value}return T!=null?new Date(T):null}get maxDate(){let T=null;for(let $ of this._def.checks)if($.kind==="max"){if(T===null||$.value<T)T=$.value}return T!=null?new Date(T):null}}kX.create=(T)=>{return new kX({checks:[],coerce:(T===null||T===void 0?void 0:T.coerce)||!1,typeName:x.ZodDate,...zT(T)})};class u8 extends DT{_parse(T){if(this._getType(T)!==o.symbol){let J=this._getOrReturnCtx(T);return p(J,{code:j.invalid_type,expected:o.symbol,received:J.parsedType}),FT}return i$(T.data)}}u8.create=(T)=>{return new u8({typeName:x.ZodSymbol,...zT(T)})};class yX extends DT{_parse(T){if(this._getType(T)!==o.undefined){let J=this._getOrReturnCtx(T);return p(J,{code:j.invalid_type,expected:o.undefined,received:J.parsedType}),FT}return i$(T.data)}}yX.create=(T)=>{return new yX({typeName:x.ZodUndefined,...zT(T)})};class IX extends DT{_parse(T){if(this._getType(T)!==o.null){let J=this._getOrReturnCtx(T);return p(J,{code:j.invalid_type,expected:o.null,received:J.parsedType}),FT}return i$(T.data)}}IX.create=(T)=>{return new IX({typeName:x.ZodNull,...zT(T)})};class c8 extends DT{constructor(){super(...arguments);this._any=!0}_parse(T){return i$(T.data)}}c8.create=(T)=>{return new c8({typeName:x.ZodAny,...zT(T)})};class O0 extends DT{constructor(){super(...arguments);this._unknown=!0}_parse(T){return i$(T.data)}}O0.create=(T)=>{return new O0({typeName:x.ZodUnknown,...zT(T)})};class M1 extends DT{_parse(T){let $=this._getOrReturnCtx(T);return p($,{code:j.invalid_type,expected:o.never,received:$.parsedType}),FT}}M1.create=(T)=>{return new M1({typeName:x.ZodNever,...zT(T)})};class o8 extends DT{_parse(T){if(this._getType(T)!==o.undefined){let J=this._getOrReturnCtx(T);return p(J,{code:j.invalid_type,expected:o.void,received:J.parsedType}),FT}return i$(T.data)}}o8.create=(T)=>{return new o8({typeName:x.ZodVoid,...zT(T)})};class oJ extends DT{_parse(T){let{ctx:$,status:J}=this._processInputParams(T),W=this._def;if($.parsedType!==o.array)return p($,{code:j.invalid_type,expected:o.array,received:$.parsedType}),FT;if(W.exactLength!==null){let F=$.data.length>W.exactLength.value,Y=$.data.length<W.exactLength.value;if(F||Y)p($,{code:F?j.too_big:j.too_small,minimum:Y?W.exactLength.value:void 0,maximum:F?W.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:W.exactLength.message}),J.dirty()}if(W.minLength!==null){if($.data.length<W.minLength.value)p($,{code:j.too_small,minimum:W.minLength.value,type:"array",inclusive:!0,exact:!1,message:W.minLength.message}),J.dirty()}if(W.maxLength!==null){if($.data.length>W.maxLength.value)p($,{code:j.too_big,maximum:W.maxLength.value,type:"array",inclusive:!0,exact:!1,message:W.maxLength.message}),J.dirty()}if($.common.async)return Promise.all([...$.data].map((F,Y)=>{return W.type._parseAsync(new qJ($,F,$.path,Y))})).then((F)=>{return g$.mergeArray(J,F)});let X=[...$.data].map((F,Y)=>{return W.type._parseSync(new qJ($,F,$.path,Y))});return g$.mergeArray(J,X)}get element(){return this._def.type}min(T,$){return new oJ({...this._def,minLength:{value:T,message:i.toString($)}})}max(T,$){return new oJ({...this._def,maxLength:{value:T,message:i.toString($)}})}length(T,$){return new oJ({...this._def,exactLength:{value:T,message:i.toString($)}})}nonempty(T){return this.min(1,T)}}oJ.create=(T,$)=>{return new oJ({type:T,minLength:null,maxLength:null,exactLength:null,typeName:x.ZodArray,...zT($)})};function YW(T){if(T instanceof $$){let $={};for(let J in T.shape){let W=T.shape[J];$[J]=KJ.create(YW(W))}return new $$({...T._def,shape:()=>$})}else if(T instanceof oJ)return new oJ({...T._def,type:YW(T.element)});else if(T instanceof KJ)return KJ.create(YW(T.unwrap()));else if(T instanceof m1)return m1.create(YW(T.unwrap()));else if(T instanceof z1)return z1.create(T.items.map(($)=>YW($)));else return T}class $$ extends DT{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let T=this._def.shape(),$=LT.objectKeys(T);return this._cached={shape:T,keys:$}}_parse(T){if(this._getType(T)!==o.object){let H=this._getOrReturnCtx(T);return p(H,{code:j.invalid_type,expected:o.object,received:H.parsedType}),FT}let{status:J,ctx:W}=this._processInputParams(T),{shape:X,keys:F}=this._getCached(),Y=[];if(!(this._def.catchall instanceof M1&&this._def.unknownKeys==="strip")){for(let H in W.data)if(!F.includes(H))Y.push(H)}let G=[];for(let H of F){let M=X[H],z=W.data[H];G.push({key:{status:"valid",value:H},value:M._parse(new qJ(W,z,W.path,H)),alwaysSet:H in W.data})}if(this._def.catchall instanceof M1){let H=this._def.unknownKeys;if(H==="passthrough")for(let M of Y)G.push({key:{status:"valid",value:M},value:{status:"valid",value:W.data[M]}});else if(H==="strict"){if(Y.length>0)p(W,{code:j.unrecognized_keys,keys:Y}),J.dirty()}else if(H==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let H=this._def.catchall;for(let M of Y){let z=W.data[M];G.push({key:{status:"valid",value:M},value:H._parse(new qJ(W,z,W.path,M)),alwaysSet:M in W.data})}}if(W.common.async)return Promise.resolve().then(async()=>{let H=[];for(let M of G){let z=await M.key,A=await M.value;H.push({key:z,value:A,alwaysSet:M.alwaysSet})}return H}).then((H)=>{return g$.mergeObjectSync(J,H)});else return g$.mergeObjectSync(J,G)}get shape(){return this._def.shape()}strict(T){return i.errToObj,new $$({...this._def,unknownKeys:"strict",...T!==void 0?{errorMap:($,J)=>{var W,X,F,Y;let G=(F=(X=(W=this._def).errorMap)===null||X===void 0?void 0:X.call(W,$,J).message)!==null&&F!==void 0?F:J.defaultError;if($.code==="unrecognized_keys")return{message:(Y=i.errToObj(T).message)!==null&&Y!==void 0?Y:G};return{message:G}}}:{}})}strip(){return new $$({...this._def,unknownKeys:"strip"})}passthrough(){return new $$({...this._def,unknownKeys:"passthrough"})}extend(T){return new $$({...this._def,shape:()=>({...this._def.shape(),...T})})}merge(T){return new $$({unknownKeys:T._def.unknownKeys,catchall:T._def.catchall,shape:()=>({...this._def.shape(),...T._def.shape()}),typeName:x.ZodObject})}setKey(T,$){return this.augment({[T]:$})}catchall(T){return new $$({...this._def,catchall:T})}pick(T){let $={};return LT.objectKeys(T).forEach((J)=>{if(T[J]&&this.shape[J])$[J]=this.shape[J]}),new $$({...this._def,shape:()=>$})}omit(T){let $={};return LT.objectKeys(this.shape).forEach((J)=>{if(!T[J])$[J]=this.shape[J]}),new $$({...this._def,shape:()=>$})}deepPartial(){return YW(this)}partial(T){let $={};return LT.objectKeys(this.shape).forEach((J)=>{let W=this.shape[J];if(T&&!T[J])$[J]=W;else $[J]=W.optional()}),new $$({...this._def,shape:()=>$})}required(T){let $={};return LT.objectKeys(this.shape).forEach((J)=>{if(T&&!T[J])$[J]=this.shape[J];else{let X=this.shape[J];while(X instanceof KJ)X=X._def.innerType;$[J]=X}}),new $$({...this._def,shape:()=>$})}keyof(){return _G(LT.objectKeys(this.shape))}}$$.create=(T,$)=>{return new $$({shape:()=>T,unknownKeys:"strip",catchall:M1.create(),typeName:x.ZodObject,...zT($)})};$$.strictCreate=(T,$)=>{return new $$({shape:()=>T,unknownKeys:"strict",catchall:M1.create(),typeName:x.ZodObject,...zT($)})};$$.lazycreate=(T,$)=>{return new $$({shape:T,unknownKeys:"strip",catchall:M1.create(),typeName:x.ZodObject,...zT($)})};class jX extends DT{_parse(T){let{ctx:$}=this._processInputParams(T),J=this._def.options;function W(X){for(let Y of X)if(Y.result.status==="valid")return Y.result;for(let Y of X)if(Y.result.status==="dirty")return $.common.issues.push(...Y.ctx.common.issues),Y.result;let F=X.map((Y)=>new DJ(Y.ctx.common.issues));return p($,{code:j.invalid_union,unionErrors:F}),FT}if($.common.async)return Promise.all(J.map(async(X)=>{let F={...$,common:{...$.common,issues:[]},parent:null};return{result:await X._parseAsync({data:$.data,path:$.path,parent:F}),ctx:F}})).then(W);else{let X=void 0,F=[];for(let G of J){let H={...$,common:{...$.common,issues:[]},parent:null},M=G._parseSync({data:$.data,path:$.path,parent:H});if(M.status==="valid")return M;else if(M.status==="dirty"&&!X)X={result:M,ctx:H};if(H.common.issues.length)F.push(H.common.issues)}if(X)return $.common.issues.push(...X.ctx.common.issues),X.result;let Y=F.map((G)=>new DJ(G));return p($,{code:j.invalid_union,unionErrors:Y}),FT}}get options(){return this._def.options}}jX.create=(T,$)=>{return new jX({options:T,typeName:x.ZodUnion,...zT($)})};var G1=(T)=>{if(T instanceof PX)return G1(T.schema);else if(T instanceof dJ)return G1(T.innerType());else if(T instanceof bX)return[T.value];else if(T instanceof U0)return T.options;else if(T instanceof vX)return LT.objectValues(T.enum);else if(T instanceof hX)return G1(T._def.innerType);else if(T instanceof yX)return[void 0];else if(T instanceof IX)return[null];else if(T instanceof KJ)return[void 0,...G1(T.unwrap())];else if(T instanceof m1)return[null,...G1(T.unwrap())];else if(T instanceof yF)return G1(T.unwrap());else if(T instanceof gX)return G1(T.unwrap());else if(T instanceof mX)return G1(T._def.innerType);else return[]};class kF extends DT{_parse(T){let{ctx:$}=this._processInputParams(T);if($.parsedType!==o.object)return p($,{code:j.invalid_type,expected:o.object,received:$.parsedType}),FT;let J=this.discriminator,W=$.data[J],X=this.optionsMap.get(W);if(!X)return p($,{code:j.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[J]}),FT;if($.common.async)return X._parseAsync({data:$.data,path:$.path,parent:$});else return X._parseSync({data:$.data,path:$.path,parent:$})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(T,$,J){let W=new Map;for(let X of $){let F=G1(X.shape[T]);if(!F.length)throw new Error(`A discriminator value for key \`${T}\` could not be extracted from all schema options`);for(let Y of F){if(W.has(Y))throw new Error(`Discriminator property ${String(T)} has duplicate value ${String(Y)}`);W.set(Y,X)}}return new kF({typeName:x.ZodDiscriminatedUnion,discriminator:T,options:$,optionsMap:W,...zT(J)})}}function qF(T,$){let J=h1(T),W=h1($);if(T===$)return{valid:!0,data:T};else if(J===o.object&&W===o.object){let X=LT.objectKeys($),F=LT.objectKeys(T).filter((G)=>X.indexOf(G)!==-1),Y={...T,...$};for(let G of F){let H=qF(T[G],$[G]);if(!H.valid)return{valid:!1};Y[G]=H.data}return{valid:!0,data:Y}}else if(J===o.array&&W===o.array){if(T.length!==$.length)return{valid:!1};let X=[];for(let F=0;F<T.length;F++){let Y=T[F],G=$[F],H=qF(Y,G);if(!H.valid)return{valid:!1};X.push(H.data)}return{valid:!0,data:X}}else if(J===o.date&&W===o.date&&+T===+$)return{valid:!0,data:T};else return{valid:!1}}class xX extends DT{_parse(T){let{status:$,ctx:J}=this._processInputParams(T),W=(X,F)=>{if(zG(X)||zG(F))return FT;let Y=qF(X.value,F.value);if(!Y.valid)return p(J,{code:j.invalid_intersection_types}),FT;if(AG(X)||AG(F))$.dirty();return{status:$.value,value:Y.data}};if(J.common.async)return Promise.all([this._def.left._parseAsync({data:J.data,path:J.path,parent:J}),this._def.right._parseAsync({data:J.data,path:J.path,parent:J})]).then(([X,F])=>W(X,F));else return W(this._def.left._parseSync({data:J.data,path:J.path,parent:J}),this._def.right._parseSync({data:J.data,path:J.path,parent:J}))}}xX.create=(T,$,J)=>{return new xX({left:T,right:$,typeName:x.ZodIntersection,...zT(J)})};class z1 extends DT{_parse(T){let{status:$,ctx:J}=this._processInputParams(T);if(J.parsedType!==o.array)return p(J,{code:j.invalid_type,expected:o.array,received:J.parsedType}),FT;if(J.data.length<this._def.items.length)return p(J,{code:j.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),FT;if(!this._def.rest&&J.data.length>this._def.items.length)p(J,{code:j.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),$.dirty();let X=[...J.data].map((F,Y)=>{let G=this._def.items[Y]||this._def.rest;if(!G)return null;return G._parse(new qJ(J,F,J.path,Y))}).filter((F)=>!!F);if(J.common.async)return Promise.all(X).then((F)=>{return g$.mergeArray($,F)});else return g$.mergeArray($,X)}get items(){return this._def.items}rest(T){return new z1({...this._def,rest:T})}}z1.create=(T,$)=>{if(!Array.isArray(T))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new z1({items:T,typeName:x.ZodTuple,rest:null,...zT($)})};class d8 extends DT{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(T){let{status:$,ctx:J}=this._processInputParams(T);if(J.parsedType!==o.object)return p(J,{code:j.invalid_type,expected:o.object,received:J.parsedType}),FT;let W=[],X=this._def.keyType,F=this._def.valueType;for(let Y in J.data)W.push({key:X._parse(new qJ(J,Y,J.path,Y)),value:F._parse(new qJ(J,J.data[Y],J.path,Y)),alwaysSet:Y in J.data});if(J.common.async)return g$.mergeObjectAsync($,W);else return g$.mergeObjectSync($,W)}get element(){return this._def.valueType}static create(T,$,J){if($ instanceof DT)return new d8({keyType:T,valueType:$,typeName:x.ZodRecord,...zT(J)});return new d8({keyType:H1.create(),valueType:T,typeName:x.ZodRecord,...zT($)})}}class l8 extends DT{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(T){let{status:$,ctx:J}=this._processInputParams(T);if(J.parsedType!==o.map)return p(J,{code:j.invalid_type,expected:o.map,received:J.parsedType}),FT;let W=this._def.keyType,X=this._def.valueType,F=[...J.data.entries()].map(([Y,G],H)=>{return{key:W._parse(new qJ(J,Y,J.path,[H,"key"])),value:X._parse(new qJ(J,G,J.path,[H,"value"]))}});if(J.common.async){let Y=new Map;return Promise.resolve().then(async()=>{for(let G of F){let H=await G.key,M=await G.value;if(H.status==="aborted"||M.status==="aborted")return FT;if(H.status==="dirty"||M.status==="dirty")$.dirty();Y.set(H.value,M.value)}return{status:$.value,value:Y}})}else{let Y=new Map;for(let G of F){let{key:H,value:M}=G;if(H.status==="aborted"||M.status==="aborted")return FT;if(H.status==="dirty"||M.status==="dirty")$.dirty();Y.set(H.value,M.value)}return{status:$.value,value:Y}}}}l8.create=(T,$,J)=>{return new l8({valueType:$,keyType:T,typeName:x.ZodMap,...zT(J)})};class zW extends DT{_parse(T){let{status:$,ctx:J}=this._processInputParams(T);if(J.parsedType!==o.set)return p(J,{code:j.invalid_type,expected:o.set,received:J.parsedType}),FT;let W=this._def;if(W.minSize!==null){if(J.data.size<W.minSize.value)p(J,{code:j.too_small,minimum:W.minSize.value,type:"set",inclusive:!0,exact:!1,message:W.minSize.message}),$.dirty()}if(W.maxSize!==null){if(J.data.size>W.maxSize.value)p(J,{code:j.too_big,maximum:W.maxSize.value,type:"set",inclusive:!0,exact:!1,message:W.maxSize.message}),$.dirty()}let X=this._def.valueType;function F(G){let H=new Set;for(let M of G){if(M.status==="aborted")return FT;if(M.status==="dirty")$.dirty();H.add(M.value)}return{status:$.value,value:H}}let Y=[...J.data.values()].map((G,H)=>X._parse(new qJ(J,G,J.path,H)));if(J.common.async)return Promise.all(Y).then((G)=>F(G));else return F(Y)}min(T,$){return new zW({...this._def,minSize:{value:T,message:i.toString($)}})}max(T,$){return new zW({...this._def,maxSize:{value:T,message:i.toString($)}})}size(T,$){return this.min(T,$).max(T,$)}nonempty(T){return this.min(1,T)}}zW.create=(T,$)=>{return new zW({valueType:T,minSize:null,maxSize:null,typeName:x.ZodSet,...zT($)})};class ZX extends DT{constructor(){super(...arguments);this.validate=this.implement}_parse(T){let{ctx:$}=this._processInputParams(T);if($.parsedType!==o.function)return p($,{code:j.invalid_type,expected:o.function,received:$.parsedType}),FT;function J(Y,G){return ZF({data:Y,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,CF(),qX].filter((H)=>!!H),issueData:{code:j.invalid_arguments,argumentsError:G}})}function W(Y,G){return ZF({data:Y,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,CF(),qX].filter((H)=>!!H),issueData:{code:j.invalid_return_type,returnTypeError:G}})}let X={errorMap:$.common.contextualErrorMap},F=$.data;if(this._def.returns instanceof AW){let Y=this;return i$(async function(...G){let H=new DJ([]),M=await Y._def.args.parseAsync(G,X).catch((w)=>{throw H.addIssue(J(G,w)),H}),z=await Reflect.apply(F,this,M);return await Y._def.returns._def.type.parseAsync(z,X).catch((w)=>{throw H.addIssue(W(z,w)),H})})}else{let Y=this;return i$(function(...G){let H=Y._def.args.safeParse(G,X);if(!H.success)throw new DJ([J(G,H.error)]);let M=Reflect.apply(F,this,H.data),z=Y._def.returns.safeParse(M,X);if(!z.success)throw new DJ([W(M,z.error)]);return z.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...T){return new ZX({...this._def,args:z1.create(T).rest(O0.create())})}returns(T){return new ZX({...this._def,returns:T})}implement(T){return this.parse(T)}strictImplement(T){return this.parse(T)}static create(T,$,J){return new ZX({args:T?T:z1.create([]).rest(O0.create()),returns:$||O0.create(),typeName:x.ZodFunction,...zT(J)})}}class PX extends DT{get schema(){return this._def.getter()}_parse(T){let{ctx:$}=this._processInputParams(T);return this._def.getter()._parse({data:$.data,path:$.path,parent:$})}}PX.create=(T,$)=>{return new PX({getter:T,typeName:x.ZodLazy,...zT($)})};class bX extends DT{_parse(T){if(T.data!==this._def.value){let $=this._getOrReturnCtx(T);return p($,{received:$.data,code:j.invalid_literal,expected:this._def.value}),FT}return{status:"valid",value:T.data}}get value(){return this._def.value}}bX.create=(T,$)=>{return new bX({value:T,typeName:x.ZodLiteral,...zT($)})};function _G(T,$){return new U0({values:T,typeName:x.ZodEnum,...zT($)})}class U0 extends DT{constructor(){super(...arguments);NX.set(this,void 0)}_parse(T){if(typeof T.data!=="string"){let $=this._getOrReturnCtx(T),J=this._def.values;return p($,{expected:LT.joinValues(J),received:$.parsedType,code:j.invalid_type}),FT}if(!g8(this,NX,"f"))QG(this,NX,new Set(this._def.values),"f");if(!g8(this,NX,"f").has(T.data)){let $=this._getOrReturnCtx(T),J=this._def.values;return p($,{received:$.data,code:j.invalid_enum_value,options:J}),FT}return i$(T.data)}get options(){return this._def.values}get enum(){let T={};for(let $ of this._def.values)T[$]=$;return T}get Values(){let T={};for(let $ of this._def.values)T[$]=$;return T}get Enum(){let T={};for(let $ of this._def.values)T[$]=$;return T}extract(T,$=this._def){return U0.create(T,{...this._def,...$})}exclude(T,$=this._def){return U0.create(this.options.filter((J)=>!T.includes(J)),{...this._def,...$})}}NX=new WeakMap;U0.create=_G;class vX extends DT{constructor(){super(...arguments);CX.set(this,void 0)}_parse(T){let $=LT.getValidEnumValues(this._def.values),J=this._getOrReturnCtx(T);if(J.parsedType!==o.string&&J.parsedType!==o.number){let W=LT.objectValues($);return p(J,{expected:LT.joinValues(W),received:J.parsedType,code:j.invalid_type}),FT}if(!g8(this,CX,"f"))QG(this,CX,new Set(LT.getValidEnumValues(this._def.values)),"f");if(!g8(this,CX,"f").has(T.data)){let W=LT.objectValues($);return p(J,{received:J.data,code:j.invalid_enum_value,options:W}),FT}return i$(T.data)}get enum(){return this._def.values}}CX=new WeakMap;vX.create=(T,$)=>{return new vX({values:T,typeName:x.ZodNativeEnum,...zT($)})};class AW extends DT{unwrap(){return this._def.type}_parse(T){let{ctx:$}=this._processInputParams(T);if($.parsedType!==o.promise&&$.common.async===!1)return p($,{code:j.invalid_type,expected:o.promise,received:$.parsedType}),FT;let J=$.parsedType===o.promise?$.data:Promise.resolve($.data);return i$(J.then((W)=>{return this._def.type.parseAsync(W,{path:$.path,errorMap:$.common.contextualErrorMap})}))}}AW.create=(T,$)=>{return new AW({type:T,typeName:x.ZodPromise,...zT($)})};class dJ extends DT{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===x.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(T){let{status:$,ctx:J}=this._processInputParams(T),W=this._def.effect||null,X={addIssue:(F)=>{if(p(J,F),F.fatal)$.abort();else $.dirty()},get path(){return J.path}};if(X.addIssue=X.addIssue.bind(X),W.type==="preprocess"){let F=W.transform(J.data,X);if(J.common.async)return Promise.resolve(F).then(async(Y)=>{if($.value==="aborted")return FT;let G=await this._def.schema._parseAsync({data:Y,path:J.path,parent:J});if(G.status==="aborted")return FT;if(G.status==="dirty")return fX(G.value);if($.value==="dirty")return fX(G.value);return G});else{if($.value==="aborted")return FT;let Y=this._def.schema._parseSync({data:F,path:J.path,parent:J});if(Y.status==="aborted")return FT;if(Y.status==="dirty")return fX(Y.value);if($.value==="dirty")return fX(Y.value);return Y}}if(W.type==="refinement"){let F=(Y)=>{let G=W.refinement(Y,X);if(J.common.async)return Promise.resolve(G);if(G instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return Y};if(J.common.async===!1){let Y=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(Y.status==="aborted")return FT;if(Y.status==="dirty")$.dirty();return F(Y.value),{status:$.value,value:Y.value}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((Y)=>{if(Y.status==="aborted")return FT;if(Y.status==="dirty")$.dirty();return F(Y.value).then(()=>{return{status:$.value,value:Y.value}})})}if(W.type==="transform")if(J.common.async===!1){let F=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(!GW(F))return F;let Y=W.transform(F.value,X);if(Y instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:$.value,value:Y}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((F)=>{if(!GW(F))return F;return Promise.resolve(W.transform(F.value,X)).then((Y)=>({status:$.value,value:Y}))});LT.assertNever(W)}}dJ.create=(T,$,J)=>{return new dJ({schema:T,typeName:x.ZodEffects,effect:$,...zT(J)})};dJ.createWithPreprocess=(T,$,J)=>{return new dJ({schema:$,effect:{type:"preprocess",transform:T},typeName:x.ZodEffects,...zT(J)})};class KJ extends DT{_parse(T){if(this._getType(T)===o.undefined)return i$(void 0);return this._def.innerType._parse(T)}unwrap(){return this._def.innerType}}KJ.create=(T,$)=>{return new KJ({innerType:T,typeName:x.ZodOptional,...zT($)})};class m1 extends DT{_parse(T){if(this._getType(T)===o.null)return i$(null);return this._def.innerType._parse(T)}unwrap(){return this._def.innerType}}m1.create=(T,$)=>{return new m1({innerType:T,typeName:x.ZodNullable,...zT($)})};class hX extends DT{_parse(T){let{ctx:$}=this._processInputParams(T),J=$.data;if($.parsedType===o.undefined)J=this._def.defaultValue();return this._def.innerType._parse({data:J,path:$.path,parent:$})}removeDefault(){return this._def.innerType}}hX.create=(T,$)=>{return new hX({innerType:T,typeName:x.ZodDefault,defaultValue:typeof $.default==="function"?$.default:()=>$.default,...zT($)})};class mX extends DT{_parse(T){let{ctx:$}=this._processInputParams(T),J={...$,common:{...$.common,issues:[]}},W=this._def.innerType._parse({data:J.data,path:J.path,parent:{...J}});if(m8(W))return W.then((X)=>{return{status:"valid",value:X.status==="valid"?X.value:this._def.catchValue({get error(){return new DJ(J.common.issues)},input:J.data})}});else return{status:"valid",value:W.status==="valid"?W.value:this._def.catchValue({get error(){return new DJ(J.common.issues)},input:J.data})}}removeCatch(){return this._def.innerType}}mX.create=(T,$)=>{return new mX({innerType:T,typeName:x.ZodCatch,catchValue:typeof $.catch==="function"?$.catch:()=>$.catch,...zT($)})};class n8 extends DT{_parse(T){if(this._getType(T)!==o.nan){let J=this._getOrReturnCtx(T);return p(J,{code:j.invalid_type,expected:o.nan,received:J.parsedType}),FT}return{status:"valid",value:T.data}}}n8.create=(T)=>{return new n8({typeName:x.ZodNaN,...zT(T)})};var Pj=Symbol("zod_brand");class yF extends DT{_parse(T){let{ctx:$}=this._processInputParams(T),J=$.data;return this._def.type._parse({data:J,path:$.path,parent:$})}unwrap(){return this._def.type}}class i8 extends DT{_parse(T){let{status:$,ctx:J}=this._processInputParams(T);if(J.common.async)return(async()=>{let X=await this._def.in._parseAsync({data:J.data,path:J.path,parent:J});if(X.status==="aborted")return FT;if(X.status==="dirty")return $.dirty(),fX(X.value);else return this._def.out._parseAsync({data:X.value,path:J.path,parent:J})})();else{let W=this._def.in._parseSync({data:J.data,path:J.path,parent:J});if(W.status==="aborted")return FT;if(W.status==="dirty")return $.dirty(),{status:"dirty",value:W.value};else return this._def.out._parseSync({data:W.value,path:J.path,parent:J})}}static create(T,$){return new i8({in:T,out:$,typeName:x.ZodPipeline})}}class gX extends DT{_parse(T){let $=this._def.innerType._parse(T),J=(W)=>{if(GW(W))W.value=Object.freeze(W.value);return W};return m8($)?$.then((W)=>J(W)):J($)}unwrap(){return this._def.innerType}}gX.create=(T,$)=>{return new gX({innerType:T,typeName:x.ZodReadonly,...zT($)})};var bj={object:$$.lazycreate},x;(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"})(x||(x={}));var vj=H1.create,hj=HW.create,mj=n8.create,gj=MW.create,pj=p8.create,uj=kX.create,cj=u8.create,oj=yX.create,dj=IX.create,lj=c8.create,nj=O0.create,ij=M1.create,tj=o8.create,rj=oJ.create,aj=$$.create,sj=$$.strictCreate,ej=jX.create,Tx=kF.create,$x=xX.create,Jx=z1.create,Wx=d8.create,Xx=l8.create,Fx=zW.create,Yx=ZX.create,Gx=PX.create,Hx=bX.create,Mx=U0.create,zx=vX.create,Ax=AW.create,wx=dJ.create,Qx=KJ.create,Ox=m1.create,Ux=dJ.createWithPreprocess,_x=i8.create;function DG(){return{}}function KG(T,$){let J={type:"array"};if(T.type?._def&&T.type?._def?.typeName!==x.ZodAny)J.items=WT(T.type._def,{...$,currentPath:[...$.currentPath,"items"]});if(T.minLength)ET(J,"minItems",T.minLength.value,T.minLength.message,$);if(T.maxLength)ET(J,"maxItems",T.maxLength.value,T.maxLength.message,$);if(T.exactLength)ET(J,"minItems",T.exactLength.value,T.exactLength.message,$),ET(J,"maxItems",T.exactLength.value,T.exactLength.message,$);return J}function SG(T,$){let J={type:"integer",format:"int64"};if(!T.checks)return J;for(let W of T.checks)switch(W.kind){case"min":if($.target==="jsonSchema7")if(W.inclusive)ET(J,"minimum",W.value,W.message,$);else ET(J,"exclusiveMinimum",W.value,W.message,$);else{if(!W.inclusive)J.exclusiveMinimum=!0;ET(J,"minimum",W.value,W.message,$)}break;case"max":if($.target==="jsonSchema7")if(W.inclusive)ET(J,"maximum",W.value,W.message,$);else ET(J,"exclusiveMaximum",W.value,W.message,$);else{if(!W.inclusive)J.exclusiveMaximum=!0;ET(J,"maximum",W.value,W.message,$)}break;case"multipleOf":ET(J,"multipleOf",W.value,W.message,$);break}return J}function VG(){return{type:"boolean"}}function t8(T,$){return WT(T.type._def,$)}var EG=(T,$)=>{return WT(T.innerType._def,$)};function IF(T,$,J){let W=J??$.dateStrategy;if(Array.isArray(W))return{anyOf:W.map((X,F)=>IF(T,$,X))};switch(W){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return j_(T,$)}}var j_=(T,$)=>{let J={type:"integer",format:"unix-time"};if($.target==="openApi3")return J;for(let W of T.checks)switch(W.kind){case"min":ET(J,"minimum",W.value,W.message,$);break;case"max":ET(J,"maximum",W.value,W.message,$);break}return J};function RG(T,$){return{...WT(T.innerType._def,$),default:T.defaultValue()}}function LG(T,$){return $.effectStrategy==="input"?WT(T.schema._def,$):{}}function BG(T){return{type:"string",enum:Array.from(T.values)}}var x_=(T)=>{if("type"in T&&T.type==="string")return!1;return"allOf"in T};function fG(T,$){let J=[WT(T.left._def,{...$,currentPath:[...$.currentPath,"allOf","0"]}),WT(T.right._def,{...$,currentPath:[...$.currentPath,"allOf","1"]})].filter((F)=>!!F),W=$.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,X=[];return J.forEach((F)=>{if(x_(F)){if(X.push(...F.allOf),F.unevaluatedProperties===void 0)W=void 0}else{let Y=F;if("additionalProperties"in F&&F.additionalProperties===!1){let{additionalProperties:G,...H}=F;Y=H}else W=void 0;X.push(Y)}}),X.length?{allOf:X,...W}:void 0}function NG(T,$){let J=typeof T.value;if(J!=="bigint"&&J!=="number"&&J!=="boolean"&&J!=="string")return{type:Array.isArray(T.value)?"array":"object"};if($.target==="openApi3")return{type:J==="bigint"?"integer":J,enum:[T.value]};return{type:J==="bigint"?"integer":J,const:T.value}}var jF=void 0,kJ={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(jF===void 0)jF=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return jF},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])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,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})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function r8(T,$){let J={type:"string"};if(T.checks)for(let W of T.checks)switch(W.kind){case"min":ET(J,"minLength",typeof J.minLength==="number"?Math.max(J.minLength,W.value):W.value,W.message,$);break;case"max":ET(J,"maxLength",typeof J.maxLength==="number"?Math.min(J.maxLength,W.value):W.value,W.message,$);break;case"email":switch($.emailStrategy){case"format:email":yJ(J,"email",W.message,$);break;case"format:idn-email":yJ(J,"idn-email",W.message,$);break;case"pattern:zod":p$(J,kJ.email,W.message,$);break}break;case"url":yJ(J,"uri",W.message,$);break;case"uuid":yJ(J,"uuid",W.message,$);break;case"regex":p$(J,W.regex,W.message,$);break;case"cuid":p$(J,kJ.cuid,W.message,$);break;case"cuid2":p$(J,kJ.cuid2,W.message,$);break;case"startsWith":p$(J,RegExp(`^${xF(W.value,$)}`),W.message,$);break;case"endsWith":p$(J,RegExp(`${xF(W.value,$)}$`),W.message,$);break;case"datetime":yJ(J,"date-time",W.message,$);break;case"date":yJ(J,"date",W.message,$);break;case"time":yJ(J,"time",W.message,$);break;case"duration":yJ(J,"duration",W.message,$);break;case"length":ET(J,"minLength",typeof J.minLength==="number"?Math.max(J.minLength,W.value):W.value,W.message,$),ET(J,"maxLength",typeof J.maxLength==="number"?Math.min(J.maxLength,W.value):W.value,W.message,$);break;case"includes":{p$(J,RegExp(xF(W.value,$)),W.message,$);break}case"ip":{if(W.version!=="v6")yJ(J,"ipv4",W.message,$);if(W.version!=="v4")yJ(J,"ipv6",W.message,$);break}case"base64url":p$(J,kJ.base64url,W.message,$);break;case"jwt":p$(J,kJ.jwt,W.message,$);break;case"cidr":{if(W.version!=="v6")p$(J,kJ.ipv4Cidr,W.message,$);if(W.version!=="v4")p$(J,kJ.ipv6Cidr,W.message,$);break}case"emoji":p$(J,kJ.emoji(),W.message,$);break;case"ulid":{p$(J,kJ.ulid,W.message,$);break}case"base64":{switch($.base64Strategy){case"format:binary":{yJ(J,"binary",W.message,$);break}case"contentEncoding:base64":{ET(J,"contentEncoding","base64",W.message,$);break}case"pattern:zod":{p$(J,kJ.base64,W.message,$);break}}break}case"nanoid":p$(J,kJ.nanoid,W.message,$);case"toLowerCase":case"toUpperCase":case"trim":break;default:((X)=>{})(W)}return J}function xF(T,$){return $.patternStrategy==="escape"?b_(T):T}var P_=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function b_(T){let $="";for(let J=0;J<T.length;J++){if(!P_.has(T[J]))$+="\\";$+=T[J]}return $}function yJ(T,$,J,W){if(T.format||T.anyOf?.some((X)=>X.format)){if(!T.anyOf)T.anyOf=[];if(T.format){if(T.anyOf.push({format:T.format,...T.errorMessage&&W.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:$,...J&&W.errorMessages&&{errorMessage:{format:J}}})}else ET(T,"format",$,J,W)}function p$(T,$,J,W){if(T.pattern||T.allOf?.some((X)=>X.pattern)){if(!T.allOf)T.allOf=[];if(T.pattern){if(T.allOf.push({pattern:T.pattern,...T.errorMessage&&W.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:CG($,W),...J&&W.errorMessages&&{errorMessage:{pattern:J}}})}else ET(T,"pattern",CG($,W),J,W)}function CG(T,$){if(!$.applyRegexFlags||!T.flags)return T.source;let J={i:T.flags.includes("i"),m:T.flags.includes("m"),s:T.flags.includes("s")},W=J.i?T.source.toLowerCase():T.source,X="",F=!1,Y=!1,G=!1;for(let H=0;H<W.length;H++){if(F){X+=W[H],F=!1;continue}if(J.i){if(Y){if(W[H].match(/[a-z]/)){if(G)X+=W[H],X+=`${W[H-2]}-${W[H]}`.toUpperCase(),G=!1;else if(W[H+1]==="-"&&W[H+2]?.match(/[a-z]/))X+=W[H],G=!0;else X+=`${W[H]}${W[H].toUpperCase()}`;continue}}else if(W[H].match(/[a-z]/)){X+=`[${W[H]}${W[H].toUpperCase()}]`;continue}}if(J.m){if(W[H]==="^"){X+=`(^|(?<=[\r
17
- ]))`;continue}else if(W[H]==="$"){X+=`($|(?=[\r
18
- ]))`;continue}}if(J.s&&W[H]==="."){X+=Y?`${W[H]}\r
19
- `:`[${W[H]}\r
20
- ]`;continue}if(X+=W[H],W[H]==="\\")F=!0;else if(Y&&W[H]==="]")Y=!1;else if(!Y&&W[H]==="[")Y=!0}try{new RegExp(X)}catch{return console.warn(`Could not convert regex pattern at ${$.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),T.source}return X}function a8(T,$){if($.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if($.target==="openApi3"&&T.keyType?._def.typeName===x.ZodEnum)return{type:"object",required:T.keyType._def.values,properties:T.keyType._def.values.reduce((W,X)=>({...W,[X]:WT(T.valueType._def,{...$,currentPath:[...$.currentPath,"properties",X]})??{}}),{}),additionalProperties:$.rejectedAdditionalProperties};let J={type:"object",additionalProperties:WT(T.valueType._def,{...$,currentPath:[...$.currentPath,"additionalProperties"]})??$.allowedAdditionalProperties};if($.target==="openApi3")return J;if(T.keyType?._def.typeName===x.ZodString&&T.keyType._def.checks?.length){let{type:W,...X}=r8(T.keyType._def,$);return{...J,propertyNames:X}}else if(T.keyType?._def.typeName===x.ZodEnum)return{...J,propertyNames:{enum:T.keyType._def.values}};else if(T.keyType?._def.typeName===x.ZodBranded&&T.keyType._def.type._def.typeName===x.ZodString&&T.keyType._def.type._def.checks?.length){let{type:W,...X}=t8(T.keyType._def,$);return{...J,propertyNames:X}}return J}function ZG(T,$){if($.mapStrategy==="record")return a8(T,$);let J=WT(T.keyType._def,{...$,currentPath:[...$.currentPath,"items","items","0"]})||{},W=WT(T.valueType._def,{...$,currentPath:[...$.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[J,W],minItems:2,maxItems:2}}}function qG(T){let $=T.values,W=Object.keys(T.values).filter((F)=>{return typeof $[$[F]]!=="number"}).map((F)=>$[F]),X=Array.from(new Set(W.map((F)=>typeof F)));return{type:X.length===1?X[0]==="string"?"string":"number":["string","number"],enum:W}}function kG(){return{not:{}}}function yG(T){return T.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var pX={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function jG(T,$){if($.target==="openApi3")return IG(T,$);let J=T.options instanceof Map?Array.from(T.options.values()):T.options;if(J.every((W)=>(W._def.typeName in pX)&&(!W._def.checks||!W._def.checks.length))){let W=J.reduce((X,F)=>{let Y=pX[F._def.typeName];return Y&&!X.includes(Y)?[...X,Y]:X},[]);return{type:W.length>1?W:W[0]}}else if(J.every((W)=>W._def.typeName==="ZodLiteral"&&!W.description)){let W=J.reduce((X,F)=>{let Y=typeof F._def.value;switch(Y){case"string":case"number":case"boolean":return[...X,Y];case"bigint":return[...X,"integer"];case"object":if(F._def.value===null)return[...X,"null"];case"symbol":case"undefined":case"function":default:return X}},[]);if(W.length===J.length){let X=W.filter((F,Y,G)=>G.indexOf(F)===Y);return{type:X.length>1?X:X[0],enum:J.reduce((F,Y)=>{return F.includes(Y._def.value)?F:[...F,Y._def.value]},[])}}}else if(J.every((W)=>W._def.typeName==="ZodEnum"))return{type:"string",enum:J.reduce((W,X)=>[...W,...X._def.values.filter((F)=>!W.includes(F))],[])};return IG(T,$)}var IG=(T,$)=>{let J=(T.options instanceof Map?Array.from(T.options.values()):T.options).map((W,X)=>WT(W._def,{...$,currentPath:[...$.currentPath,"anyOf",`${X}`]})).filter((W)=>!!W&&(!$.strictUnions||typeof W==="object"&&Object.keys(W).length>0));return J.length?{anyOf:J}:void 0};function xG(T,$){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(T.innerType._def.typeName)&&(!T.innerType._def.checks||!T.innerType._def.checks.length)){if($.target==="openApi3")return{type:pX[T.innerType._def.typeName],nullable:!0};return{type:[pX[T.innerType._def.typeName],"null"]}}if($.target==="openApi3"){let W=WT(T.innerType._def,{...$,currentPath:[...$.currentPath]});if(W&&"$ref"in W)return{allOf:[W],nullable:!0};return W&&{...W,nullable:!0}}let J=WT(T.innerType._def,{...$,currentPath:[...$.currentPath,"anyOf","0"]});return J&&{anyOf:[J,{type:"null"}]}}function PG(T,$){let J={type:"number"};if(!T.checks)return J;for(let W of T.checks)switch(W.kind){case"int":J.type="integer",fF(J,"type",W.message,$);break;case"min":if($.target==="jsonSchema7")if(W.inclusive)ET(J,"minimum",W.value,W.message,$);else ET(J,"exclusiveMinimum",W.value,W.message,$);else{if(!W.inclusive)J.exclusiveMinimum=!0;ET(J,"minimum",W.value,W.message,$)}break;case"max":if($.target==="jsonSchema7")if(W.inclusive)ET(J,"maximum",W.value,W.message,$);else ET(J,"exclusiveMaximum",W.value,W.message,$);else{if(!W.inclusive)J.exclusiveMaximum=!0;ET(J,"maximum",W.value,W.message,$)}break;case"multipleOf":ET(J,"multipleOf",W.value,W.message,$);break}return J}function bG(T,$){let J=$.target==="openAi",W={type:"object",properties:{}},X=[],F=T.shape();for(let G in F){let H=F[G];if(H===void 0||H._def===void 0)continue;let M=h_(H);if(M&&J){if(H instanceof KJ)H=H._def.innerType;if(!H.isNullable())H=H.nullable();M=!1}let z=WT(H._def,{...$,currentPath:[...$.currentPath,"properties",G],propertyPath:[...$.currentPath,"properties",G]});if(z===void 0)continue;if(W.properties[G]=z,!M)X.push(G)}if(X.length)W.required=X;let Y=v_(T,$);if(Y!==void 0)W.additionalProperties=Y;return W}function v_(T,$){if(T.catchall._def.typeName!=="ZodNever")return WT(T.catchall._def,{...$,currentPath:[...$.currentPath,"additionalProperties"]});switch(T.unknownKeys){case"passthrough":return $.allowedAdditionalProperties;case"strict":return $.rejectedAdditionalProperties;case"strip":return $.removeAdditionalStrategy==="strict"?$.allowedAdditionalProperties:$.rejectedAdditionalProperties}}function h_(T){try{return T.isOptional()}catch{return!0}}var vG=(T,$)=>{if($.currentPath.toString()===$.propertyPath?.toString())return WT(T.innerType._def,$);let J=WT(T.innerType._def,{...$,currentPath:[...$.currentPath,"anyOf","1"]});return J?{anyOf:[{not:{}},J]}:{}};var hG=(T,$)=>{if($.pipeStrategy==="input")return WT(T.in._def,$);else if($.pipeStrategy==="output")return WT(T.out._def,$);let J=WT(T.in._def,{...$,currentPath:[...$.currentPath,"allOf","0"]}),W=WT(T.out._def,{...$,currentPath:[...$.currentPath,"allOf",J?"1":"0"]});return{allOf:[J,W].filter((X)=>X!==void 0)}};function mG(T,$){return WT(T.type._def,$)}function gG(T,$){let W={type:"array",uniqueItems:!0,items:WT(T.valueType._def,{...$,currentPath:[...$.currentPath,"items"]})};if(T.minSize)ET(W,"minItems",T.minSize.value,T.minSize.message,$);if(T.maxSize)ET(W,"maxItems",T.maxSize.value,T.maxSize.message,$);return W}function pG(T,$){if(T.rest)return{type:"array",minItems:T.items.length,items:T.items.map((J,W)=>WT(J._def,{...$,currentPath:[...$.currentPath,"items",`${W}`]})).reduce((J,W)=>W===void 0?J:[...J,W],[]),additionalItems:WT(T.rest._def,{...$,currentPath:[...$.currentPath,"additionalItems"]})};else return{type:"array",minItems:T.items.length,maxItems:T.items.length,items:T.items.map((J,W)=>WT(J._def,{...$,currentPath:[...$.currentPath,"items",`${W}`]})).reduce((J,W)=>W===void 0?J:[...J,W],[])}}function uG(){return{not:{}}}function cG(){return{}}var oG=(T,$)=>{return WT(T.innerType._def,$)};var dG=(T,$,J)=>{switch($){case x.ZodString:return r8(T,J);case x.ZodNumber:return PG(T,J);case x.ZodObject:return bG(T,J);case x.ZodBigInt:return SG(T,J);case x.ZodBoolean:return VG();case x.ZodDate:return IF(T,J);case x.ZodUndefined:return uG();case x.ZodNull:return yG(J);case x.ZodArray:return KG(T,J);case x.ZodUnion:case x.ZodDiscriminatedUnion:return jG(T,J);case x.ZodIntersection:return fG(T,J);case x.ZodTuple:return pG(T,J);case x.ZodRecord:return a8(T,J);case x.ZodLiteral:return NG(T,J);case x.ZodEnum:return BG(T);case x.ZodNativeEnum:return qG(T);case x.ZodNullable:return xG(T,J);case x.ZodOptional:return vG(T,J);case x.ZodMap:return ZG(T,J);case x.ZodSet:return gG(T,J);case x.ZodLazy:return()=>T.getter()._def;case x.ZodPromise:return mG(T,J);case x.ZodNaN:case x.ZodNever:return kG();case x.ZodEffects:return LG(T,J);case x.ZodAny:return DG();case x.ZodUnknown:return cG();case x.ZodDefault:return RG(T,J);case x.ZodBranded:return t8(T,J);case x.ZodReadonly:return oG(T,J);case x.ZodCatch:return EG(T,J);case x.ZodPipeline:return hG(T,J);case x.ZodFunction:case x.ZodVoid:case x.ZodSymbol:return;default:return((W)=>{return})($)}};function WT(T,$,J=!1){let W=$.seen.get(T);if($.override){let G=$.override?.(T,$,W,J);if(G!==YG)return G}if(W&&!J){let G=m_(W,$);if(G!==void 0)return G}let X={def:T,path:$.currentPath,jsonSchema:void 0};$.seen.set(T,X);let F=dG(T,T.typeName,$),Y=typeof F==="function"?WT(F(),$):F;if(Y)p_(T,$,Y);if($.postProcess){let G=$.postProcess(Y,T,$);return X.jsonSchema=Y,G}return X.jsonSchema=Y,Y}var m_=(T,$)=>{switch($.$refStrategy){case"root":return{$ref:T.path.join("/")};case"relative":return{$ref:g_($.currentPath,T.path)};case"none":case"seen":{if(T.path.length<$.currentPath.length&&T.path.every((J,W)=>$.currentPath[W]===J))return console.warn(`Recursive reference detected at ${$.currentPath.join("/")}! Defaulting to any`),{};return $.$refStrategy==="seen"?{}:void 0}}},g_=(T,$)=>{let J=0;for(;J<T.length&&J<$.length;J++)if(T[J]!==$[J])break;return[(T.length-J).toString(),...$.slice(J)].join("/")},p_=(T,$,J)=>{if(T.description){if(J.description=T.description,$.markdownDescription)J.markdownDescription=T.description}return J};var lG=(T,$)=>{let J=HG($),W=typeof $==="object"&&$.definitions?Object.entries($.definitions).reduce((H,[M,z])=>({...H,[M]:WT(z._def,{...J,currentPath:[...J.basePath,J.definitionPath,M]},!0)??{}}),{}):void 0,X=typeof $==="string"?$:$?.nameStrategy==="title"?void 0:$?.name,F=WT(T._def,X===void 0?J:{...J,currentPath:[...J.basePath,J.definitionPath,X]},!1)??{},Y=typeof $==="object"&&$.name!==void 0&&$.nameStrategy==="title"?$.name:void 0;if(Y!==void 0)F.title=Y;let G=X===void 0?W?{...F,[J.definitionPath]:W}:F:{$ref:[...J.$refStrategy==="relative"?[]:J.basePath,J.definitionPath,X].join("/"),[J.definitionPath]:{...W,[X]:F}};if(J.target==="jsonSchema7")G.$schema="http://json-schema.org/draft-07/schema#";else if(J.target==="jsonSchema2019-09"||J.target==="openAi")G.$schema="https://json-schema.org/draft/2019-09/schema#";if(J.target==="openAi"&&(("anyOf"in G)||("oneOf"in G)||("allOf"in G)||("type"in G)&&Array.isArray(G.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return G};var nG=lG;function iG(T,$){return function J({schema:W,fallback:X,toJsonSchema:F=nG}){let Y=F(W);return async function G(H,M=3){let z,A=[];while(A.length<M){z=await T(H,Y,X,A);let w=await W["~standard"].validate(z);if("value"in w)return w.value;$?.warn(`safegen failed to generate well-formed data.
3
+ var N_=Object.create;var{getPrototypeOf:B_,defineProperty:K9,getOwnPropertyNames:R_}=Object;var Z_=Object.prototype.hasOwnProperty;var S_=(W,$,X)=>{X=W!=null?N_(B_(W)):{};let Y=$||!W||!W.__esModule?K9(X,"default",{value:W,enumerable:!0}):X;for(let J of R_(W))if(!Z_.call(Y,J))K9(Y,J,{get:()=>W[J],enumerable:!0});return Y};var q_=(W,$)=>()=>($||W(($={exports:{}}).exports,$),$.exports);var C_=(W,$)=>{for(var X in $)K9(W,X,{get:$[X],enumerable:!0,configurable:!0,set:(Y)=>$[X]=()=>Y})};var sE=(W,$)=>()=>(W&&($=W(W=0)),$);var GG=import.meta.require;var ZH=q_((GP,RH)=>{var i4=GG("os"),n4=GG("path");function BH(W){let $=process.env.XDG_CACHE_HOME||n4.join(i4.homedir(),".cache");return n4.join($,W)}function IV(W){return n4.join(i4.homedir(),"Library","Caches",W)}function jV(W){let $=process.env.LOCALAPPDATA||n4.join(i4.homedir(),"AppData","Local");return n4.join($,W,"Cache")}var fV=function(){switch(i4.platform()){case"darwin":return IV;case"win32":return jV;case"aix":case"android":case"freebsd":case"linux":case"netbsd":case"openbsd":case"sunos":return BH;default:return console.error(`(node:${process.pid}) [cachedir] Warning: the platform "${i4.platform()}" is not currently supported by node-cachedir, falling back to "posix". Please file an issue with your platform here: https://github.com/LinusU/node-cachedir/issues/new`),BH}}();RH.exports=function W($){if(typeof $!=="string")throw new TypeError("id is not a string");if($.length===0)throw new Error("id cannot be empty");if(/[^0-9a-zA-Z-]/.test($))throw new Error("id cannot contain special characters");return fV($)}});class m$ extends Promise{fate;resolve;reject;done=!1;constructor(W){let $,X;super((Y,J)=>{$=Y,X=J});this.resolve=$,this.reject=X,this.use(W instanceof Promise?W:new Promise(W))}pass(W,$){if(W===this.fate)this.resolve($),this.done=!0}fail(W,$){if(W===this.fate)this.reject($),this.done=!0}use(W){if(W instanceof Promise){let $=W;this.fate=$,$.then((X)=>{this.pass($,X)},(X)=>{this.fail($,X)})}else this.resolve(W),this.fate=void 0}}var XN=(W,$,X=QG.STORE)=>{return HG(X,{key:`${W.key}:JSON`,get:({get:Y})=>$.toJson(Y(W)),set:({set:Y},J)=>{Y(W,$.fromJson(J))}})};function GN(W,$,X){return L9(W,{key:`${$.key}:JSON`,get:(J)=>({get:G})=>{let H=G($,J);return X.toJson(H)},set:(J)=>({set:G},H)=>{G($,J,X.fromJson(H))}},["mutable","json"])}var p$=(W)=>JSON.parse(W),Z1=(W)=>JSON.stringify(W),QN=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];function J0(W){while(W.child!==null)W=W.child;return W}class t6{_buffer;_index=0;constructor(W){let $;if(typeof W==="number")$=W;else $=W.length;this._buffer=Array.from({length:$})}get buffer(){return this._buffer}get index(){return this._index}add(W){this._buffer[this._index]=W,this._index=(this._index+1)%this._buffer.length}copy(){let W=new t6([...this._buffer]);return W._index=this._index,W}}var k_={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function zG(W,$){let X=Z1($),Y=`${W.key}(${X})`,J=k_[W.type],G={key:Y,type:J};return Object.assign(G,{family:{key:W.key,subKey:X}}),Object.assign(G,{counterfeit:!0}),G}function u$(W){let $={key:W.key,type:W.type};if("family"in W)$.family=W.family;return $}var A9=(W)=>($,X,Y,J,...G)=>{console[W](`${$} ${X} "${Y}" ${J}`,...G)},I_={error:A9("error"),info:A9("info"),warn:A9("warn")};class E9{logLevel;filter;logger;constructor(W,$,X=I_){this.logLevel=W,this.filter=$,this.logger=X}error=(...W)=>{if((this.filter?.(...W)??!0)&&this.logLevel!==null)this.logger.error(...W)};info=(...W)=>{if((this.filter?.(...W)??!0)&&this.logLevel==="info")this.logger.info(...W)};warn=(...W)=>{if((this.filter?.(...W)??!0)&&this.logLevel!=="error"&&this.logLevel!==null)this.logger.warn(...W)}}class IW{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(W,$)=>`${W}:${$}`;warn;getRelatedKeys(W){return this.relations.get(W)}addRelation(W,$){let X=this.relations.get(W),Y=this.relations.get($);if(X)X.add($);else X=new Set([$]),this.relations.set(W,X);if(Y)Y.add(W);else Y=new Set([W]),this.relations.set($,Y)}deleteRelation(W,$){let X=this.relations.get(W);if(X){if(X.delete($),X.size===0)this.relations.delete(W);let Y=this.relations.get($);if(Y){if(Y.delete(W),Y.size===0)this.relations.delete($)}}}replaceRelationsUnsafely(W,$){this.relations.set(W,new Set($));for(let X of $){let Y=new Set().add(W);this.relations.set(X,Y)}}replaceRelationsSafely(W,$){let X=this.relations.get(W),Y=this.isAType?.(W)?W:void 0,J=Y===void 0?W:void 0;if(X)for(let G of X){Y??=G,J??=G;let H=this.relations.get(G);if(H){if(H.size===1)this.relations.delete(G);else H.delete(W);this.contents.delete(this.makeContentKey(Y,J))}}this.relations.set(W,new Set($));for(let G of $){let H=this.relations.get(G);if(H)H.add(W);else H=new Set().add(W),this.relations.set(G,H)}}getContentInternal(W){return this.contents.get(W)}setContent(W,$){this.contents.set(W,$)}deleteContent(W){this.contents.delete(W)}constructor(W,$){if(this.a=W.between[0],this.b=W.between[1],this.cardinality=W.cardinality,!$?.externalStore)this.relations=new Map(W.relations?.map(([X,Y])=>[X,new Set(Y)])),this.contents=new Map(W.contents);if(this.isAType=$?.isAType??null,this.isBType=$?.isBType??null,this.isContent=$?.isContent??null,$?.makeContentKey)this.makeContentKey=$.makeContentKey;if($?.externalStore){let X=$.externalStore;if(this.has=(Y,J)=>X.has(Y,J),this.addRelation=(Y,J)=>{X.addRelation(Y,J)},this.deleteRelation=(Y,J)=>{X.deleteRelation(Y,J)},this.replaceRelationsSafely=(Y,J)=>{X.replaceRelationsSafely(Y,J)},this.replaceRelationsUnsafely=(Y,J)=>{X.replaceRelationsUnsafely(Y,J)},this.getRelatedKeys=(Y)=>X.getRelatedKeys(Y),X.getContent)this.getContentInternal=(Y)=>{return X.getContent(Y)},this.setContent=(Y,J)=>{X.setContent(Y,J)},this.deleteContent=(Y)=>{X.deleteContent(Y)};for(let[Y,J]of W.relations??[]){let G=this.isAType?.(Y)?Y:void 0,H=G===void 0?Y:void 0;for(let Q of J)G??=Q,H??=Q,this.addRelation(G,H)}for(let[Y,J]of W.contents??[])this.setContent(Y,J)}if($?.warn)this.warn=$.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([W,$])=>[W,[...$]]),contents:[...this.contents.entries()]}}set(...W){let $,X,Y;switch(W.length){case 1:{let J=W[0];$=J[this.a],X=J[this.b],Y=void 0;break}case 2:{let J=W[0];if(typeof J==="string")[$,X]=W;else $=J[this.a],X=J[this.b],Y=W[1];break}default:{$=W[0],X=W[1],Y=W[2];break}}switch(this.cardinality){case"1:1":{let J=this.getRelatedKey($);if(J&&J!==X)this.delete($,J)}case"1:n":{let J=this.getRelatedKey(X);if(J&&J!==$)this.delete(J,X)}break;case"n:n":}if(Y){let J=this.makeContentKey($,X);this.setContent(J,Y)}return this.addRelation($,X),this}delete(W,$){$=typeof $==="string"?$:W[this.b];let X=typeof W==="string"?W:W[this.a];if(X===void 0&&typeof $==="string"){let Y=this.getRelatedKeys($);if(Y)for(let J of Y)this.delete(J,$)}if(typeof X==="string"&&$===void 0){let Y=this.getRelatedKeys(X);if(Y)for(let J of Y)this.delete(X,J)}if(typeof X==="string"&&typeof $==="string"){this.deleteRelation(X,$);let Y=this.makeContentKey(X,$);this.deleteContent(Y)}return this}getRelatedKey(W){let $=this.getRelatedKeys(W);if($){if($.size>1)this.warn?.(`${$.size} related keys were found for key "${W}": (${[...$].map((Y)=>`"${Y}"`).join(", ")}). Only one related key was expected.`);let X;for(let Y of $){X=Y;break}return X}}replaceRelations(W,$,X){let Y=!Array.isArray($),J=Y?Object.keys($):$;if(X?.reckless)this.replaceRelationsUnsafely(W,J);else this.replaceRelationsSafely(W,J);if(Y)for(let G of J){let H=this.makeContentKey(W,G),Q=$[G];this.setContent(H,Q)}return this}getContent(W,$){let X=this.makeContentKey(W,$);return this.getContentInternal(X)}getRelationEntries(W){let $=W[this.a],X=W[this.b];if($!==void 0&&X===void 0){let Y=this.getRelatedKeys($);if(Y)return[...Y].map((J)=>{return[J,this.getContent($,J)]})}if($===void 0&&X!==void 0){let Y=this.getRelatedKeys(X);if(Y)return[...Y].map((J)=>{return[J,this.getContent(J,X)]})}return[]}has(W,$){if($)return this.getRelatedKeys(W)?.has($)??!1;return this.relations.has(W)}}class Z0{Subscriber;subscribers=new Map;subscribe(W,$){return this.subscribers.set(W,$),()=>{this.unsubscribe(W)}}unsubscribe(W){this.subscribers.delete(W)}next(W){let $=this.subscribers.values();for(let X of $)X(W)}}class N9 extends Z0{state;constructor(W){super();this.state=W}next(W){this.state=W,super.next(W)}}function I8(W){return"epoch"in W.transactionMeta}function d1(W){return"phase"in W.transactionMeta}function FG(W){return W[0].toUpperCase()+W.slice(1)}function a6(W){return W.type.split("_").map(FG).join(" ")}class c$ extends Error{constructor(W,$){super(`${a6(W)} ${Z1(W.key)} not found in store "${$.config.name}".`)}}var s6=(W)=>($)=>W instanceof Function?W($):W;var K2=(W,$)=>{if(W.valueMap.has($.key))return W.logger.info("\uD83D\uDCD6",$.type,$.key,"reading cached value"),TG($,W);switch($.type){case"selector":case"readonly_selector":return W.logger.info("\uD83E\uDDEE",$.type,$.key,"computing value"),$.get();case"atom":case"mutable_atom":{let X=$.default,Y;if(X instanceof Function)Y=X();else Y=X;return W.logger.info("\uD83D\uDC81","atom",$.key,"could not find cached value; using default",Y),Y}}};var UG=(W,$)=>{if(W.operation.open){let X=performance.now();return W.logger.info("\u2757",$.type,$.key,`deferring setState at T-${X} until setState for "${W.operation.token.key}" is done`),X}W.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:$},W.logger.info("\u2B55",$.type,$.key,`operation start in store "${W.config.name}"${!d1(W)?"":` ${W.transactionMeta.phase} "${W.transactionMeta.update.key}"`}`)},wG=(W)=>{if(W.operation.open)W.logger.info("\uD83D\uDD34",W.operation.token.type,W.operation.token.key,`operation done in store "${W.config.name}"`);W.operation={open:!1},W.on.operationClose.next(W.operation)},MG=(W,$)=>{if(!W.operation.open)return W.logger.error("\uD83D\uDC1E","unknown",$,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return W.operation.done.has($)},j8=(W,$)=>{if(!W.operation.open){W.logger.error("\uD83D\uDC1E","unknown",$,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}W.operation.done.add($)};var _G=(W,$,X)=>{switch($.type){case"mutable_atom":W.logger.info("\uD83D\uDCE2",$.type,$.key,"is now (",X.newValue,") subscribers:",$.subject.subscribers);break;case"atom":case"selector":case"readonly_selector":W.logger.info("\uD83D\uDCE2",$.type,$.key,"went (",X.oldValue,"->",X.newValue,") subscribers:",$.subject.subscribers)}$.subject.next(X)};var B9=(W,$)=>{let X=J0(W),Y=X.selectorAtoms.getRelatedKeys($.key);if(X.logger.info("\uD83E\uDDF9",$.type,$.key,Y?`evicting ${Y.size} states downstream:`:"no downstream states",Y??"to evict"),Y){if(X.operation.open)X.logger.info("\uD83E\uDDF9",$.type,$.key,`[ ${[...X.operation.done].join(", ")} ] already done`);for(let J of Y){if(MG(X,J))continue;DG(J,X),j8(X,J)}}};var VG=(W,$,X)=>{let Y=K2(W,$),J=Y;if($.type==="mutable_atom"&&d1(W)){let{parent:H}=W;J=d$(W,$,H)}if(J=s6(X)(J),W.logger.info("\uD83D\uDCDD","atom",$.key,"set to",J),J=jW(W,$.key,J,$.subject),KG(W,$.key))LG(W,$.key);j8(W,$.key),B9(W,$);let G={oldValue:Y,newValue:J};if(!d1(W)){_G(W,$,G);return}if(W.on.transactionApplying.state===null){let{key:H}=$;if(OG(G.newValue))return;let Q={type:"atom_update",key:H,...G};if($.family)Q.family=$.family;W.transactionMeta.update.updates.push(Q),W.logger.info("\uD83D\uDCC1","atom",H,"stowed (",G.oldValue,"->",G.newValue,")")}else if($.key.startsWith("*")){let H=$.key.slice(1),Q=W.atoms.get(H),z=W.valueMap.get(H);if(Q.type==="mutable_atom"&&d1(W)){let{parent:T}=W;z=d$(W,Q,T)}if(z.do(G.newValue)===null)B9(W,Q)}};var e6=(W,$,X)=>{switch($.type){case"atom":case"mutable_atom":VG(W,$,X);break;case"selector":$.set(X);break}};var WX=(W,$)=>J0(W).atoms.has($),j_=(W,$)=>J0(W).selectors.has($),f_=(W,$)=>J0(W).readonlySelectors.has($),AG=(W,$)=>WX(W,$)||j_(W,$)||f_(W,$);var $X=(W,$)=>{return J0($).selectorGraph.getRelationEntries({downstreamSelectorKey:W}).filter(([Y,{source:J}])=>J!==W).map(([Y,{source:J}])=>J).filter((Y)=>AG($,Y))};var R9=(W,$,X)=>{let Y=[],J=$X(W,X);while(J.length>0){let G=J.shift();if($.has(G))continue;if($.add(G),!WX(X,G))J.push(...$X(G,X));else if(!Y.includes(G))Y.push(G)}return Y},EG=(W,$)=>{let X=W.key,Y=$X(X,$),J=new Set;return Y.flatMap((G)=>WX($,G)?G:R9(G,J,$))};var NG=(W,$,X,Y)=>{let J=J0(Y);if($.type==="atom"||$.type==="mutable_atom")J.selectorAtoms.set({selectorKey:W,atomKey:$.key}),Y.logger.info("\uD83D\uDD0D","selector",W,`discovers root atom "${$.key}"`);else{let G=R9($.key,X,Y);Y.logger.info("\uD83D\uDD0D","selector",W,`discovers root atoms: [ ${G.map((H)=>`"${H}"`).join(", ")} ]`);for(let H of G)J.selectorAtoms=J.selectorAtoms.set({selectorKey:W,atomKey:H})}X.add($.key)};var XX=(W,$,X)=>({get:(...Y)=>{let J=J0(X),G;if(Y.length===2){let[z,F]=Y;G=l1(X,z,F)}else[G]=Y;let H=P1(X,G),Q=K2(X,H);return X.logger.info("\uD83D\uDD0C","selector",W,`registers dependency ( "${G.key}" =`,Q,")"),J.selectorGraph.set({upstreamSelectorKey:G.key,downstreamSelectorKey:W},{source:G.key}),NG(W,G,$,X),Q},set:(...Y)=>{let J,G;if(Y.length===2)J=Y[0],G=Y[1];else{let z=Y[0],F=Y[1];G=Y[2],J=l1(X,z,F)}let H=J0(X),Q=P1(H,J);e6(H,Q,G)},find:(...Y)=>l1(X,...Y),json:(Y)=>f8(X,Y)});var Z9=(W,$,X)=>{let Y=J0(W),J=new Z0,G=new Set,{get:H,find:Q,json:z}=XX($.key,G,Y),F=()=>{let V=$.get({get:H,find:Q,json:z});return jW(J0(W),$.key,V,J),G.clear(),V},T={...$,subject:J,install:(V)=>Z9(V,$,X),get:F,type:"readonly_selector",...X&&{family:X}};Y.readonlySelectors.set($.key,T);let U=F();W.logger.info("\u2728",T.type,T.key,"=",U);let M={key:$.key,type:"readonly_selector"};if(X)M.family=X;return M};var l$=(W,$,X)=>{let Y=J0(W),J=new Z0,G=new Set,H=XX($.key,G,Y),{find:Q,get:z,json:F}=H,T={find:Q,get:z,json:F},U=(I=$.get,C=J0(W))=>{let B=I(T);return jW(C,$.key,B,J),G.clear(),B},V={...$,subject:J,install:(I)=>l$(I,$,X),get:U,set:(I)=>{let C=J0(W),B=U($.get,C),q=s6(I)(B);if(W.logger.info("\uD83D\uDCDD","selector",$.key,"set (",B,"->",q,")"),jW(C,$.key,q,J),j8(C,$.key),I8(C))J.next({newValue:q,oldValue:B});$.set(H,q)},type:"selector",...X&&{family:X}};Y.selectors.set($.key,V);let K=U();W.logger.info("\u2728",V.type,V.key,"=",K);let N={key:$.key,type:"selector"};if(X)N.family=X;return N};function HG(W,$){if("set"in $){let J=l$(W,$,void 0);return W.on.selectorCreation.next(J),J}let Y=Z9(W,$,void 0);return W.on.selectorCreation.next(Y),Y}function L9(W,$,X){let Y={key:$.key,type:"selector_family"},J=W.families.get($.key);if(J)W.logger.error("\u2757","selector_family",$.key,`Overwriting an existing ${a6(J)} "${J.key}" in store "${W.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let G=new Z0,Q=Object.assign((z)=>{let F=Z1(z),T={key:$.key,subKey:F},U=`${$.key}(${F})`,M=J0(W),V=l$(M,{key:U,get:$.get(z),set:$.set(z)},T);return G.next({type:"state_creation",token:V}),V},Y,{internalRoles:X,subject:G,install:(z)=>L9(z,$),default:(z)=>{return $.get(z)({get:(...T)=>o$(W,...T),find:(...T)=>l1(W,...T),json:(T)=>f8(W,T)})}});return W.families.set($.key,Q),Y}function BG(W,$,X){let Y=W.families.get($.key);if(Y===void 0)throw new c$($,W);let J=Y(X),G=J0(W);if(J.family){if(I8(G))switch(J.type){case"atom":case"mutable_atom":W.on.atomCreation.next(J);break;case"selector":case"readonly_selector":W.on.selectorCreation.next(J);break}else if(d1(G)&&G.on.transactionApplying.state===null)G.transactionMeta.update.updates.push({type:"state_creation",token:J})}return J}function RG(W,$,X){let Y=Z1(X),J=`${$.key}(${Y})`,G=J0(W),H;switch($.type){case"atom_family":case"mutable_atom_family":H=G.atoms.get(J);break;case"selector_family":H=G.selectors.get(J);break;case"readonly_selector_family":H=G.readonlySelectors.get(J);break}if(H)return u$(H);return H}function l1(W,$,X){let Y=RG(W,$,X);if(Y)return Y;let J=Z1(X),G=W.molecules.get(J);if(!G&&W.config.lifespan==="immortal"){let H=zG($,X);return W.logger.error("\u274C",H.type,H.key,`was not found in store "${W.config.name}"; returned a counterfeit token.`),H}if(Y=BG(W,$,X),G)J0(W).moleculeData.set(J,$.key);return Y}function ZG(W,$){if($.family){let X=W.families.get($.family.key);if(X)return X}}function L2(W,...$){let X,Y,J,G;if($.length===2){if(X=$[0],G=$[1],Y=ZG(W,X)??null,Y)J=X.family?p$(X.family.subKey):null,X=l1(W,Y,J)}else Y=$[0],J=$[1],G=$[2],X=l1(W,Y,J);if("counterfeit"in X&&"family"in X){let z=X.family.subKey,F=W.disposalTraces.buffer.find((T)=>T?.key===z);W.logger.error("\u274C",X.type,X.key,`could not be set because it was not found in the store "${W.config.name}".`,F?`This state was previously disposed:
4
+ ${F.trace}`:"No previous disposal trace was found.");return}let H=UG(W,X);if(H){let z=W.on.operationClose.subscribe(`waiting to set "${X.key}" at T-${H}`,()=>{z(),W.logger.info("\uD83D\uDFE2",X.type,X.key,`resuming deferred setState from T-${H}`),L2(W,X,G)});return}let Q=P1(W,X);e6(W,Q,G),wG(W)}function o$(W,...$){let X,Y,J;if($.length===1)X=$[0];else Y=$[0],J=$[1],X=l1(W,Y,J);if("counterfeit"in X&&"family"in X){Y=W.families.get(X.family.key);let G=X.family.subKey,H=W.disposalTraces.buffer.find((Q)=>Q?.key===G);switch(W.logger.error("\u274C",X.type,X.key,`could not be retrieved because it was not found in the store "${W.config.name}".`,H?`This state was previously disposed:
5
+ ${H.trace}`:"No previous disposal trace was found."),Y.type){case"atom_family":case"mutable_atom_family":return W.defaults.get(Y.key);case"selector_family":case"readonly_selector_family":{if(W.defaults.has(Y.key))return W.defaults.get(X.family.key);let Q=P1(W,Y).default(G);return W.defaults.set(Y.key,Q),Q}}}return K2(W,P1(W,X))}class SG{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;selectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new IW({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new IW({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...W)=>W.sort().join(":")});trackers=new Map;families=new Map;joins=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new IW({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new IW({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new t6(100);molecules=new Map;moleculeJoins=new IW({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...W)=>W.sort().join(":")});moleculeGraph=new IW({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...W)=>W.sort().join(":")});moleculeData=new IW({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...W)=>W.sort().join(":")});miscResources=new Map;on={atomCreation:new Z0,atomDisposal:new Z0,selectorCreation:new Z0,selectorDisposal:new Z0,timelineCreation:new Z0,transactionCreation:new Z0,transactionApplying:new N9(null),operationClose:new Z0,moleculeCreation:new Z0,moleculeDisposal:new Z0};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new E9("warn",(W,$,X)=>!CG(X))];logger={error:(...W)=>{for(let $ of this.loggers)$.error(...W)},info:(...W)=>{for(let $ of this.loggers)$.info(...W)},warn:(...W)=>{for(let $ of this.loggers)$.warn(...W)}};constructor(W,$=null){if(this.config={...$?.config,...W},$!==null){if(this.valueMap=new Map($?.valueMap),this.operation={...$?.operation},I8($))this.transactionMeta={epoch:new Map($?.transactionMeta.epoch),actionContinuities:new IW($?.transactionMeta.actionContinuities.toJSON())};for(let[,Y]of $.families){if(Y.internalRoles?.includes("mutable")||Y.internalRoles?.includes("join"))continue;Y.install(this)}let X=new Set;for(let[,Y]of $.atoms){if(X.has(Y.key))continue;if(Y.install(this),Y.type==="mutable_atom"){let J=f8($,Y),G=qG(Y);X.add(J.key),X.add(G.key)}}for(let[,Y]of $.readonlySelectors)Y.install(this);for(let[,Y]of $.selectors){if(X.has(Y.key))continue;Y.install(this)}for(let[,Y]of $.transactions)Y.install(this);for(let[,Y]of $.timelines)Y.install(this)}}}var QG={get STORE(){return globalThis.ATOM_IO_IMPLICIT_STORE??=new SG({name:"IMPLICIT_STORE",lifespan:"ephemeral"}),globalThis.ATOM_IO_IMPLICIT_STORE}};function P1(W,$){let X,Y=W;while(Y!==null){switch($.type){case"atom":case"mutable_atom":X=Y.atoms.get($.key);break;case"selector":X=Y.selectors.get($.key);break;case"readonly_selector":X=Y.readonlySelectors.get($.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":X=Y.families.get($.key);break;case"timeline":X=Y.timelines.get($.key);break;case"transaction":X=Y.transactions.get($.key);break}if(X)return X;Y=Y.child}throw new c$($,W)}var kG=(W,$)=>{let X=J0(W);if(X.operation.open)return X.operation.prev.get($.key);return X.valueMap.get($.key)};var S9=(W,$)=>{let X=J0(W);return EG($,W).map((J)=>{let G=X.atoms.get(J);if(G===void 0)throw new Error(`Atom "${J}", a dependency of selector "${$.key}", not found in store "${W.config.name}".`);return G.subject.subscribe(`${$.type}:${$.key}`,(H)=>{W.logger.info("\uD83D\uDCE2",$.type,$.key,"root",J,"went",H.oldValue,"->",H.newValue);let Q=kG(X,$),z=K2(X,$);W.logger.info("\u2728",$.type,$.key,"went",Q,"->",z),$.subject.next({newValue:z,oldValue:Q})})})};function i$(W,$,X,Y){function J(U){if(W.operation.open){let M=W.on.operationClose.subscribe(`state subscription ${X}`,()=>{M(),Y(U)})}else Y(U)}let G=P1(W,$);W.logger.info("\uD83D\uDC40",G.type,G.key,`Adding subscription "${X}"`);let H=G.type==="selector"||G.type==="readonly_selector",Q=null,z=J;if(H)Q=S9(W,G),z=(U)=>{if(Q)Q.length=0,Q.push(...S9(W,G));J(U)};let F=G.subject.subscribe(X,z);return()=>{if(W.logger.info("\uD83D\uDE48",G.type,G.key,`Removing subscription "${X}"`),F(),Q)for(let U of Q)U()}}var IG=(W,$,X,Y)=>{let J=P1(W,$);W.logger.info("\uD83D\uDC40","timeline",$.key,`Adding subscription "${X}"`);let G=J.subject.subscribe(X,Y);return()=>{W.logger.info("\uD83D\uDE48","timeline",$.key,`Removing subscription "${X}" from timeline`),G()}};class q9{initializeState(W,$){let X=`*${W.key}`;$.atoms.delete(X),$.valueMap.delete(X);let Y=W.family?{key:`*${W.family.key}`,subKey:W.family.subKey}:void 0,J=C9($,{key:X,default:null},Y);if($.parent?.valueMap.has(X)){let G=$.parent.valueMap.get(X);$.valueMap.set(X,G)}return J}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(W,$,X){let Y=`tracker:${X.config.name}:${d1(X)?X.transactionMeta.update.key:"main"}:${W.key}`,J=o$(X,W);this.unsubscribeFromInnerValue=J.subscribe(Y,(G)=>{L2(X,$,G)}),this.unsubscribeFromState=i$(X,W,Y,(G)=>{if(G.newValue!==G.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=G.newValue.subscribe(Y,(H)=>{L2(X,$,H)})})}updateCore(W,$,X){let Y=`tracker:${X.config.name}:${d1(X)?X.transactionMeta.update.key:"main"}:${W.key}`;i$(X,$,Y,({newValue:J,oldValue:G})=>{let H=X.timelineTopics.getRelatedKey($.key);if(H){if(X.timelines.get(H)?.timeTraveling){let F=IG(X,{key:H,type:"timeline"},Y,(T)=>{F(),L2(X,W,(U)=>{if(T==="redo"&&J)U.do(J);else if(T==="undo"&&G)U.undo(G);return U})});return}}let Q=X.on.operationClose.subscribe(Y,()=>{Q();let z=o$(X,W),F=J===null?-1:z.getUpdateNumber(J),T=F-z.cacheUpdateNumber;if(J&&T===1)L2(X,W,(U)=>(U.do(J),U));else X.logger.info("\u274C","mutable_atom",W.key,`could not be updated. Expected update number ${z.cacheUpdateNumber+1}, but got ${F}`)})})}mutableState;latestUpdateState;[Symbol.dispose];constructor(W,$){this.mutableState=W;let X=J0($);this.latestUpdateState=this.initializeState(W,X),this.observeCore(W,this.latestUpdateState,X),this.updateCore(W,this.latestUpdateState,X),X.trackers.set(W.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),X.trackers.delete(W.key)}}}var f8=(W,$)=>{if($.family){let Y=J0(W),G={key:`${$.family.key}:JSON`,type:"selector_family"},H=P1(Y,G),Q=JSON.parse($.family.subKey);return l1(W,H,Q)}return{type:"selector",key:`${$.key}:JSON`}};var qG=(W)=>{let X={type:"atom",key:`*${W.key}`};if(W.family)X.family={key:`*${W.family.key}`,subKey:W.family.subKey};return X};function OG(W){return typeof W==="object"&&W!==null&&"do"in W&&"undo"in W&&"subscribe"in W}function d$(W,$,X){let Y=X.valueMap.get($.key),J=W.valueMap.get($.key);if(Y!==J)return J;if(Y===void 0)return $.default();X.logger.info("\uD83D\uDCC3","atom",$.key,"copying");let G=$.toJson(Y),H=$.fromJson(G);return W.valueMap.set($.key,H),new q9($,X),H}function jW(W,$,X,Y){let J=W.valueMap.get($);if(J instanceof m$)J.use(X);if(X instanceof Promise){let G=new m$(X);return W.valueMap.set($,G),G.then((H)=>{jW(W,$,H,Y),Y.next({newValue:H,oldValue:G})}).catch((H)=>{W.logger.error("\uD83D\uDCA5","state",$,"rejected:",H)}),G}return W.valueMap.set($,X),X}var TG=(W,$)=>{let X=$.valueMap.get(W.key);if(W.type==="mutable_atom"&&d1($)){let{parent:Y}=$;X=d$($,W,Y)}return X},DG=(W,$)=>{let X=$.valueMap.get(W);if(X instanceof m$){let Y=X,J=$.selectors.get(W)??$.readonlySelectors.get(W);if(J)Y.use(J.get());return}if($.operation.open)$.operation.prev.set(W,X);$.valueMap.delete(W),$.logger.info("\uD83D\uDDD1","state",W,"evicted")};var KG=(W,$)=>{return J0(W).atomsThatAreDefault.has($)},jG=(W,$)=>{let X=J0(W);X.atomsThatAreDefault=new Set(X.atomsThatAreDefault).add($)},LG=(W,$)=>{let X=J0(W);X.atomsThatAreDefault=new Set(J0(W).atomsThatAreDefault),X.atomsThatAreDefault.delete($)};function C9(W,$,X){W.logger.info("\uD83D\uDD28","atom",$.key,`creating in store "${W.config.name}"`);let Y=J0(W),J=Y.atoms.get($.key);if(J&&J.type==="atom")return W.logger.error("\u274C","atom",$.key,"Tried to create atom, but it already exists in the store."),u$(J);let G=new Z0,H={...$,type:"atom",install:(F)=>{return F.logger.info("\uD83D\uDEE0\uFE0F","atom",$.key,`installing in store "${F.config.name}"`),C9(F,$,X)},subject:G};if(X)H.family=X;let Q=$.default;if($.default instanceof Function)Q=$.default();Y.atoms.set(H.key,H),jG(W,$.key),jW(Y,$.key,Q,G);let z=u$(H);if($.effects){let F=0,T=[];for(let U of $.effects){let M=U({setSelf:(V)=>{L2(W,z,V)},onSet:(V)=>i$(W,z,`effect[${F}]`,V)});if(M)T.push(M);++F}H.cleanup=()=>{for(let U of T)U()}}return z}class P8 extends Set{mode="record";subject=new Z0;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(W,$=0){super(W);if(W instanceof P8)this.parent=W,this.cacheUpdateNumber=W.cacheUpdateNumber;if($)this.cacheLimit=$,this.cache=new Array($),this.subscribe("auto cache",(X)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=X})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(W){let $=new P8(W.members,W.cacheLimit);return $.cache=W.cache,$.cacheIdx=W.cacheIdx,$.cacheUpdateNumber=W.cacheUpdateNumber,$}add(W){let $=super.add(W);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${Z1(W)}`);return $}clear(){let W=this.mode==="record"?[...this]:null;if(super.clear(),W)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(W)}`)}delete(W){let $=super.delete(W);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${Z1(W)}`);return $}parent=null;child=null;transactionUpdates=null;transaction(W){this.mode="transaction",this.transactionUpdates=[],this.child=new P8(this);let $=this.child._subscribe("transaction",(X)=>{this.transactionUpdates?.push(X)});try{if(W(this.child)){for(let Y of this.transactionUpdates)this.doStep(Y);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(X){throw console.warn("Did not apply transaction to SetRTX; this error was thrown:",X),X}finally{$(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(W,$){return this.subject.subscribe(W,$)}subscribe(W,$){return this.subject.subscribe(W,(X)=>{$(`${this.cacheUpdateNumber}=${X}`)})}emit(W){this.subject.next(W)}doStep(W){let $=W.indexOf(":"),X=W.substring(0,$),Y=W.substring($+1);switch(X){case"add":this.add(JSON.parse(Y));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(Y));break;case"tx":for(let J of Y.split(";"))this.doStep(J)}}getUpdateNumber(W){let $=W.indexOf("=");return Number(W.substring(0,$))}do(W){let $=W.indexOf("="),X=Number(W.substring(0,$)),Y=X-this.cacheUpdateNumber;if(Y>0){if(Y===1){this.mode="playback";let G=W.substring($+1);return this.doStep(G),this.mode="record",this.cacheUpdateNumber=X,null}return this.cacheUpdateNumber+1}if(Math.abs(Y)<this.cacheLimit){let G=this.cacheIdx+Y;if(this.cache[G]===W)return null;this.mode="playback";let Q=!1;while(!Q){this.cacheIdx%=this.cacheLimit;let F=this.cache[this.cacheIdx];if(this.cacheIdx--,!F)return"OUT_OF_RANGE";this.undo(F),Q=this.cacheIdx===G-1}let z=W.substring($+1);return this.doStep(z),this.mode="record",this.cacheUpdateNumber=X,null}return"OUT_OF_RANGE"}undoStep(W){let $=W.indexOf(":"),X=W.substring(0,$),Y=W.substring($+1);switch(X){case"add":this.delete(JSON.parse(Y));break;case"del":this.add(JSON.parse(Y));break;case"clear":{let J=JSON.parse(Y);for(let G of J)this.add(G);break}case"tx":{let J=Y.split(";");for(let G=J.length-1;G>=0;G--)this.undoStep(J[G])}}}undo(W){let $=W.indexOf("=");if(Number(W.substring(0,$))===this.cacheUpdateNumber){this.mode="playback";let Y=W.substring($+1);return this.undoStep(Y),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function CG(W){return W.startsWith("\uD83D\uDD0D ")}class YX{listeners;globalListeners;handleEvent(W,...$){for(let Y of this.globalListeners)Y(W,...$);let X=this.listeners.get(W);if(X)for(let Y of X)Y(...$)}id="no_id_retrieved";emit;constructor(W){this.emit=W,this.listeners=new Map,this.globalListeners=new Set}on(W,$){let X=this.listeners.get(W);if(X)X.add($);else this.listeners.set(W,new Set([$]));return this}onAny(W){return this.globalListeners.add(W),this}off(W,$){let X=this.listeners.get(W);if(X)if($)X.delete($);else this.listeners.delete(W);return this}offAny(W){return this.globalListeners.delete(W),this}}class fG extends YX{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(W){super((...$)=>{return this.out.next($),this});this.id=W,this.in=new Z0,this.out=new Z0,this.in.subscribe("socket",($)=>{this.handleEvent(...$)})}dispose(){for(let W of this.disposalFunctions)W()}}class k9 extends YX{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...W){this.process.stderr.write(Z1(W.map(($)=>$ instanceof P8?`{ ${$.toJSON().members.join(" | ")} }`:$))+"\x03")}logger={info:(...W)=>{this.log("i",...W)},warn:(...W)=>{this.log("w",...W)},error:(...W)=>{this.log("e",...W)}};constructor(){super((W,...$)=>{let X=JSON.stringify([W,...$]);return this.process.stdout.write(X+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(W)=>{let $=W.toString();this.unprocessedEvents.push(...$.split("\x03"));let X=this.unprocessedEvents.shift();this.incompleteData+=X??"";try{let Y=p$(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",Y),this.handleEvent(...Y);while(this.unprocessedEvents.length>0){let J=this.unprocessedEvents.shift();if(J){if(this.unprocessedEvents.length===0)this.incompleteData=J;let G=p$(J);this.handleEvent(...G)}}this.incompleteData=""}catch(Y){if(Y instanceof Error)this.logger.error("\u2757",Y.message,Y.cause,Y.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(W)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${W}`)}),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",(W)=>{this.logger.info("\uD83D\uDC64","user",W,"joined");let $=new fG(`user:${W}`);this.relays.set(W,$),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let X of this.relayServices){let Y=X($);if(Y)$.disposalFunctions.push(Y)}this.on(`user:${W}`,(...X)=>{$.in.next(X)}),$.out.subscribe("socket",(X)=>{this.emit(...X)})}),this.on("user-leaves",(W)=>{let $=this.relays.get(W);if(this.off(`relay:${W}`),$)$.dispose(),this.relays.delete(W)}),process.stdout.write("ALIVE")}relay(W){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(W)}}var xG=Symbol("Let zodToJsonSchema decide on which parser to use");var PG={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},vG=(W)=>typeof W==="string"?{...PG,name:W}:{...PG,...W};var bG=(W)=>{let $=vG(W),X=$.name!==void 0?[...$.basePath,$.definitionPath,$.name]:$.basePath;return{...$,currentPath:X,propertyPath:void 0,seen:new Map(Object.entries($.definitions).map(([Y,J])=>[J._def,{def:J._def,path:[...$.basePath,$.definitionPath,Y],jsonSchema:void 0}]))}};function I9(W,$,X,Y){if(!Y?.errorMessages)return;if(X)W.errorMessage={...W.errorMessage,[$]:X}}function V0(W,$,X,Y,J){W[$]=X,I9(W,$,Y,J)}var K0;(function(W){W.assertEqual=(J)=>J;function $(J){}W.assertIs=$;function X(J){throw new Error}W.assertNever=X,W.arrayToEnum=(J)=>{let G={};for(let H of J)G[H]=H;return G},W.getValidEnumValues=(J)=>{let G=W.objectKeys(J).filter((Q)=>typeof J[J[Q]]!=="number"),H={};for(let Q of G)H[Q]=J[Q];return W.objectValues(H)},W.objectValues=(J)=>{return W.objectKeys(J).map(function(G){return J[G]})},W.objectKeys=typeof Object.keys==="function"?(J)=>Object.keys(J):(J)=>{let G=[];for(let H in J)if(Object.prototype.hasOwnProperty.call(J,H))G.push(H);return G},W.find=(J,G)=>{for(let H of J)if(G(H))return H;return},W.isInteger=typeof Number.isInteger==="function"?(J)=>Number.isInteger(J):(J)=>typeof J==="number"&&isFinite(J)&&Math.floor(J)===J;function Y(J,G=" | "){return J.map((H)=>typeof H==="string"?`'${H}'`:H).join(G)}W.joinValues=Y,W.jsonStringifyReplacer=(J,G)=>{if(typeof G==="bigint")return G.toString();return G}})(K0||(K0={}));var yG;(function(W){W.mergeShapes=($,X)=>{return{...$,...X}}})(yG||(yG={}));var p=K0.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),A2=(W)=>{switch(typeof W){case"undefined":return p.undefined;case"string":return p.string;case"number":return isNaN(W)?p.nan:p.number;case"boolean":return p.boolean;case"function":return p.function;case"bigint":return p.bigint;case"symbol":return p.symbol;case"object":if(Array.isArray(W))return p.array;if(W===null)return p.null;if(W.then&&typeof W.then==="function"&&W.catch&&typeof W.catch==="function")return p.promise;if(typeof Map!=="undefined"&&W instanceof Map)return p.map;if(typeof Set!=="undefined"&&W instanceof Set)return p.set;if(typeof Date!=="undefined"&&W instanceof Date)return p.date;return p.object;default:return p.unknown}},Z=K0.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"]);class $W extends Error{get errors(){return this.issues}constructor(W){super();this.issues=[],this.addIssue=(X)=>{this.issues=[...this.issues,X]},this.addIssues=(X=[])=>{this.issues=[...this.issues,...X]};let $=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,$);else this.__proto__=$;this.name="ZodError",this.issues=W}format(W){let $=W||function(J){return J.message},X={_errors:[]},Y=(J)=>{for(let G of J.issues)if(G.code==="invalid_union")G.unionErrors.map(Y);else if(G.code==="invalid_return_type")Y(G.returnTypeError);else if(G.code==="invalid_arguments")Y(G.argumentsError);else if(G.path.length===0)X._errors.push($(G));else{let H=X,Q=0;while(Q<G.path.length){let z=G.path[Q];if(Q!==G.path.length-1)H[z]=H[z]||{_errors:[]};else H[z]=H[z]||{_errors:[]},H[z]._errors.push($(G));H=H[z],Q++}}};return Y(this),X}static assert(W){if(!(W instanceof $W))throw new Error(`Not a ZodError: ${W}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,K0.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(W=($)=>$.message){let $={},X=[];for(let Y of this.issues)if(Y.path.length>0)$[Y.path[0]]=$[Y.path[0]]||[],$[Y.path[0]].push(W(Y));else X.push(W(Y));return{formErrors:X,fieldErrors:$}}get formErrors(){return this.flatten()}}$W.create=(W)=>{return new $W(W)};var s$=(W,$)=>{let X;switch(W.code){case Z.invalid_type:if(W.received===p.undefined)X="Required";else X=`Expected ${W.expected}, received ${W.received}`;break;case Z.invalid_literal:X=`Invalid literal value, expected ${JSON.stringify(W.expected,K0.jsonStringifyReplacer)}`;break;case Z.unrecognized_keys:X=`Unrecognized key(s) in object: ${K0.joinValues(W.keys,", ")}`;break;case Z.invalid_union:X="Invalid input";break;case Z.invalid_union_discriminator:X=`Invalid discriminator value. Expected ${K0.joinValues(W.options)}`;break;case Z.invalid_enum_value:X=`Invalid enum value. Expected ${K0.joinValues(W.options)}, received '${W.received}'`;break;case Z.invalid_arguments:X="Invalid function arguments";break;case Z.invalid_return_type:X="Invalid function return type";break;case Z.invalid_date:X="Invalid date";break;case Z.invalid_string:if(typeof W.validation==="object")if("includes"in W.validation){if(X=`Invalid input: must include "${W.validation.includes}"`,typeof W.validation.position==="number")X=`${X} at one or more positions greater than or equal to ${W.validation.position}`}else if("startsWith"in W.validation)X=`Invalid input: must start with "${W.validation.startsWith}"`;else if("endsWith"in W.validation)X=`Invalid input: must end with "${W.validation.endsWith}"`;else K0.assertNever(W.validation);else if(W.validation!=="regex")X=`Invalid ${W.validation}`;else X="Invalid";break;case Z.too_small:if(W.type==="array")X=`Array must contain ${W.exact?"exactly":W.inclusive?"at least":"more than"} ${W.minimum} element(s)`;else if(W.type==="string")X=`String must contain ${W.exact?"exactly":W.inclusive?"at least":"over"} ${W.minimum} character(s)`;else if(W.type==="number")X=`Number must be ${W.exact?"exactly equal to ":W.inclusive?"greater than or equal to ":"greater than "}${W.minimum}`;else if(W.type==="date")X=`Date must be ${W.exact?"exactly equal to ":W.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(W.minimum))}`;else X="Invalid input";break;case Z.too_big:if(W.type==="array")X=`Array must contain ${W.exact?"exactly":W.inclusive?"at most":"less than"} ${W.maximum} element(s)`;else if(W.type==="string")X=`String must contain ${W.exact?"exactly":W.inclusive?"at most":"under"} ${W.maximum} character(s)`;else if(W.type==="number")X=`Number must be ${W.exact?"exactly":W.inclusive?"less than or equal to":"less than"} ${W.maximum}`;else if(W.type==="bigint")X=`BigInt must be ${W.exact?"exactly":W.inclusive?"less than or equal to":"less than"} ${W.maximum}`;else if(W.type==="date")X=`Date must be ${W.exact?"exactly":W.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(W.maximum))}`;else X="Invalid input";break;case Z.custom:X="Invalid input";break;case Z.invalid_intersection_types:X="Intersection results could not be merged";break;case Z.not_multiple_of:X=`Number must be a multiple of ${W.multipleOf}`;break;case Z.not_finite:X="Number must be finite";break;default:X=$.defaultError,K0.assertNever(W)}return{message:X}},P_=s$;function f9(){return P_}var P9=(W)=>{let{data:$,path:X,errorMaps:Y,issueData:J}=W,G=[...X,...J.path||[]],H={...J,path:G};if(J.message!==void 0)return{...J,path:G,message:J.message};let Q="",z=Y.filter((F)=>!!F).slice().reverse();for(let F of z)Q=F(H,{data:$,defaultError:Q}).message;return{...J,path:G,message:Q}};function b(W,$){let X=f9(),Y=P9({issueData:$,data:W.data,path:W.path,errorMaps:[W.common.contextualErrorMap,W.schemaErrorMap,X,X===s$?void 0:s$].filter((J)=>!!J)});W.common.issues.push(Y)}class S1{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(W,$){let X=[];for(let Y of $){if(Y.status==="aborted")return W0;if(Y.status==="dirty")W.dirty();X.push(Y.value)}return{status:W.value,value:X}}static async mergeObjectAsync(W,$){let X=[];for(let Y of $){let J=await Y.key,G=await Y.value;X.push({key:J,value:G})}return S1.mergeObjectSync(W,X)}static mergeObjectSync(W,$){let X={};for(let Y of $){let{key:J,value:G}=Y;if(J.status==="aborted")return W0;if(G.status==="aborted")return W0;if(J.status==="dirty")W.dirty();if(G.status==="dirty")W.dirty();if(J.value!=="__proto__"&&(typeof G.value!=="undefined"||Y.alwaysSet))X[J.value]=G.value}return{status:W.value,value:X}}}var W0=Object.freeze({status:"aborted"}),n$=(W)=>({status:"dirty",value:W}),x1=(W)=>({status:"valid",value:W}),hG=(W)=>W.status==="aborted",gG=(W)=>W.status==="dirty",v8=(W)=>W.status==="valid",JX=(W)=>typeof Promise!=="undefined"&&W instanceof Promise;function GX(W,$,X,Y){if(X==="a"&&!Y)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?W!==$||!Y:!$.has(W))throw new TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call(W):Y?Y.value:$.get(W)}function pG(W,$,X,Y,J){if(Y==="m")throw new TypeError("Private method is not writable");if(Y==="a"&&!J)throw new TypeError("Private accessor was defined without a setter");if(typeof $==="function"?W!==$||!J:!$.has(W))throw new TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?J.call(W,X):J?J.value=X:$.set(W,X),X}var l;(function(W){W.errToObj=($)=>typeof $==="string"?{message:$}:$||{},W.toString=($)=>typeof $==="string"?$:$===null||$===void 0?void 0:$.message})(l||(l={}));var r$,t$;class DW{constructor(W,$,X,Y){this._cachedPath=[],this.parent=W,this.data=$,this._path=X,this._key=Y}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 mG=(W,$)=>{if(v8($))return{success:!0,data:$.value};else{if(!W.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let X=new $W(W.common.issues);return this._error=X,this._error}}}};function G0(W){if(!W)return{};let{errorMap:$,invalid_type_error:X,required_error:Y,description:J}=W;if($&&(X||Y))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if($)return{errorMap:$,description:J};return{errorMap:(H,Q)=>{var z,F;let{message:T}=W;if(H.code==="invalid_enum_value")return{message:T!==null&&T!==void 0?T:Q.defaultError};if(typeof Q.data==="undefined")return{message:(z=T!==null&&T!==void 0?T:Y)!==null&&z!==void 0?z:Q.defaultError};if(H.code!=="invalid_type")return{message:Q.defaultError};return{message:(F=T!==null&&T!==void 0?T:X)!==null&&F!==void 0?F:Q.defaultError}},description:J}}class T0{get description(){return this._def.description}_getType(W){return A2(W.data)}_getOrReturnCtx(W,$){return $||{common:W.parent.common,data:W.data,parsedType:A2(W.data),schemaErrorMap:this._def.errorMap,path:W.path,parent:W.parent}}_processInputParams(W){return{status:new S1,ctx:{common:W.parent.common,data:W.data,parsedType:A2(W.data),schemaErrorMap:this._def.errorMap,path:W.path,parent:W.parent}}}_parseSync(W){let $=this._parse(W);if(JX($))throw new Error("Synchronous parse encountered promise.");return $}_parseAsync(W){let $=this._parse(W);return Promise.resolve($)}parse(W,$){let X=this.safeParse(W,$);if(X.success)return X.data;throw X.error}safeParse(W,$){var X;let Y={common:{issues:[],async:(X=$===null||$===void 0?void 0:$.async)!==null&&X!==void 0?X:!1,contextualErrorMap:$===null||$===void 0?void 0:$.errorMap},path:($===null||$===void 0?void 0:$.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:W,parsedType:A2(W)},J=this._parseSync({data:W,path:Y.path,parent:Y});return mG(Y,J)}"~validate"(W){var $,X;let Y={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:W,parsedType:A2(W)};if(!this["~standard"].async)try{let J=this._parseSync({data:W,path:[],parent:Y});return v8(J)?{value:J.value}:{issues:Y.common.issues}}catch(J){if((X=($=J===null||J===void 0?void 0:J.message)===null||$===void 0?void 0:$.toLowerCase())===null||X===void 0?void 0:X.includes("encountered"))this["~standard"].async=!0;Y.common={issues:[],async:!0}}return this._parseAsync({data:W,path:[],parent:Y}).then((J)=>v8(J)?{value:J.value}:{issues:Y.common.issues})}async parseAsync(W,$){let X=await this.safeParseAsync(W,$);if(X.success)return X.data;throw X.error}async safeParseAsync(W,$){let X={common:{issues:[],contextualErrorMap:$===null||$===void 0?void 0:$.errorMap,async:!0},path:($===null||$===void 0?void 0:$.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:W,parsedType:A2(W)},Y=this._parse({data:W,path:X.path,parent:X}),J=await(JX(Y)?Y:Promise.resolve(Y));return mG(X,J)}refine(W,$){let X=(Y)=>{if(typeof $==="string"||typeof $==="undefined")return{message:$};else if(typeof $==="function")return $(Y);else return $};return this._refinement((Y,J)=>{let G=W(Y),H=()=>J.addIssue({code:Z.custom,...X(Y)});if(typeof Promise!=="undefined"&&G instanceof Promise)return G.then((Q)=>{if(!Q)return H(),!1;else return!0});if(!G)return H(),!1;else return!0})}refinement(W,$){return this._refinement((X,Y)=>{if(!W(X))return Y.addIssue(typeof $==="function"?$(X,Y):$),!1;else return!0})}_refinement(W){return new PW({schema:this,typeName:S.ZodEffects,effect:{type:"refinement",refinement:W}})}superRefine(W){return this._refinement(W)}constructor(W){this.spa=this.safeParseAsync,this._def=W,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:($)=>this["~validate"]($)}}optional(){return XW.create(this,this._def)}nullable(){return E2.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return fW.create(this)}promise(){return g8.create(this,this._def)}or(W){return X4.create([this,W],this._def)}and(W){return Y4.create(this,W,this._def)}transform(W){return new PW({...G0(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:W}})}default(W){let $=typeof W==="function"?W:()=>W;return new Q4({...G0(this._def),innerType:this,defaultValue:$,typeName:S.ZodDefault})}brand(){return new b9({typeName:S.ZodBranded,type:this,...G0(this._def)})}catch(W){let $=typeof W==="function"?W:()=>W;return new z4({...G0(this._def),innerType:this,catchValue:$,typeName:S.ZodCatch})}describe(W){return new this.constructor({...this._def,description:W})}pipe(W){return MX.create(this,W)}readonly(){return F4.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var x_=/^c[^\s-]{8,}$/i,v_=/^[0-9a-z]+$/,b_=/^[0-9A-HJKMNP-TV-Z]{26}$/i,y_=/^[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,h_=/^[a-z0-9_-]{21}$/i,g_=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,m_=/^[-+]?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)?)??$/,p_=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,u_="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",j9,c_=/^(?:(?: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])$/,d_=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,l_=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,o_=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,i_=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,n_=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,uG="((\\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])))",r_=new RegExp(`^${uG}$`);function cG(W){let $="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";if(W.precision)$=`${$}\\.\\d{${W.precision}}`;else if(W.precision==null)$=`${$}(\\.\\d+)?`;return $}function t_(W){return new RegExp(`^${cG(W)}$`)}function a_(W){let $=`${uG}T${cG(W)}`,X=[];if(X.push(W.local?"Z?":"Z"),W.offset)X.push("([+-]\\d{2}:?\\d{2})");return $=`${$}(${X.join("|")})`,new RegExp(`^${$}$`)}function s_(W,$){if(($==="v4"||!$)&&c_.test(W))return!0;if(($==="v6"||!$)&&l_.test(W))return!0;return!1}function e_(W,$){if(!g_.test(W))return!1;try{let[X]=W.split("."),Y=X.replace(/-/g,"+").replace(/_/g,"/").padEnd(X.length+(4-X.length%4)%4,"="),J=JSON.parse(atob(Y));if(typeof J!=="object"||J===null)return!1;if(!J.typ||!J.alg)return!1;if($&&J.alg!==$)return!1;return!0}catch(X){return!1}}function WD(W,$){if(($==="v4"||!$)&&d_.test(W))return!0;if(($==="v6"||!$)&&o_.test(W))return!0;return!1}class lW extends T0{_parse(W){if(this._def.coerce)W.data=String(W.data);if(this._getType(W)!==p.string){let J=this._getOrReturnCtx(W);return b(J,{code:Z.invalid_type,expected:p.string,received:J.parsedType}),W0}let X=new S1,Y=void 0;for(let J of this._def.checks)if(J.kind==="min"){if(W.data.length<J.value)Y=this._getOrReturnCtx(W,Y),b(Y,{code:Z.too_small,minimum:J.value,type:"string",inclusive:!0,exact:!1,message:J.message}),X.dirty()}else if(J.kind==="max"){if(W.data.length>J.value)Y=this._getOrReturnCtx(W,Y),b(Y,{code:Z.too_big,maximum:J.value,type:"string",inclusive:!0,exact:!1,message:J.message}),X.dirty()}else if(J.kind==="length"){let G=W.data.length>J.value,H=W.data.length<J.value;if(G||H){if(Y=this._getOrReturnCtx(W,Y),G)b(Y,{code:Z.too_big,maximum:J.value,type:"string",inclusive:!0,exact:!0,message:J.message});else if(H)b(Y,{code:Z.too_small,minimum:J.value,type:"string",inclusive:!0,exact:!0,message:J.message});X.dirty()}}else if(J.kind==="email"){if(!p_.test(W.data))Y=this._getOrReturnCtx(W,Y),b(Y,{validation:"email",code:Z.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="emoji"){if(!j9)j9=new RegExp(u_,"u");if(!j9.test(W.data))Y=this._getOrReturnCtx(W,Y),b(Y,{validation:"emoji",code:Z.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="uuid"){if(!y_.test(W.data))Y=this._getOrReturnCtx(W,Y),b(Y,{validation:"uuid",code:Z.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="nanoid"){if(!h_.test(W.data))Y=this._getOrReturnCtx(W,Y),b(Y,{validation:"nanoid",code:Z.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="cuid"){if(!x_.test(W.data))Y=this._getOrReturnCtx(W,Y),b(Y,{validation:"cuid",code:Z.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="cuid2"){if(!v_.test(W.data))Y=this._getOrReturnCtx(W,Y),b(Y,{validation:"cuid2",code:Z.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="ulid"){if(!b_.test(W.data))Y=this._getOrReturnCtx(W,Y),b(Y,{validation:"ulid",code:Z.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="url")try{new URL(W.data)}catch(G){Y=this._getOrReturnCtx(W,Y),b(Y,{validation:"url",code:Z.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="regex"){if(J.regex.lastIndex=0,!J.regex.test(W.data))Y=this._getOrReturnCtx(W,Y),b(Y,{validation:"regex",code:Z.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="trim")W.data=W.data.trim();else if(J.kind==="includes"){if(!W.data.includes(J.value,J.position))Y=this._getOrReturnCtx(W,Y),b(Y,{code:Z.invalid_string,validation:{includes:J.value,position:J.position},message:J.message}),X.dirty()}else if(J.kind==="toLowerCase")W.data=W.data.toLowerCase();else if(J.kind==="toUpperCase")W.data=W.data.toUpperCase();else if(J.kind==="startsWith"){if(!W.data.startsWith(J.value))Y=this._getOrReturnCtx(W,Y),b(Y,{code:Z.invalid_string,validation:{startsWith:J.value},message:J.message}),X.dirty()}else if(J.kind==="endsWith"){if(!W.data.endsWith(J.value))Y=this._getOrReturnCtx(W,Y),b(Y,{code:Z.invalid_string,validation:{endsWith:J.value},message:J.message}),X.dirty()}else if(J.kind==="datetime"){if(!a_(J).test(W.data))Y=this._getOrReturnCtx(W,Y),b(Y,{code:Z.invalid_string,validation:"datetime",message:J.message}),X.dirty()}else if(J.kind==="date"){if(!r_.test(W.data))Y=this._getOrReturnCtx(W,Y),b(Y,{code:Z.invalid_string,validation:"date",message:J.message}),X.dirty()}else if(J.kind==="time"){if(!t_(J).test(W.data))Y=this._getOrReturnCtx(W,Y),b(Y,{code:Z.invalid_string,validation:"time",message:J.message}),X.dirty()}else if(J.kind==="duration"){if(!m_.test(W.data))Y=this._getOrReturnCtx(W,Y),b(Y,{validation:"duration",code:Z.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="ip"){if(!s_(W.data,J.version))Y=this._getOrReturnCtx(W,Y),b(Y,{validation:"ip",code:Z.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="jwt"){if(!e_(W.data,J.alg))Y=this._getOrReturnCtx(W,Y),b(Y,{validation:"jwt",code:Z.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="cidr"){if(!WD(W.data,J.version))Y=this._getOrReturnCtx(W,Y),b(Y,{validation:"cidr",code:Z.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="base64"){if(!i_.test(W.data))Y=this._getOrReturnCtx(W,Y),b(Y,{validation:"base64",code:Z.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="base64url"){if(!n_.test(W.data))Y=this._getOrReturnCtx(W,Y),b(Y,{validation:"base64url",code:Z.invalid_string,message:J.message}),X.dirty()}else K0.assertNever(J);return{status:X.value,value:W.data}}_regex(W,$,X){return this.refinement((Y)=>W.test(Y),{validation:$,code:Z.invalid_string,...l.errToObj(X)})}_addCheck(W){return new lW({...this._def,checks:[...this._def.checks,W]})}email(W){return this._addCheck({kind:"email",...l.errToObj(W)})}url(W){return this._addCheck({kind:"url",...l.errToObj(W)})}emoji(W){return this._addCheck({kind:"emoji",...l.errToObj(W)})}uuid(W){return this._addCheck({kind:"uuid",...l.errToObj(W)})}nanoid(W){return this._addCheck({kind:"nanoid",...l.errToObj(W)})}cuid(W){return this._addCheck({kind:"cuid",...l.errToObj(W)})}cuid2(W){return this._addCheck({kind:"cuid2",...l.errToObj(W)})}ulid(W){return this._addCheck({kind:"ulid",...l.errToObj(W)})}base64(W){return this._addCheck({kind:"base64",...l.errToObj(W)})}base64url(W){return this._addCheck({kind:"base64url",...l.errToObj(W)})}jwt(W){return this._addCheck({kind:"jwt",...l.errToObj(W)})}ip(W){return this._addCheck({kind:"ip",...l.errToObj(W)})}cidr(W){return this._addCheck({kind:"cidr",...l.errToObj(W)})}datetime(W){var $,X;if(typeof W==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:W});return this._addCheck({kind:"datetime",precision:typeof(W===null||W===void 0?void 0:W.precision)==="undefined"?null:W===null||W===void 0?void 0:W.precision,offset:($=W===null||W===void 0?void 0:W.offset)!==null&&$!==void 0?$:!1,local:(X=W===null||W===void 0?void 0:W.local)!==null&&X!==void 0?X:!1,...l.errToObj(W===null||W===void 0?void 0:W.message)})}date(W){return this._addCheck({kind:"date",message:W})}time(W){if(typeof W==="string")return this._addCheck({kind:"time",precision:null,message:W});return this._addCheck({kind:"time",precision:typeof(W===null||W===void 0?void 0:W.precision)==="undefined"?null:W===null||W===void 0?void 0:W.precision,...l.errToObj(W===null||W===void 0?void 0:W.message)})}duration(W){return this._addCheck({kind:"duration",...l.errToObj(W)})}regex(W,$){return this._addCheck({kind:"regex",regex:W,...l.errToObj($)})}includes(W,$){return this._addCheck({kind:"includes",value:W,position:$===null||$===void 0?void 0:$.position,...l.errToObj($===null||$===void 0?void 0:$.message)})}startsWith(W,$){return this._addCheck({kind:"startsWith",value:W,...l.errToObj($)})}endsWith(W,$){return this._addCheck({kind:"endsWith",value:W,...l.errToObj($)})}min(W,$){return this._addCheck({kind:"min",value:W,...l.errToObj($)})}max(W,$){return this._addCheck({kind:"max",value:W,...l.errToObj($)})}length(W,$){return this._addCheck({kind:"length",value:W,...l.errToObj($)})}nonempty(W){return this.min(1,l.errToObj(W))}trim(){return new lW({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new lW({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new lW({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((W)=>W.kind==="datetime")}get isDate(){return!!this._def.checks.find((W)=>W.kind==="date")}get isTime(){return!!this._def.checks.find((W)=>W.kind==="time")}get isDuration(){return!!this._def.checks.find((W)=>W.kind==="duration")}get isEmail(){return!!this._def.checks.find((W)=>W.kind==="email")}get isURL(){return!!this._def.checks.find((W)=>W.kind==="url")}get isEmoji(){return!!this._def.checks.find((W)=>W.kind==="emoji")}get isUUID(){return!!this._def.checks.find((W)=>W.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((W)=>W.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((W)=>W.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((W)=>W.kind==="cuid2")}get isULID(){return!!this._def.checks.find((W)=>W.kind==="ulid")}get isIP(){return!!this._def.checks.find((W)=>W.kind==="ip")}get isCIDR(){return!!this._def.checks.find((W)=>W.kind==="cidr")}get isBase64(){return!!this._def.checks.find((W)=>W.kind==="base64")}get isBase64url(){return!!this._def.checks.find((W)=>W.kind==="base64url")}get minLength(){let W=null;for(let $ of this._def.checks)if($.kind==="min"){if(W===null||$.value>W)W=$.value}return W}get maxLength(){let W=null;for(let $ of this._def.checks)if($.kind==="max"){if(W===null||$.value<W)W=$.value}return W}}lW.create=(W)=>{var $;return new lW({checks:[],typeName:S.ZodString,coerce:($=W===null||W===void 0?void 0:W.coerce)!==null&&$!==void 0?$:!1,...G0(W)})};function $D(W,$){let X=(W.toString().split(".")[1]||"").length,Y=($.toString().split(".")[1]||"").length,J=X>Y?X:Y,G=parseInt(W.toFixed(J).replace(".","")),H=parseInt($.toFixed(J).replace(".",""));return G%H/Math.pow(10,J)}class b8 extends T0{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(W){if(this._def.coerce)W.data=Number(W.data);if(this._getType(W)!==p.number){let J=this._getOrReturnCtx(W);return b(J,{code:Z.invalid_type,expected:p.number,received:J.parsedType}),W0}let X=void 0,Y=new S1;for(let J of this._def.checks)if(J.kind==="int"){if(!K0.isInteger(W.data))X=this._getOrReturnCtx(W,X),b(X,{code:Z.invalid_type,expected:"integer",received:"float",message:J.message}),Y.dirty()}else if(J.kind==="min"){if(J.inclusive?W.data<J.value:W.data<=J.value)X=this._getOrReturnCtx(W,X),b(X,{code:Z.too_small,minimum:J.value,type:"number",inclusive:J.inclusive,exact:!1,message:J.message}),Y.dirty()}else if(J.kind==="max"){if(J.inclusive?W.data>J.value:W.data>=J.value)X=this._getOrReturnCtx(W,X),b(X,{code:Z.too_big,maximum:J.value,type:"number",inclusive:J.inclusive,exact:!1,message:J.message}),Y.dirty()}else if(J.kind==="multipleOf"){if($D(W.data,J.value)!==0)X=this._getOrReturnCtx(W,X),b(X,{code:Z.not_multiple_of,multipleOf:J.value,message:J.message}),Y.dirty()}else if(J.kind==="finite"){if(!Number.isFinite(W.data))X=this._getOrReturnCtx(W,X),b(X,{code:Z.not_finite,message:J.message}),Y.dirty()}else K0.assertNever(J);return{status:Y.value,value:W.data}}gte(W,$){return this.setLimit("min",W,!0,l.toString($))}gt(W,$){return this.setLimit("min",W,!1,l.toString($))}lte(W,$){return this.setLimit("max",W,!0,l.toString($))}lt(W,$){return this.setLimit("max",W,!1,l.toString($))}setLimit(W,$,X,Y){return new b8({...this._def,checks:[...this._def.checks,{kind:W,value:$,inclusive:X,message:l.toString(Y)}]})}_addCheck(W){return new b8({...this._def,checks:[...this._def.checks,W]})}int(W){return this._addCheck({kind:"int",message:l.toString(W)})}positive(W){return this._addCheck({kind:"min",value:0,inclusive:!1,message:l.toString(W)})}negative(W){return this._addCheck({kind:"max",value:0,inclusive:!1,message:l.toString(W)})}nonpositive(W){return this._addCheck({kind:"max",value:0,inclusive:!0,message:l.toString(W)})}nonnegative(W){return this._addCheck({kind:"min",value:0,inclusive:!0,message:l.toString(W)})}multipleOf(W,$){return this._addCheck({kind:"multipleOf",value:W,message:l.toString($)})}finite(W){return this._addCheck({kind:"finite",message:l.toString(W)})}safe(W){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:l.toString(W)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:l.toString(W)})}get minValue(){let W=null;for(let $ of this._def.checks)if($.kind==="min"){if(W===null||$.value>W)W=$.value}return W}get maxValue(){let W=null;for(let $ of this._def.checks)if($.kind==="max"){if(W===null||$.value<W)W=$.value}return W}get isInt(){return!!this._def.checks.find((W)=>W.kind==="int"||W.kind==="multipleOf"&&K0.isInteger(W.value))}get isFinite(){let W=null,$=null;for(let X of this._def.checks)if(X.kind==="finite"||X.kind==="int"||X.kind==="multipleOf")return!0;else if(X.kind==="min"){if($===null||X.value>$)$=X.value}else if(X.kind==="max"){if(W===null||X.value<W)W=X.value}return Number.isFinite($)&&Number.isFinite(W)}}b8.create=(W)=>{return new b8({checks:[],typeName:S.ZodNumber,coerce:(W===null||W===void 0?void 0:W.coerce)||!1,...G0(W)})};class y8 extends T0{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(W){if(this._def.coerce)try{W.data=BigInt(W.data)}catch(J){return this._getInvalidInput(W)}if(this._getType(W)!==p.bigint)return this._getInvalidInput(W);let X=void 0,Y=new S1;for(let J of this._def.checks)if(J.kind==="min"){if(J.inclusive?W.data<J.value:W.data<=J.value)X=this._getOrReturnCtx(W,X),b(X,{code:Z.too_small,type:"bigint",minimum:J.value,inclusive:J.inclusive,message:J.message}),Y.dirty()}else if(J.kind==="max"){if(J.inclusive?W.data>J.value:W.data>=J.value)X=this._getOrReturnCtx(W,X),b(X,{code:Z.too_big,type:"bigint",maximum:J.value,inclusive:J.inclusive,message:J.message}),Y.dirty()}else if(J.kind==="multipleOf"){if(W.data%J.value!==BigInt(0))X=this._getOrReturnCtx(W,X),b(X,{code:Z.not_multiple_of,multipleOf:J.value,message:J.message}),Y.dirty()}else K0.assertNever(J);return{status:Y.value,value:W.data}}_getInvalidInput(W){let $=this._getOrReturnCtx(W);return b($,{code:Z.invalid_type,expected:p.bigint,received:$.parsedType}),W0}gte(W,$){return this.setLimit("min",W,!0,l.toString($))}gt(W,$){return this.setLimit("min",W,!1,l.toString($))}lte(W,$){return this.setLimit("max",W,!0,l.toString($))}lt(W,$){return this.setLimit("max",W,!1,l.toString($))}setLimit(W,$,X,Y){return new y8({...this._def,checks:[...this._def.checks,{kind:W,value:$,inclusive:X,message:l.toString(Y)}]})}_addCheck(W){return new y8({...this._def,checks:[...this._def.checks,W]})}positive(W){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:l.toString(W)})}negative(W){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:l.toString(W)})}nonpositive(W){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:l.toString(W)})}nonnegative(W){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:l.toString(W)})}multipleOf(W,$){return this._addCheck({kind:"multipleOf",value:W,message:l.toString($)})}get minValue(){let W=null;for(let $ of this._def.checks)if($.kind==="min"){if(W===null||$.value>W)W=$.value}return W}get maxValue(){let W=null;for(let $ of this._def.checks)if($.kind==="max"){if(W===null||$.value<W)W=$.value}return W}}y8.create=(W)=>{var $;return new y8({checks:[],typeName:S.ZodBigInt,coerce:($=W===null||W===void 0?void 0:W.coerce)!==null&&$!==void 0?$:!1,...G0(W)})};class HX extends T0{_parse(W){if(this._def.coerce)W.data=Boolean(W.data);if(this._getType(W)!==p.boolean){let X=this._getOrReturnCtx(W);return b(X,{code:Z.invalid_type,expected:p.boolean,received:X.parsedType}),W0}return x1(W.data)}}HX.create=(W)=>{return new HX({typeName:S.ZodBoolean,coerce:(W===null||W===void 0?void 0:W.coerce)||!1,...G0(W)})};class e$ extends T0{_parse(W){if(this._def.coerce)W.data=new Date(W.data);if(this._getType(W)!==p.date){let J=this._getOrReturnCtx(W);return b(J,{code:Z.invalid_type,expected:p.date,received:J.parsedType}),W0}if(isNaN(W.data.getTime())){let J=this._getOrReturnCtx(W);return b(J,{code:Z.invalid_date}),W0}let X=new S1,Y=void 0;for(let J of this._def.checks)if(J.kind==="min"){if(W.data.getTime()<J.value)Y=this._getOrReturnCtx(W,Y),b(Y,{code:Z.too_small,message:J.message,inclusive:!0,exact:!1,minimum:J.value,type:"date"}),X.dirty()}else if(J.kind==="max"){if(W.data.getTime()>J.value)Y=this._getOrReturnCtx(W,Y),b(Y,{code:Z.too_big,message:J.message,inclusive:!0,exact:!1,maximum:J.value,type:"date"}),X.dirty()}else K0.assertNever(J);return{status:X.value,value:new Date(W.data.getTime())}}_addCheck(W){return new e$({...this._def,checks:[...this._def.checks,W]})}min(W,$){return this._addCheck({kind:"min",value:W.getTime(),message:l.toString($)})}max(W,$){return this._addCheck({kind:"max",value:W.getTime(),message:l.toString($)})}get minDate(){let W=null;for(let $ of this._def.checks)if($.kind==="min"){if(W===null||$.value>W)W=$.value}return W!=null?new Date(W):null}get maxDate(){let W=null;for(let $ of this._def.checks)if($.kind==="max"){if(W===null||$.value<W)W=$.value}return W!=null?new Date(W):null}}e$.create=(W)=>{return new e$({checks:[],coerce:(W===null||W===void 0?void 0:W.coerce)||!1,typeName:S.ZodDate,...G0(W)})};class QX extends T0{_parse(W){if(this._getType(W)!==p.symbol){let X=this._getOrReturnCtx(W);return b(X,{code:Z.invalid_type,expected:p.symbol,received:X.parsedType}),W0}return x1(W.data)}}QX.create=(W)=>{return new QX({typeName:S.ZodSymbol,...G0(W)})};class W4 extends T0{_parse(W){if(this._getType(W)!==p.undefined){let X=this._getOrReturnCtx(W);return b(X,{code:Z.invalid_type,expected:p.undefined,received:X.parsedType}),W0}return x1(W.data)}}W4.create=(W)=>{return new W4({typeName:S.ZodUndefined,...G0(W)})};class $4 extends T0{_parse(W){if(this._getType(W)!==p.null){let X=this._getOrReturnCtx(W);return b(X,{code:Z.invalid_type,expected:p.null,received:X.parsedType}),W0}return x1(W.data)}}$4.create=(W)=>{return new $4({typeName:S.ZodNull,...G0(W)})};class zX extends T0{constructor(){super(...arguments);this._any=!0}_parse(W){return x1(W.data)}}zX.create=(W)=>{return new zX({typeName:S.ZodAny,...G0(W)})};class d2 extends T0{constructor(){super(...arguments);this._unknown=!0}_parse(W){return x1(W.data)}}d2.create=(W)=>{return new d2({typeName:S.ZodUnknown,...G0(W)})};class oW extends T0{_parse(W){let $=this._getOrReturnCtx(W);return b($,{code:Z.invalid_type,expected:p.never,received:$.parsedType}),W0}}oW.create=(W)=>{return new oW({typeName:S.ZodNever,...G0(W)})};class FX extends T0{_parse(W){if(this._getType(W)!==p.undefined){let X=this._getOrReturnCtx(W);return b(X,{code:Z.invalid_type,expected:p.void,received:X.parsedType}),W0}return x1(W.data)}}FX.create=(W)=>{return new FX({typeName:S.ZodVoid,...G0(W)})};class fW extends T0{_parse(W){let{ctx:$,status:X}=this._processInputParams(W),Y=this._def;if($.parsedType!==p.array)return b($,{code:Z.invalid_type,expected:p.array,received:$.parsedType}),W0;if(Y.exactLength!==null){let G=$.data.length>Y.exactLength.value,H=$.data.length<Y.exactLength.value;if(G||H)b($,{code:G?Z.too_big:Z.too_small,minimum:H?Y.exactLength.value:void 0,maximum:G?Y.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:Y.exactLength.message}),X.dirty()}if(Y.minLength!==null){if($.data.length<Y.minLength.value)b($,{code:Z.too_small,minimum:Y.minLength.value,type:"array",inclusive:!0,exact:!1,message:Y.minLength.message}),X.dirty()}if(Y.maxLength!==null){if($.data.length>Y.maxLength.value)b($,{code:Z.too_big,maximum:Y.maxLength.value,type:"array",inclusive:!0,exact:!1,message:Y.maxLength.message}),X.dirty()}if($.common.async)return Promise.all([...$.data].map((G,H)=>{return Y.type._parseAsync(new DW($,G,$.path,H))})).then((G)=>{return S1.mergeArray(X,G)});let J=[...$.data].map((G,H)=>{return Y.type._parseSync(new DW($,G,$.path,H))});return S1.mergeArray(X,J)}get element(){return this._def.type}min(W,$){return new fW({...this._def,minLength:{value:W,message:l.toString($)}})}max(W,$){return new fW({...this._def,maxLength:{value:W,message:l.toString($)}})}length(W,$){return new fW({...this._def,exactLength:{value:W,message:l.toString($)}})}nonempty(W){return this.min(1,W)}}fW.create=(W,$)=>{return new fW({type:W,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...G0($)})};function x8(W){if(W instanceof l0){let $={};for(let X in W.shape){let Y=W.shape[X];$[X]=XW.create(x8(Y))}return new l0({...W._def,shape:()=>$})}else if(W instanceof fW)return new fW({...W._def,type:x8(W.element)});else if(W instanceof XW)return XW.create(x8(W.unwrap()));else if(W instanceof E2)return E2.create(x8(W.unwrap()));else if(W instanceof iW)return iW.create(W.items.map(($)=>x8($)));else return W}class l0 extends T0{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let W=this._def.shape(),$=K0.objectKeys(W);return this._cached={shape:W,keys:$}}_parse(W){if(this._getType(W)!==p.object){let z=this._getOrReturnCtx(W);return b(z,{code:Z.invalid_type,expected:p.object,received:z.parsedType}),W0}let{status:X,ctx:Y}=this._processInputParams(W),{shape:J,keys:G}=this._getCached(),H=[];if(!(this._def.catchall instanceof oW&&this._def.unknownKeys==="strip")){for(let z in Y.data)if(!G.includes(z))H.push(z)}let Q=[];for(let z of G){let F=J[z],T=Y.data[z];Q.push({key:{status:"valid",value:z},value:F._parse(new DW(Y,T,Y.path,z)),alwaysSet:z in Y.data})}if(this._def.catchall instanceof oW){let z=this._def.unknownKeys;if(z==="passthrough")for(let F of H)Q.push({key:{status:"valid",value:F},value:{status:"valid",value:Y.data[F]}});else if(z==="strict"){if(H.length>0)b(Y,{code:Z.unrecognized_keys,keys:H}),X.dirty()}else if(z==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let z=this._def.catchall;for(let F of H){let T=Y.data[F];Q.push({key:{status:"valid",value:F},value:z._parse(new DW(Y,T,Y.path,F)),alwaysSet:F in Y.data})}}if(Y.common.async)return Promise.resolve().then(async()=>{let z=[];for(let F of Q){let T=await F.key,U=await F.value;z.push({key:T,value:U,alwaysSet:F.alwaysSet})}return z}).then((z)=>{return S1.mergeObjectSync(X,z)});else return S1.mergeObjectSync(X,Q)}get shape(){return this._def.shape()}strict(W){return l.errToObj,new l0({...this._def,unknownKeys:"strict",...W!==void 0?{errorMap:($,X)=>{var Y,J,G,H;let Q=(G=(J=(Y=this._def).errorMap)===null||J===void 0?void 0:J.call(Y,$,X).message)!==null&&G!==void 0?G:X.defaultError;if($.code==="unrecognized_keys")return{message:(H=l.errToObj(W).message)!==null&&H!==void 0?H:Q};return{message:Q}}}:{}})}strip(){return new l0({...this._def,unknownKeys:"strip"})}passthrough(){return new l0({...this._def,unknownKeys:"passthrough"})}extend(W){return new l0({...this._def,shape:()=>({...this._def.shape(),...W})})}merge(W){return new l0({unknownKeys:W._def.unknownKeys,catchall:W._def.catchall,shape:()=>({...this._def.shape(),...W._def.shape()}),typeName:S.ZodObject})}setKey(W,$){return this.augment({[W]:$})}catchall(W){return new l0({...this._def,catchall:W})}pick(W){let $={};return K0.objectKeys(W).forEach((X)=>{if(W[X]&&this.shape[X])$[X]=this.shape[X]}),new l0({...this._def,shape:()=>$})}omit(W){let $={};return K0.objectKeys(this.shape).forEach((X)=>{if(!W[X])$[X]=this.shape[X]}),new l0({...this._def,shape:()=>$})}deepPartial(){return x8(this)}partial(W){let $={};return K0.objectKeys(this.shape).forEach((X)=>{let Y=this.shape[X];if(W&&!W[X])$[X]=Y;else $[X]=Y.optional()}),new l0({...this._def,shape:()=>$})}required(W){let $={};return K0.objectKeys(this.shape).forEach((X)=>{if(W&&!W[X])$[X]=this.shape[X];else{let J=this.shape[X];while(J instanceof XW)J=J._def.innerType;$[X]=J}}),new l0({...this._def,shape:()=>$})}keyof(){return dG(K0.objectKeys(this.shape))}}l0.create=(W,$)=>{return new l0({shape:()=>W,unknownKeys:"strip",catchall:oW.create(),typeName:S.ZodObject,...G0($)})};l0.strictCreate=(W,$)=>{return new l0({shape:()=>W,unknownKeys:"strict",catchall:oW.create(),typeName:S.ZodObject,...G0($)})};l0.lazycreate=(W,$)=>{return new l0({shape:W,unknownKeys:"strip",catchall:oW.create(),typeName:S.ZodObject,...G0($)})};class X4 extends T0{_parse(W){let{ctx:$}=this._processInputParams(W),X=this._def.options;function Y(J){for(let H of J)if(H.result.status==="valid")return H.result;for(let H of J)if(H.result.status==="dirty")return $.common.issues.push(...H.ctx.common.issues),H.result;let G=J.map((H)=>new $W(H.ctx.common.issues));return b($,{code:Z.invalid_union,unionErrors:G}),W0}if($.common.async)return Promise.all(X.map(async(J)=>{let G={...$,common:{...$.common,issues:[]},parent:null};return{result:await J._parseAsync({data:$.data,path:$.path,parent:G}),ctx:G}})).then(Y);else{let J=void 0,G=[];for(let Q of X){let z={...$,common:{...$.common,issues:[]},parent:null},F=Q._parseSync({data:$.data,path:$.path,parent:z});if(F.status==="valid")return F;else if(F.status==="dirty"&&!J)J={result:F,ctx:z};if(z.common.issues.length)G.push(z.common.issues)}if(J)return $.common.issues.push(...J.ctx.common.issues),J.result;let H=G.map((Q)=>new $W(Q));return b($,{code:Z.invalid_union,unionErrors:H}),W0}}get options(){return this._def.options}}X4.create=(W,$)=>{return new X4({options:W,typeName:S.ZodUnion,...G0($)})};var dW=(W)=>{if(W instanceof J4)return dW(W.schema);else if(W instanceof PW)return dW(W.innerType());else if(W instanceof G4)return[W.value];else if(W instanceof l2)return W.options;else if(W instanceof H4)return K0.objectValues(W.enum);else if(W instanceof Q4)return dW(W._def.innerType);else if(W instanceof W4)return[void 0];else if(W instanceof $4)return[null];else if(W instanceof XW)return[void 0,...dW(W.unwrap())];else if(W instanceof E2)return[null,...dW(W.unwrap())];else if(W instanceof b9)return dW(W.unwrap());else if(W instanceof F4)return dW(W.unwrap());else if(W instanceof z4)return dW(W._def.innerType);else return[]};class v9 extends T0{_parse(W){let{ctx:$}=this._processInputParams(W);if($.parsedType!==p.object)return b($,{code:Z.invalid_type,expected:p.object,received:$.parsedType}),W0;let X=this.discriminator,Y=$.data[X],J=this.optionsMap.get(Y);if(!J)return b($,{code:Z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[X]}),W0;if($.common.async)return J._parseAsync({data:$.data,path:$.path,parent:$});else return J._parseSync({data:$.data,path:$.path,parent:$})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(W,$,X){let Y=new Map;for(let J of $){let G=dW(J.shape[W]);if(!G.length)throw new Error(`A discriminator value for key \`${W}\` could not be extracted from all schema options`);for(let H of G){if(Y.has(H))throw new Error(`Discriminator property ${String(W)} has duplicate value ${String(H)}`);Y.set(H,J)}}return new v9({typeName:S.ZodDiscriminatedUnion,discriminator:W,options:$,optionsMap:Y,...G0(X)})}}function x9(W,$){let X=A2(W),Y=A2($);if(W===$)return{valid:!0,data:W};else if(X===p.object&&Y===p.object){let J=K0.objectKeys($),G=K0.objectKeys(W).filter((Q)=>J.indexOf(Q)!==-1),H={...W,...$};for(let Q of G){let z=x9(W[Q],$[Q]);if(!z.valid)return{valid:!1};H[Q]=z.data}return{valid:!0,data:H}}else if(X===p.array&&Y===p.array){if(W.length!==$.length)return{valid:!1};let J=[];for(let G=0;G<W.length;G++){let H=W[G],Q=$[G],z=x9(H,Q);if(!z.valid)return{valid:!1};J.push(z.data)}return{valid:!0,data:J}}else if(X===p.date&&Y===p.date&&+W===+$)return{valid:!0,data:W};else return{valid:!1}}class Y4 extends T0{_parse(W){let{status:$,ctx:X}=this._processInputParams(W),Y=(J,G)=>{if(hG(J)||hG(G))return W0;let H=x9(J.value,G.value);if(!H.valid)return b(X,{code:Z.invalid_intersection_types}),W0;if(gG(J)||gG(G))$.dirty();return{status:$.value,value:H.data}};if(X.common.async)return Promise.all([this._def.left._parseAsync({data:X.data,path:X.path,parent:X}),this._def.right._parseAsync({data:X.data,path:X.path,parent:X})]).then(([J,G])=>Y(J,G));else return Y(this._def.left._parseSync({data:X.data,path:X.path,parent:X}),this._def.right._parseSync({data:X.data,path:X.path,parent:X}))}}Y4.create=(W,$,X)=>{return new Y4({left:W,right:$,typeName:S.ZodIntersection,...G0(X)})};class iW extends T0{_parse(W){let{status:$,ctx:X}=this._processInputParams(W);if(X.parsedType!==p.array)return b(X,{code:Z.invalid_type,expected:p.array,received:X.parsedType}),W0;if(X.data.length<this._def.items.length)return b(X,{code:Z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),W0;if(!this._def.rest&&X.data.length>this._def.items.length)b(X,{code:Z.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),$.dirty();let J=[...X.data].map((G,H)=>{let Q=this._def.items[H]||this._def.rest;if(!Q)return null;return Q._parse(new DW(X,G,X.path,H))}).filter((G)=>!!G);if(X.common.async)return Promise.all(J).then((G)=>{return S1.mergeArray($,G)});else return S1.mergeArray($,J)}get items(){return this._def.items}rest(W){return new iW({...this._def,rest:W})}}iW.create=(W,$)=>{if(!Array.isArray(W))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new iW({items:W,typeName:S.ZodTuple,rest:null,...G0($)})};class TX extends T0{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(W){let{status:$,ctx:X}=this._processInputParams(W);if(X.parsedType!==p.object)return b(X,{code:Z.invalid_type,expected:p.object,received:X.parsedType}),W0;let Y=[],J=this._def.keyType,G=this._def.valueType;for(let H in X.data)Y.push({key:J._parse(new DW(X,H,X.path,H)),value:G._parse(new DW(X,X.data[H],X.path,H)),alwaysSet:H in X.data});if(X.common.async)return S1.mergeObjectAsync($,Y);else return S1.mergeObjectSync($,Y)}get element(){return this._def.valueType}static create(W,$,X){if($ instanceof T0)return new TX({keyType:W,valueType:$,typeName:S.ZodRecord,...G0(X)});return new TX({keyType:lW.create(),valueType:W,typeName:S.ZodRecord,...G0($)})}}class UX extends T0{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(W){let{status:$,ctx:X}=this._processInputParams(W);if(X.parsedType!==p.map)return b(X,{code:Z.invalid_type,expected:p.map,received:X.parsedType}),W0;let Y=this._def.keyType,J=this._def.valueType,G=[...X.data.entries()].map(([H,Q],z)=>{return{key:Y._parse(new DW(X,H,X.path,[z,"key"])),value:J._parse(new DW(X,Q,X.path,[z,"value"]))}});if(X.common.async){let H=new Map;return Promise.resolve().then(async()=>{for(let Q of G){let z=await Q.key,F=await Q.value;if(z.status==="aborted"||F.status==="aborted")return W0;if(z.status==="dirty"||F.status==="dirty")$.dirty();H.set(z.value,F.value)}return{status:$.value,value:H}})}else{let H=new Map;for(let Q of G){let{key:z,value:F}=Q;if(z.status==="aborted"||F.status==="aborted")return W0;if(z.status==="dirty"||F.status==="dirty")$.dirty();H.set(z.value,F.value)}return{status:$.value,value:H}}}}UX.create=(W,$,X)=>{return new UX({valueType:$,keyType:W,typeName:S.ZodMap,...G0(X)})};class h8 extends T0{_parse(W){let{status:$,ctx:X}=this._processInputParams(W);if(X.parsedType!==p.set)return b(X,{code:Z.invalid_type,expected:p.set,received:X.parsedType}),W0;let Y=this._def;if(Y.minSize!==null){if(X.data.size<Y.minSize.value)b(X,{code:Z.too_small,minimum:Y.minSize.value,type:"set",inclusive:!0,exact:!1,message:Y.minSize.message}),$.dirty()}if(Y.maxSize!==null){if(X.data.size>Y.maxSize.value)b(X,{code:Z.too_big,maximum:Y.maxSize.value,type:"set",inclusive:!0,exact:!1,message:Y.maxSize.message}),$.dirty()}let J=this._def.valueType;function G(Q){let z=new Set;for(let F of Q){if(F.status==="aborted")return W0;if(F.status==="dirty")$.dirty();z.add(F.value)}return{status:$.value,value:z}}let H=[...X.data.values()].map((Q,z)=>J._parse(new DW(X,Q,X.path,z)));if(X.common.async)return Promise.all(H).then((Q)=>G(Q));else return G(H)}min(W,$){return new h8({...this._def,minSize:{value:W,message:l.toString($)}})}max(W,$){return new h8({...this._def,maxSize:{value:W,message:l.toString($)}})}size(W,$){return this.min(W,$).max(W,$)}nonempty(W){return this.min(1,W)}}h8.create=(W,$)=>{return new h8({valueType:W,minSize:null,maxSize:null,typeName:S.ZodSet,...G0($)})};class a$ extends T0{constructor(){super(...arguments);this.validate=this.implement}_parse(W){let{ctx:$}=this._processInputParams(W);if($.parsedType!==p.function)return b($,{code:Z.invalid_type,expected:p.function,received:$.parsedType}),W0;function X(H,Q){return P9({data:H,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,f9(),s$].filter((z)=>!!z),issueData:{code:Z.invalid_arguments,argumentsError:Q}})}function Y(H,Q){return P9({data:H,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,f9(),s$].filter((z)=>!!z),issueData:{code:Z.invalid_return_type,returnTypeError:Q}})}let J={errorMap:$.common.contextualErrorMap},G=$.data;if(this._def.returns instanceof g8){let H=this;return x1(async function(...Q){let z=new $W([]),F=await H._def.args.parseAsync(Q,J).catch((M)=>{throw z.addIssue(X(Q,M)),z}),T=await Reflect.apply(G,this,F);return await H._def.returns._def.type.parseAsync(T,J).catch((M)=>{throw z.addIssue(Y(T,M)),z})})}else{let H=this;return x1(function(...Q){let z=H._def.args.safeParse(Q,J);if(!z.success)throw new $W([X(Q,z.error)]);let F=Reflect.apply(G,this,z.data),T=H._def.returns.safeParse(F,J);if(!T.success)throw new $W([Y(F,T.error)]);return T.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...W){return new a$({...this._def,args:iW.create(W).rest(d2.create())})}returns(W){return new a$({...this._def,returns:W})}implement(W){return this.parse(W)}strictImplement(W){return this.parse(W)}static create(W,$,X){return new a$({args:W?W:iW.create([]).rest(d2.create()),returns:$||d2.create(),typeName:S.ZodFunction,...G0(X)})}}class J4 extends T0{get schema(){return this._def.getter()}_parse(W){let{ctx:$}=this._processInputParams(W);return this._def.getter()._parse({data:$.data,path:$.path,parent:$})}}J4.create=(W,$)=>{return new J4({getter:W,typeName:S.ZodLazy,...G0($)})};class G4 extends T0{_parse(W){if(W.data!==this._def.value){let $=this._getOrReturnCtx(W);return b($,{received:$.data,code:Z.invalid_literal,expected:this._def.value}),W0}return{status:"valid",value:W.data}}get value(){return this._def.value}}G4.create=(W,$)=>{return new G4({value:W,typeName:S.ZodLiteral,...G0($)})};function dG(W,$){return new l2({values:W,typeName:S.ZodEnum,...G0($)})}class l2 extends T0{constructor(){super(...arguments);r$.set(this,void 0)}_parse(W){if(typeof W.data!=="string"){let $=this._getOrReturnCtx(W),X=this._def.values;return b($,{expected:K0.joinValues(X),received:$.parsedType,code:Z.invalid_type}),W0}if(!GX(this,r$,"f"))pG(this,r$,new Set(this._def.values),"f");if(!GX(this,r$,"f").has(W.data)){let $=this._getOrReturnCtx(W),X=this._def.values;return b($,{received:$.data,code:Z.invalid_enum_value,options:X}),W0}return x1(W.data)}get options(){return this._def.values}get enum(){let W={};for(let $ of this._def.values)W[$]=$;return W}get Values(){let W={};for(let $ of this._def.values)W[$]=$;return W}get Enum(){let W={};for(let $ of this._def.values)W[$]=$;return W}extract(W,$=this._def){return l2.create(W,{...this._def,...$})}exclude(W,$=this._def){return l2.create(this.options.filter((X)=>!W.includes(X)),{...this._def,...$})}}r$=new WeakMap;l2.create=dG;class H4 extends T0{constructor(){super(...arguments);t$.set(this,void 0)}_parse(W){let $=K0.getValidEnumValues(this._def.values),X=this._getOrReturnCtx(W);if(X.parsedType!==p.string&&X.parsedType!==p.number){let Y=K0.objectValues($);return b(X,{expected:K0.joinValues(Y),received:X.parsedType,code:Z.invalid_type}),W0}if(!GX(this,t$,"f"))pG(this,t$,new Set(K0.getValidEnumValues(this._def.values)),"f");if(!GX(this,t$,"f").has(W.data)){let Y=K0.objectValues($);return b(X,{received:X.data,code:Z.invalid_enum_value,options:Y}),W0}return x1(W.data)}get enum(){return this._def.values}}t$=new WeakMap;H4.create=(W,$)=>{return new H4({values:W,typeName:S.ZodNativeEnum,...G0($)})};class g8 extends T0{unwrap(){return this._def.type}_parse(W){let{ctx:$}=this._processInputParams(W);if($.parsedType!==p.promise&&$.common.async===!1)return b($,{code:Z.invalid_type,expected:p.promise,received:$.parsedType}),W0;let X=$.parsedType===p.promise?$.data:Promise.resolve($.data);return x1(X.then((Y)=>{return this._def.type.parseAsync(Y,{path:$.path,errorMap:$.common.contextualErrorMap})}))}}g8.create=(W,$)=>{return new g8({type:W,typeName:S.ZodPromise,...G0($)})};class PW extends T0{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===S.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(W){let{status:$,ctx:X}=this._processInputParams(W),Y=this._def.effect||null,J={addIssue:(G)=>{if(b(X,G),G.fatal)$.abort();else $.dirty()},get path(){return X.path}};if(J.addIssue=J.addIssue.bind(J),Y.type==="preprocess"){let G=Y.transform(X.data,J);if(X.common.async)return Promise.resolve(G).then(async(H)=>{if($.value==="aborted")return W0;let Q=await this._def.schema._parseAsync({data:H,path:X.path,parent:X});if(Q.status==="aborted")return W0;if(Q.status==="dirty")return n$(Q.value);if($.value==="dirty")return n$(Q.value);return Q});else{if($.value==="aborted")return W0;let H=this._def.schema._parseSync({data:G,path:X.path,parent:X});if(H.status==="aborted")return W0;if(H.status==="dirty")return n$(H.value);if($.value==="dirty")return n$(H.value);return H}}if(Y.type==="refinement"){let G=(H)=>{let Q=Y.refinement(H,J);if(X.common.async)return Promise.resolve(Q);if(Q instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return H};if(X.common.async===!1){let H=this._def.schema._parseSync({data:X.data,path:X.path,parent:X});if(H.status==="aborted")return W0;if(H.status==="dirty")$.dirty();return G(H.value),{status:$.value,value:H.value}}else return this._def.schema._parseAsync({data:X.data,path:X.path,parent:X}).then((H)=>{if(H.status==="aborted")return W0;if(H.status==="dirty")$.dirty();return G(H.value).then(()=>{return{status:$.value,value:H.value}})})}if(Y.type==="transform")if(X.common.async===!1){let G=this._def.schema._parseSync({data:X.data,path:X.path,parent:X});if(!v8(G))return G;let H=Y.transform(G.value,J);if(H instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:$.value,value:H}}else return this._def.schema._parseAsync({data:X.data,path:X.path,parent:X}).then((G)=>{if(!v8(G))return G;return Promise.resolve(Y.transform(G.value,J)).then((H)=>({status:$.value,value:H}))});K0.assertNever(Y)}}PW.create=(W,$,X)=>{return new PW({schema:W,typeName:S.ZodEffects,effect:$,...G0(X)})};PW.createWithPreprocess=(W,$,X)=>{return new PW({schema:$,effect:{type:"preprocess",transform:W},typeName:S.ZodEffects,...G0(X)})};class XW extends T0{_parse(W){if(this._getType(W)===p.undefined)return x1(void 0);return this._def.innerType._parse(W)}unwrap(){return this._def.innerType}}XW.create=(W,$)=>{return new XW({innerType:W,typeName:S.ZodOptional,...G0($)})};class E2 extends T0{_parse(W){if(this._getType(W)===p.null)return x1(null);return this._def.innerType._parse(W)}unwrap(){return this._def.innerType}}E2.create=(W,$)=>{return new E2({innerType:W,typeName:S.ZodNullable,...G0($)})};class Q4 extends T0{_parse(W){let{ctx:$}=this._processInputParams(W),X=$.data;if($.parsedType===p.undefined)X=this._def.defaultValue();return this._def.innerType._parse({data:X,path:$.path,parent:$})}removeDefault(){return this._def.innerType}}Q4.create=(W,$)=>{return new Q4({innerType:W,typeName:S.ZodDefault,defaultValue:typeof $.default==="function"?$.default:()=>$.default,...G0($)})};class z4 extends T0{_parse(W){let{ctx:$}=this._processInputParams(W),X={...$,common:{...$.common,issues:[]}},Y=this._def.innerType._parse({data:X.data,path:X.path,parent:{...X}});if(JX(Y))return Y.then((J)=>{return{status:"valid",value:J.status==="valid"?J.value:this._def.catchValue({get error(){return new $W(X.common.issues)},input:X.data})}});else return{status:"valid",value:Y.status==="valid"?Y.value:this._def.catchValue({get error(){return new $W(X.common.issues)},input:X.data})}}removeCatch(){return this._def.innerType}}z4.create=(W,$)=>{return new z4({innerType:W,typeName:S.ZodCatch,catchValue:typeof $.catch==="function"?$.catch:()=>$.catch,...G0($)})};class wX extends T0{_parse(W){if(this._getType(W)!==p.nan){let X=this._getOrReturnCtx(W);return b(X,{code:Z.invalid_type,expected:p.nan,received:X.parsedType}),W0}return{status:"valid",value:W.data}}}wX.create=(W)=>{return new wX({typeName:S.ZodNaN,...G0(W)})};var LZ=Symbol("zod_brand");class b9 extends T0{_parse(W){let{ctx:$}=this._processInputParams(W),X=$.data;return this._def.type._parse({data:X,path:$.path,parent:$})}unwrap(){return this._def.type}}class MX extends T0{_parse(W){let{status:$,ctx:X}=this._processInputParams(W);if(X.common.async)return(async()=>{let J=await this._def.in._parseAsync({data:X.data,path:X.path,parent:X});if(J.status==="aborted")return W0;if(J.status==="dirty")return $.dirty(),n$(J.value);else return this._def.out._parseAsync({data:J.value,path:X.path,parent:X})})();else{let Y=this._def.in._parseSync({data:X.data,path:X.path,parent:X});if(Y.status==="aborted")return W0;if(Y.status==="dirty")return $.dirty(),{status:"dirty",value:Y.value};else return this._def.out._parseSync({data:Y.value,path:X.path,parent:X})}}static create(W,$){return new MX({in:W,out:$,typeName:S.ZodPipeline})}}class F4 extends T0{_parse(W){let $=this._def.innerType._parse(W),X=(Y)=>{if(v8(Y))Y.value=Object.freeze(Y.value);return Y};return JX($)?$.then((Y)=>X(Y)):X($)}unwrap(){return this._def.innerType}}F4.create=(W,$)=>{return new F4({innerType:W,typeName:S.ZodReadonly,...G0($)})};var AZ={object:l0.lazycreate},S;(function(W){W.ZodString="ZodString",W.ZodNumber="ZodNumber",W.ZodNaN="ZodNaN",W.ZodBigInt="ZodBigInt",W.ZodBoolean="ZodBoolean",W.ZodDate="ZodDate",W.ZodSymbol="ZodSymbol",W.ZodUndefined="ZodUndefined",W.ZodNull="ZodNull",W.ZodAny="ZodAny",W.ZodUnknown="ZodUnknown",W.ZodNever="ZodNever",W.ZodVoid="ZodVoid",W.ZodArray="ZodArray",W.ZodObject="ZodObject",W.ZodUnion="ZodUnion",W.ZodDiscriminatedUnion="ZodDiscriminatedUnion",W.ZodIntersection="ZodIntersection",W.ZodTuple="ZodTuple",W.ZodRecord="ZodRecord",W.ZodMap="ZodMap",W.ZodSet="ZodSet",W.ZodFunction="ZodFunction",W.ZodLazy="ZodLazy",W.ZodLiteral="ZodLiteral",W.ZodEnum="ZodEnum",W.ZodEffects="ZodEffects",W.ZodNativeEnum="ZodNativeEnum",W.ZodOptional="ZodOptional",W.ZodNullable="ZodNullable",W.ZodDefault="ZodDefault",W.ZodCatch="ZodCatch",W.ZodPromise="ZodPromise",W.ZodBranded="ZodBranded",W.ZodPipeline="ZodPipeline",W.ZodReadonly="ZodReadonly"})(S||(S={}));var EZ=lW.create,NZ=b8.create,BZ=wX.create,RZ=y8.create,ZZ=HX.create,SZ=e$.create,qZ=QX.create,CZ=W4.create,kZ=$4.create,IZ=zX.create,jZ=d2.create,fZ=oW.create,PZ=FX.create,xZ=fW.create,vZ=l0.create,bZ=l0.strictCreate,yZ=X4.create,hZ=v9.create,gZ=Y4.create,mZ=iW.create,pZ=TX.create,uZ=UX.create,cZ=h8.create,dZ=a$.create,lZ=J4.create,oZ=G4.create,iZ=l2.create,nZ=H4.create,rZ=g8.create,tZ=PW.create,aZ=XW.create,sZ=E2.create,eZ=PW.createWithPreprocess,WS=MX.create;function lG(){return{}}function oG(W,$){let X={type:"array"};if(W.type?._def&&W.type?._def?.typeName!==S.ZodAny)X.items=s(W.type._def,{...$,currentPath:[...$.currentPath,"items"]});if(W.minLength)V0(X,"minItems",W.minLength.value,W.minLength.message,$);if(W.maxLength)V0(X,"maxItems",W.maxLength.value,W.maxLength.message,$);if(W.exactLength)V0(X,"minItems",W.exactLength.value,W.exactLength.message,$),V0(X,"maxItems",W.exactLength.value,W.exactLength.message,$);return X}function iG(W,$){let X={type:"integer",format:"int64"};if(!W.checks)return X;for(let Y of W.checks)switch(Y.kind){case"min":if($.target==="jsonSchema7")if(Y.inclusive)V0(X,"minimum",Y.value,Y.message,$);else V0(X,"exclusiveMinimum",Y.value,Y.message,$);else{if(!Y.inclusive)X.exclusiveMinimum=!0;V0(X,"minimum",Y.value,Y.message,$)}break;case"max":if($.target==="jsonSchema7")if(Y.inclusive)V0(X,"maximum",Y.value,Y.message,$);else V0(X,"exclusiveMaximum",Y.value,Y.message,$);else{if(!Y.inclusive)X.exclusiveMaximum=!0;V0(X,"maximum",Y.value,Y.message,$)}break;case"multipleOf":V0(X,"multipleOf",Y.value,Y.message,$);break}return X}function nG(){return{type:"boolean"}}function _X(W,$){return s(W.type._def,$)}var rG=(W,$)=>{return s(W.innerType._def,$)};function y9(W,$,X){let Y=X??$.dateStrategy;if(Array.isArray(Y))return{anyOf:Y.map((J,G)=>y9(W,$,J))};switch(Y){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return XD(W,$)}}var XD=(W,$)=>{let X={type:"integer",format:"unix-time"};if($.target==="openApi3")return X;for(let Y of W.checks)switch(Y.kind){case"min":V0(X,"minimum",Y.value,Y.message,$);break;case"max":V0(X,"maximum",Y.value,Y.message,$);break}return X};function tG(W,$){return{...s(W.innerType._def,$),default:W.defaultValue()}}function aG(W,$){return $.effectStrategy==="input"?s(W.schema._def,$):{}}function sG(W){return{type:"string",enum:Array.from(W.values)}}var YD=(W)=>{if("type"in W&&W.type==="string")return!1;return"allOf"in W};function eG(W,$){let X=[s(W.left._def,{...$,currentPath:[...$.currentPath,"allOf","0"]}),s(W.right._def,{...$,currentPath:[...$.currentPath,"allOf","1"]})].filter((G)=>!!G),Y=$.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,J=[];return X.forEach((G)=>{if(YD(G)){if(J.push(...G.allOf),G.unevaluatedProperties===void 0)Y=void 0}else{let H=G;if("additionalProperties"in G&&G.additionalProperties===!1){let{additionalProperties:Q,...z}=G;H=z}else Y=void 0;J.push(H)}}),J.length?{allOf:J,...Y}:void 0}function W3(W,$){let X=typeof W.value;if(X!=="bigint"&&X!=="number"&&X!=="boolean"&&X!=="string")return{type:Array.isArray(W.value)?"array":"object"};if($.target==="openApi3")return{type:X==="bigint"?"integer":X,enum:[W.value]};return{type:X==="bigint"?"integer":X,const:W.value}}var h9=void 0,VW={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(h9===void 0)h9=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return h9},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])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,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})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function DX(W,$){let X={type:"string"};if(W.checks)for(let Y of W.checks)switch(Y.kind){case"min":V0(X,"minLength",typeof X.minLength==="number"?Math.max(X.minLength,Y.value):Y.value,Y.message,$);break;case"max":V0(X,"maxLength",typeof X.maxLength==="number"?Math.min(X.maxLength,Y.value):Y.value,Y.message,$);break;case"email":switch($.emailStrategy){case"format:email":OW(X,"email",Y.message,$);break;case"format:idn-email":OW(X,"idn-email",Y.message,$);break;case"pattern:zod":q1(X,VW.email,Y.message,$);break}break;case"url":OW(X,"uri",Y.message,$);break;case"uuid":OW(X,"uuid",Y.message,$);break;case"regex":q1(X,Y.regex,Y.message,$);break;case"cuid":q1(X,VW.cuid,Y.message,$);break;case"cuid2":q1(X,VW.cuid2,Y.message,$);break;case"startsWith":q1(X,RegExp(`^${g9(Y.value,$)}`),Y.message,$);break;case"endsWith":q1(X,RegExp(`${g9(Y.value,$)}$`),Y.message,$);break;case"datetime":OW(X,"date-time",Y.message,$);break;case"date":OW(X,"date",Y.message,$);break;case"time":OW(X,"time",Y.message,$);break;case"duration":OW(X,"duration",Y.message,$);break;case"length":V0(X,"minLength",typeof X.minLength==="number"?Math.max(X.minLength,Y.value):Y.value,Y.message,$),V0(X,"maxLength",typeof X.maxLength==="number"?Math.min(X.maxLength,Y.value):Y.value,Y.message,$);break;case"includes":{q1(X,RegExp(g9(Y.value,$)),Y.message,$);break}case"ip":{if(Y.version!=="v6")OW(X,"ipv4",Y.message,$);if(Y.version!=="v4")OW(X,"ipv6",Y.message,$);break}case"base64url":q1(X,VW.base64url,Y.message,$);break;case"jwt":q1(X,VW.jwt,Y.message,$);break;case"cidr":{if(Y.version!=="v6")q1(X,VW.ipv4Cidr,Y.message,$);if(Y.version!=="v4")q1(X,VW.ipv6Cidr,Y.message,$);break}case"emoji":q1(X,VW.emoji(),Y.message,$);break;case"ulid":{q1(X,VW.ulid,Y.message,$);break}case"base64":{switch($.base64Strategy){case"format:binary":{OW(X,"binary",Y.message,$);break}case"contentEncoding:base64":{V0(X,"contentEncoding","base64",Y.message,$);break}case"pattern:zod":{q1(X,VW.base64,Y.message,$);break}}break}case"nanoid":q1(X,VW.nanoid,Y.message,$);case"toLowerCase":case"toUpperCase":case"trim":break;default:((J)=>{})(Y)}return X}function g9(W,$){return $.patternStrategy==="escape"?GD(W):W}var JD=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function GD(W){let $="";for(let X=0;X<W.length;X++){if(!JD.has(W[X]))$+="\\";$+=W[X]}return $}function OW(W,$,X,Y){if(W.format||W.anyOf?.some((J)=>J.format)){if(!W.anyOf)W.anyOf=[];if(W.format){if(W.anyOf.push({format:W.format,...W.errorMessage&&Y.errorMessages&&{errorMessage:{format:W.errorMessage.format}}}),delete W.format,W.errorMessage){if(delete W.errorMessage.format,Object.keys(W.errorMessage).length===0)delete W.errorMessage}}W.anyOf.push({format:$,...X&&Y.errorMessages&&{errorMessage:{format:X}}})}else V0(W,"format",$,X,Y)}function q1(W,$,X,Y){if(W.pattern||W.allOf?.some((J)=>J.pattern)){if(!W.allOf)W.allOf=[];if(W.pattern){if(W.allOf.push({pattern:W.pattern,...W.errorMessage&&Y.errorMessages&&{errorMessage:{pattern:W.errorMessage.pattern}}}),delete W.pattern,W.errorMessage){if(delete W.errorMessage.pattern,Object.keys(W.errorMessage).length===0)delete W.errorMessage}}W.allOf.push({pattern:$3($,Y),...X&&Y.errorMessages&&{errorMessage:{pattern:X}}})}else V0(W,"pattern",$3($,Y),X,Y)}function $3(W,$){if(!$.applyRegexFlags||!W.flags)return W.source;let X={i:W.flags.includes("i"),m:W.flags.includes("m"),s:W.flags.includes("s")},Y=X.i?W.source.toLowerCase():W.source,J="",G=!1,H=!1,Q=!1;for(let z=0;z<Y.length;z++){if(G){J+=Y[z],G=!1;continue}if(X.i){if(H){if(Y[z].match(/[a-z]/)){if(Q)J+=Y[z],J+=`${Y[z-2]}-${Y[z]}`.toUpperCase(),Q=!1;else if(Y[z+1]==="-"&&Y[z+2]?.match(/[a-z]/))J+=Y[z],Q=!0;else J+=`${Y[z]}${Y[z].toUpperCase()}`;continue}}else if(Y[z].match(/[a-z]/)){J+=`[${Y[z]}${Y[z].toUpperCase()}]`;continue}}if(X.m){if(Y[z]==="^"){J+=`(^|(?<=[\r
6
+ ]))`;continue}else if(Y[z]==="$"){J+=`($|(?=[\r
7
+ ]))`;continue}}if(X.s&&Y[z]==="."){J+=H?`${Y[z]}\r
8
+ `:`[${Y[z]}\r
9
+ ]`;continue}if(J+=Y[z],Y[z]==="\\")G=!0;else if(H&&Y[z]==="]")H=!1;else if(!H&&Y[z]==="[")H=!0}try{new RegExp(J)}catch{return console.warn(`Could not convert regex pattern at ${$.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),W.source}return J}function VX(W,$){if($.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if($.target==="openApi3"&&W.keyType?._def.typeName===S.ZodEnum)return{type:"object",required:W.keyType._def.values,properties:W.keyType._def.values.reduce((Y,J)=>({...Y,[J]:s(W.valueType._def,{...$,currentPath:[...$.currentPath,"properties",J]})??{}}),{}),additionalProperties:$.rejectedAdditionalProperties};let X={type:"object",additionalProperties:s(W.valueType._def,{...$,currentPath:[...$.currentPath,"additionalProperties"]})??$.allowedAdditionalProperties};if($.target==="openApi3")return X;if(W.keyType?._def.typeName===S.ZodString&&W.keyType._def.checks?.length){let{type:Y,...J}=DX(W.keyType._def,$);return{...X,propertyNames:J}}else if(W.keyType?._def.typeName===S.ZodEnum)return{...X,propertyNames:{enum:W.keyType._def.values}};else if(W.keyType?._def.typeName===S.ZodBranded&&W.keyType._def.type._def.typeName===S.ZodString&&W.keyType._def.type._def.checks?.length){let{type:Y,...J}=_X(W.keyType._def,$);return{...X,propertyNames:J}}return X}function X3(W,$){if($.mapStrategy==="record")return VX(W,$);let X=s(W.keyType._def,{...$,currentPath:[...$.currentPath,"items","items","0"]})||{},Y=s(W.valueType._def,{...$,currentPath:[...$.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[X,Y],minItems:2,maxItems:2}}}function Y3(W){let $=W.values,Y=Object.keys(W.values).filter((G)=>{return typeof $[$[G]]!=="number"}).map((G)=>$[G]),J=Array.from(new Set(Y.map((G)=>typeof G)));return{type:J.length===1?J[0]==="string"?"string":"number":["string","number"],enum:Y}}function J3(){return{not:{}}}function G3(W){return W.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var T4={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Q3(W,$){if($.target==="openApi3")return H3(W,$);let X=W.options instanceof Map?Array.from(W.options.values()):W.options;if(X.every((Y)=>(Y._def.typeName in T4)&&(!Y._def.checks||!Y._def.checks.length))){let Y=X.reduce((J,G)=>{let H=T4[G._def.typeName];return H&&!J.includes(H)?[...J,H]:J},[]);return{type:Y.length>1?Y:Y[0]}}else if(X.every((Y)=>Y._def.typeName==="ZodLiteral"&&!Y.description)){let Y=X.reduce((J,G)=>{let H=typeof G._def.value;switch(H){case"string":case"number":case"boolean":return[...J,H];case"bigint":return[...J,"integer"];case"object":if(G._def.value===null)return[...J,"null"];case"symbol":case"undefined":case"function":default:return J}},[]);if(Y.length===X.length){let J=Y.filter((G,H,Q)=>Q.indexOf(G)===H);return{type:J.length>1?J:J[0],enum:X.reduce((G,H)=>{return G.includes(H._def.value)?G:[...G,H._def.value]},[])}}}else if(X.every((Y)=>Y._def.typeName==="ZodEnum"))return{type:"string",enum:X.reduce((Y,J)=>[...Y,...J._def.values.filter((G)=>!Y.includes(G))],[])};return H3(W,$)}var H3=(W,$)=>{let X=(W.options instanceof Map?Array.from(W.options.values()):W.options).map((Y,J)=>s(Y._def,{...$,currentPath:[...$.currentPath,"anyOf",`${J}`]})).filter((Y)=>!!Y&&(!$.strictUnions||typeof Y==="object"&&Object.keys(Y).length>0));return X.length?{anyOf:X}:void 0};function z3(W,$){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(W.innerType._def.typeName)&&(!W.innerType._def.checks||!W.innerType._def.checks.length)){if($.target==="openApi3")return{type:T4[W.innerType._def.typeName],nullable:!0};return{type:[T4[W.innerType._def.typeName],"null"]}}if($.target==="openApi3"){let Y=s(W.innerType._def,{...$,currentPath:[...$.currentPath]});if(Y&&"$ref"in Y)return{allOf:[Y],nullable:!0};return Y&&{...Y,nullable:!0}}let X=s(W.innerType._def,{...$,currentPath:[...$.currentPath,"anyOf","0"]});return X&&{anyOf:[X,{type:"null"}]}}function F3(W,$){let X={type:"number"};if(!W.checks)return X;for(let Y of W.checks)switch(Y.kind){case"int":X.type="integer",I9(X,"type",Y.message,$);break;case"min":if($.target==="jsonSchema7")if(Y.inclusive)V0(X,"minimum",Y.value,Y.message,$);else V0(X,"exclusiveMinimum",Y.value,Y.message,$);else{if(!Y.inclusive)X.exclusiveMinimum=!0;V0(X,"minimum",Y.value,Y.message,$)}break;case"max":if($.target==="jsonSchema7")if(Y.inclusive)V0(X,"maximum",Y.value,Y.message,$);else V0(X,"exclusiveMaximum",Y.value,Y.message,$);else{if(!Y.inclusive)X.exclusiveMaximum=!0;V0(X,"maximum",Y.value,Y.message,$)}break;case"multipleOf":V0(X,"multipleOf",Y.value,Y.message,$);break}return X}function T3(W,$){let X=$.target==="openAi",Y={type:"object",properties:{}},J=[],G=W.shape();for(let Q in G){let z=G[Q];if(z===void 0||z._def===void 0)continue;let F=QD(z);if(F&&X){if(z instanceof XW)z=z._def.innerType;if(!z.isNullable())z=z.nullable();F=!1}let T=s(z._def,{...$,currentPath:[...$.currentPath,"properties",Q],propertyPath:[...$.currentPath,"properties",Q]});if(T===void 0)continue;if(Y.properties[Q]=T,!F)J.push(Q)}if(J.length)Y.required=J;let H=HD(W,$);if(H!==void 0)Y.additionalProperties=H;return Y}function HD(W,$){if(W.catchall._def.typeName!=="ZodNever")return s(W.catchall._def,{...$,currentPath:[...$.currentPath,"additionalProperties"]});switch(W.unknownKeys){case"passthrough":return $.allowedAdditionalProperties;case"strict":return $.rejectedAdditionalProperties;case"strip":return $.removeAdditionalStrategy==="strict"?$.allowedAdditionalProperties:$.rejectedAdditionalProperties}}function QD(W){try{return W.isOptional()}catch{return!0}}var U3=(W,$)=>{if($.currentPath.toString()===$.propertyPath?.toString())return s(W.innerType._def,$);let X=s(W.innerType._def,{...$,currentPath:[...$.currentPath,"anyOf","1"]});return X?{anyOf:[{not:{}},X]}:{}};var w3=(W,$)=>{if($.pipeStrategy==="input")return s(W.in._def,$);else if($.pipeStrategy==="output")return s(W.out._def,$);let X=s(W.in._def,{...$,currentPath:[...$.currentPath,"allOf","0"]}),Y=s(W.out._def,{...$,currentPath:[...$.currentPath,"allOf",X?"1":"0"]});return{allOf:[X,Y].filter((J)=>J!==void 0)}};function M3(W,$){return s(W.type._def,$)}function _3(W,$){let Y={type:"array",uniqueItems:!0,items:s(W.valueType._def,{...$,currentPath:[...$.currentPath,"items"]})};if(W.minSize)V0(Y,"minItems",W.minSize.value,W.minSize.message,$);if(W.maxSize)V0(Y,"maxItems",W.maxSize.value,W.maxSize.message,$);return Y}function D3(W,$){if(W.rest)return{type:"array",minItems:W.items.length,items:W.items.map((X,Y)=>s(X._def,{...$,currentPath:[...$.currentPath,"items",`${Y}`]})).reduce((X,Y)=>Y===void 0?X:[...X,Y],[]),additionalItems:s(W.rest._def,{...$,currentPath:[...$.currentPath,"additionalItems"]})};else return{type:"array",minItems:W.items.length,maxItems:W.items.length,items:W.items.map((X,Y)=>s(X._def,{...$,currentPath:[...$.currentPath,"items",`${Y}`]})).reduce((X,Y)=>Y===void 0?X:[...X,Y],[])}}function V3(){return{not:{}}}function O3(){return{}}var K3=(W,$)=>{return s(W.innerType._def,$)};var L3=(W,$,X)=>{switch($){case S.ZodString:return DX(W,X);case S.ZodNumber:return F3(W,X);case S.ZodObject:return T3(W,X);case S.ZodBigInt:return iG(W,X);case S.ZodBoolean:return nG();case S.ZodDate:return y9(W,X);case S.ZodUndefined:return V3();case S.ZodNull:return G3(X);case S.ZodArray:return oG(W,X);case S.ZodUnion:case S.ZodDiscriminatedUnion:return Q3(W,X);case S.ZodIntersection:return eG(W,X);case S.ZodTuple:return D3(W,X);case S.ZodRecord:return VX(W,X);case S.ZodLiteral:return W3(W,X);case S.ZodEnum:return sG(W);case S.ZodNativeEnum:return Y3(W);case S.ZodNullable:return z3(W,X);case S.ZodOptional:return U3(W,X);case S.ZodMap:return X3(W,X);case S.ZodSet:return _3(W,X);case S.ZodLazy:return()=>W.getter()._def;case S.ZodPromise:return M3(W,X);case S.ZodNaN:case S.ZodNever:return J3();case S.ZodEffects:return aG(W,X);case S.ZodAny:return lG();case S.ZodUnknown:return O3();case S.ZodDefault:return tG(W,X);case S.ZodBranded:return _X(W,X);case S.ZodReadonly:return K3(W,X);case S.ZodCatch:return rG(W,X);case S.ZodPipeline:return w3(W,X);case S.ZodFunction:case S.ZodVoid:case S.ZodSymbol:return;default:return((Y)=>{return})($)}};function s(W,$,X=!1){let Y=$.seen.get(W);if($.override){let Q=$.override?.(W,$,Y,X);if(Q!==xG)return Q}if(Y&&!X){let Q=zD(Y,$);if(Q!==void 0)return Q}let J={def:W,path:$.currentPath,jsonSchema:void 0};$.seen.set(W,J);let G=L3(W,W.typeName,$),H=typeof G==="function"?s(G(),$):G;if(H)TD(W,$,H);if($.postProcess){let Q=$.postProcess(H,W,$);return J.jsonSchema=H,Q}return J.jsonSchema=H,H}var zD=(W,$)=>{switch($.$refStrategy){case"root":return{$ref:W.path.join("/")};case"relative":return{$ref:FD($.currentPath,W.path)};case"none":case"seen":{if(W.path.length<$.currentPath.length&&W.path.every((X,Y)=>$.currentPath[Y]===X))return console.warn(`Recursive reference detected at ${$.currentPath.join("/")}! Defaulting to any`),{};return $.$refStrategy==="seen"?{}:void 0}}},FD=(W,$)=>{let X=0;for(;X<W.length&&X<$.length;X++)if(W[X]!==$[X])break;return[(W.length-X).toString(),...$.slice(X)].join("/")},TD=(W,$,X)=>{if(W.description){if(X.description=W.description,$.markdownDescription)X.markdownDescription=W.description}return X};var A3=(W,$)=>{let X=bG($),Y=typeof $==="object"&&$.definitions?Object.entries($.definitions).reduce((z,[F,T])=>({...z,[F]:s(T._def,{...X,currentPath:[...X.basePath,X.definitionPath,F]},!0)??{}}),{}):void 0,J=typeof $==="string"?$:$?.nameStrategy==="title"?void 0:$?.name,G=s(W._def,J===void 0?X:{...X,currentPath:[...X.basePath,X.definitionPath,J]},!1)??{},H=typeof $==="object"&&$.name!==void 0&&$.nameStrategy==="title"?$.name:void 0;if(H!==void 0)G.title=H;let Q=J===void 0?Y?{...G,[X.definitionPath]:Y}:G:{$ref:[...X.$refStrategy==="relative"?[]:X.basePath,X.definitionPath,J].join("/"),[X.definitionPath]:{...Y,[J]:G}};if(X.target==="jsonSchema7")Q.$schema="http://json-schema.org/draft-07/schema#";else if(X.target==="jsonSchema2019-09"||X.target==="openAi")Q.$schema="https://json-schema.org/draft/2019-09/schema#";if(X.target==="openAi"&&(("anyOf"in Q)||("oneOf"in Q)||("allOf"in Q)||("type"in Q)&&Array.isArray(Q.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return Q};var E3=A3;function N3(W,$){return function X({schema:Y,fallback:J,toJsonSchema:G=E3}){let H=G(Y);return async function Q(z,F=3){let T,U=[];while(U.length<F){T=await W(z,H,J,U);let M=await Y["~standard"].validate(T);if("value"in M)return M.value;$?.warn(`safegen failed to generate well-formed data.
21
10
  `,`Here's what was returned last time:
22
- `,JSON.stringify(z,null,"\t"),`
11
+ `,JSON.stringify(T,null,"\t"),`
23
12
  `,`Here are the issues returned from our validation:
24
- `,JSON.stringify(w.issues,null,"\t")),A.push({response:z,error:w})}return $?.error(`safegen was unable to generate well-formed data after ${M} failed attempts.`),X}}}function tG(T){return["Please generate a response in JSON that conforms to the following JSON Schema:",JSON.stringify(T,null,2)].join(`
25
- `)}var s8="RFC3986",e8={RFC1738:(T)=>String(T).replace(/%20/g,"+"),RFC3986:(T)=>String(T)},rG="RFC1738";var u_=Array.isArray,lJ=(()=>{let T=[];for(let $=0;$<256;++$)T.push("%"+(($<16?"0":"")+$.toString(16)).toUpperCase());return T})();var PF=1024,aG=(T,$,J,W,X)=>{if(T.length===0)return T;let F=T;if(typeof T==="symbol")F=Symbol.prototype.toString.call(T);else if(typeof T!=="string")F=String(T);if(J==="iso-8859-1")return escape(F).replace(/%u[0-9a-f]{4}/gi,function(G){return"%26%23"+parseInt(G.slice(2),16)+"%3B"});let Y="";for(let G=0;G<F.length;G+=PF){let H=F.length>=PF?F.slice(G,G+PF):F,M=[];for(let z=0;z<H.length;++z){let A=H.charCodeAt(z);if(A===45||A===46||A===95||A===126||A>=48&&A<=57||A>=65&&A<=90||A>=97&&A<=122||X===rG&&(A===40||A===41)){M[M.length]=H.charAt(z);continue}if(A<128){M[M.length]=lJ[A];continue}if(A<2048){M[M.length]=lJ[192|A>>6]+lJ[128|A&63];continue}if(A<55296||A>=57344){M[M.length]=lJ[224|A>>12]+lJ[128|A>>6&63]+lJ[128|A&63];continue}z+=1,A=65536+((A&1023)<<10|H.charCodeAt(z)&1023),M[M.length]=lJ[240|A>>18]+lJ[128|A>>12&63]+lJ[128|A>>6&63]+lJ[128|A&63]}Y+=M.join("")}return Y};function sG(T){if(!T||typeof T!=="object")return!1;return!!(T.constructor&&T.constructor.isBuffer&&T.constructor.isBuffer(T))}function bF(T,$){if(u_(T)){let J=[];for(let W=0;W<T.length;W+=1)J.push($(T[W]));return J}return $(T)}var c_=Object.prototype.hasOwnProperty,eG={brackets(T){return String(T)+"[]"},comma:"comma",indices(T,$){return String(T)+"["+$+"]"},repeat(T){return String(T)}},nJ=Array.isArray,o_=Array.prototype.push,T3=function(T,$){o_.apply(T,nJ($)?$:[$])},d_=Date.prototype.toISOString,O$={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:aG,encodeValuesOnly:!1,format:s8,formatter:e8[s8],indices:!1,serializeDate(T){return d_.call(T)},skipNulls:!1,strictNullHandling:!1};function l_(T){return typeof T==="string"||typeof T==="number"||typeof T==="boolean"||typeof T==="symbol"||typeof T==="bigint"}var vF={};function $3(T,$,J,W,X,F,Y,G,H,M,z,A,w,_,D,S,Z,q){let N=T,y=q,V=0,f=!1;while((y=y.get(vF))!==void 0&&!f){let E=y.get(T);if(V+=1,typeof E!=="undefined")if(E===V)throw new RangeError("Cyclic object value");else f=!0;if(typeof y.get(vF)==="undefined")V=0}if(typeof M==="function")N=M($,N);else if(N instanceof Date)N=w?.(N);else if(J==="comma"&&nJ(N))N=bF(N,function(E){if(E instanceof Date)return w?.(E);return E});if(N===null){if(F)return H&&!S?H($,O$.encoder,Z,"key",_):$;N=""}if(l_(N)||sG(N)){if(H){let E=S?$:H($,O$.encoder,Z,"key",_);return[D?.(E)+"="+D?.(H(N,O$.encoder,Z,"value",_))]}return[D?.($)+"="+D?.(String(N))]}let C=[];if(typeof N==="undefined")return C;let B;if(J==="comma"&&nJ(N)){if(S&&H)N=bF(N,H);B=[{value:N.length>0?N.join(",")||null:void 0}]}else if(nJ(M))B=M;else{let E=Object.keys(N);B=z?E.sort(z):E}let m=G?String($).replace(/\./g,"%2E"):String($),$T=W&&nJ(N)&&N.length===1?m+"[]":m;if(X&&nJ(N)&&N.length===0)return $T+"[]";for(let E=0;E<B.length;++E){let XT=B[E],n=typeof XT==="object"&&typeof XT.value!=="undefined"?XT.value:N[XT];if(Y&&n===null)continue;let MT=A&&G?XT.replace(/\./g,"%2E"):XT,kT=nJ(N)?typeof J==="function"?J($T,MT):$T:$T+(A?"."+MT:"["+MT+"]");q.set(T,V);let eT=new WeakMap;eT.set(vF,q),T3(C,$3(n,kT,J,W,X,F,Y,G,J==="comma"&&S&&nJ(N)?null:H,M,z,A,w,_,D,S,Z,eT))}return C}function n_(T=O$){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.");let $=T.charset||O$.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 J=s8;if(typeof T.format!=="undefined"){if(!c_.call(e8,T.format))throw new TypeError("Unknown format option provided.");J=T.format}let W=e8[J],X=O$.filter;if(typeof T.filter==="function"||nJ(T.filter))X=T.filter;let F;if(T.arrayFormat&&T.arrayFormat in eG)F=T.arrayFormat;else if("indices"in T)F=T.indices?"indices":"repeat";else F=O$.arrayFormat;if("commaRoundTrip"in T&&typeof T.commaRoundTrip!=="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let Y=typeof T.allowDots==="undefined"?!!T.encodeDotInKeys===!0?!0:O$.allowDots:!!T.allowDots;return{addQueryPrefix:typeof T.addQueryPrefix==="boolean"?T.addQueryPrefix:O$.addQueryPrefix,allowDots:Y,allowEmptyArrays:typeof T.allowEmptyArrays==="boolean"?!!T.allowEmptyArrays:O$.allowEmptyArrays,arrayFormat:F,charset:$,charsetSentinel:typeof T.charsetSentinel==="boolean"?T.charsetSentinel:O$.charsetSentinel,commaRoundTrip:!!T.commaRoundTrip,delimiter:typeof T.delimiter==="undefined"?O$.delimiter:T.delimiter,encode:typeof T.encode==="boolean"?T.encode:O$.encode,encodeDotInKeys:typeof T.encodeDotInKeys==="boolean"?T.encodeDotInKeys:O$.encodeDotInKeys,encoder:typeof T.encoder==="function"?T.encoder:O$.encoder,encodeValuesOnly:typeof T.encodeValuesOnly==="boolean"?T.encodeValuesOnly:O$.encodeValuesOnly,filter:X,format:J,formatter:W,serializeDate:typeof T.serializeDate==="function"?T.serializeDate:O$.serializeDate,skipNulls:typeof T.skipNulls==="boolean"?T.skipNulls:O$.skipNulls,sort:typeof T.sort==="function"?T.sort:null,strictNullHandling:typeof T.strictNullHandling==="boolean"?T.strictNullHandling:O$.strictNullHandling}}function hF(T,$={}){let J=T,W=n_($),X,F;if(typeof W.filter==="function")F=W.filter,J=F("",J);else if(nJ(W.filter))F=W.filter,X=F;let Y=[];if(typeof J!=="object"||J===null)return"";let G=eG[W.arrayFormat],H=G==="comma"&&W.commaRoundTrip;if(!X)X=Object.keys(J);if(W.sort)X.sort(W.sort);let M=new WeakMap;for(let w=0;w<X.length;++w){let _=X[w];if(W.skipNulls&&J[_]===null)continue;T3(Y,$3(J[_],_,G,H,W.allowEmptyArrays,W.strictNullHandling,W.skipNulls,W.encodeDotInKeys,W.encode?W.encoder:null,W.filter,W.sort,W.allowDots,W.serializeDate,W.format,W.formatter,W.encodeValuesOnly,W.charset,M))}let z=Y.join(W.delimiter),A=W.addQueryPrefix===!0?"?":"";if(W.charsetSentinel)if(W.charset==="iso-8859-1")A+="utf8=%26%2310003%3B&";else A+="utf8=%E2%9C%93&";return z.length>0?A+z:""}var _0="4.96.0";var J3=!1,D0=void 0,mF=void 0,t_=void 0,r_=void 0,a_=void 0,gF=void 0,s_=void 0,T4=void 0,pF=void 0,uF=void 0,cF=void 0,$4=void 0,oF=void 0;function W3(T,$={auto:!1}){if(J3)throw new Error(`you must \`import 'openai/shims/${T.kind}'\` before importing anything else from openai`);if(D0)throw new Error(`can't \`import 'openai/shims/${T.kind}'\` after \`import 'openai/shims/${D0}'\``);J3=$.auto,D0=T.kind,mF=T.fetch,t_=T.Request,r_=T.Response,a_=T.Headers,gF=T.FormData,s_=T.Blob,T4=T.File,pF=T.ReadableStream,uF=T.getMultipartRequestOptions,cF=T.getDefaultAgent,$4=T.fileFromPath,oF=T.isFsReadStream}class dF{constructor(T){this.body=T}get[Symbol.toStringTag](){return"MultipartBody"}}function X3({manuallyImported:T}={}){let $=T?"You may need to use polyfills":"Add one of these imports before your first `import \u2026 from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n",J,W,X,F;try{J=fetch,W=Request,X=Response,F=Headers}catch(Y){throw new Error(`this environment is missing the following Web Fetch API type: ${Y.message}. ${$}`)}return{kind:"web",fetch:J,Request:W,Response:X,Headers:F,FormData:typeof FormData!=="undefined"?FormData:class Y{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${$}`)}},Blob:typeof Blob!=="undefined"?Blob:class Y{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${$}`)}},File:typeof File!=="undefined"?File:class Y{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${$}`)}},ReadableStream:typeof ReadableStream!=="undefined"?ReadableStream:class Y{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${$}`)}},getMultipartRequestOptions:async(Y,G)=>({...G,body:new dF(Y)}),getDefaultAgent:(Y)=>{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:(Y)=>!1}}import{ReadStream as TD}from"fs";function F3(){let T=X3();function $(J){return J instanceof TD}return{...T,isFsReadStream:$}}var lF=()=>{if(!D0)W3(F3(),{auto:!0})};lF();class t extends Error{}class F$ extends t{constructor(T,$,J,W){super(`${F$.makeMessage(T,$,J)}`);this.status=T,this.headers=W,this.request_id=W?.["x-request-id"],this.error=$;let X=$;this.code=X?.code,this.param=X?.param,this.type=X?.type}static makeMessage(T,$,J){let W=$?.message?typeof $.message==="string"?$.message:JSON.stringify($.message):$?JSON.stringify($):J;if(T&&W)return`${T} ${W}`;if(T)return`${T} status code (no body)`;if(W)return W;return"(no status code or body)"}static generate(T,$,J,W){if(!T||!W)return new K0({message:J,cause:z4($)});let X=$?.error;if(T===400)return new J4(T,X,J,W);if(T===401)return new W4(T,X,J,W);if(T===403)return new X4(T,X,J,W);if(T===404)return new F4(T,X,J,W);if(T===409)return new Y4(T,X,J,W);if(T===422)return new G4(T,X,J,W);if(T===429)return new H4(T,X,J,W);if(T>=500)return new M4(T,X,J,W);return new F$(T,X,J,W)}}class U$ extends F${constructor({message:T}={}){super(void 0,void 0,T||"Request was aborted.",void 0)}}class K0 extends F${constructor({message:T,cause:$}){super(void 0,void 0,T||"Connection error.",void 0);if($)this.cause=$}}class S0 extends K0{constructor({message:T}={}){super({message:T??"Request timed out."})}}class J4 extends F${}class W4 extends F${}class X4 extends F${}class F4 extends F${}class Y4 extends F${}class G4 extends F${}class H4 extends F${}class M4 extends F${}class uX extends t{constructor(){super("Could not parse response content as the length limit was reached")}}class cX extends t{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}var A4=function(T,$,J,W,X){if(W==="m")throw new TypeError("Private method is not writable");if(W==="a"&&!X)throw new TypeError("Private accessor was defined without a setter");if(typeof $==="function"?T!==$||!X:!$.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return W==="a"?X.call(T,J):X?X.value=J:$.set(T,J),J},V0=function(T,$,J,W){if(J==="a"&&!W)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?T!==$||!W:!$.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return J==="m"?W:J==="a"?W.call(T):W?W.value:$.get(T)},FJ;class wW{constructor(){FJ.set(this,void 0),this.buffer=new Uint8Array,A4(this,FJ,null,"f")}decode(T){if(T==null)return[];let $=T instanceof ArrayBuffer?new Uint8Array(T):typeof T==="string"?new TextEncoder().encode(T):T,J=new Uint8Array(this.buffer.length+$.length);J.set(this.buffer),J.set($,this.buffer.length),this.buffer=J;let W=[],X;while((X=JD(this.buffer,V0(this,FJ,"f")))!=null){if(X.carriage&&V0(this,FJ,"f")==null){A4(this,FJ,X.index,"f");continue}if(V0(this,FJ,"f")!=null&&(X.index!==V0(this,FJ,"f")+1||X.carriage)){W.push(this.decodeText(this.buffer.slice(0,V0(this,FJ,"f")-1))),this.buffer=this.buffer.slice(V0(this,FJ,"f")),A4(this,FJ,null,"f");continue}let F=V0(this,FJ,"f")!==null?X.preceding-1:X.preceding,Y=this.decodeText(this.buffer.slice(0,F));W.push(Y),this.buffer=this.buffer.slice(X.index),A4(this,FJ,null,"f")}return W}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)return[];return this.decode(`
26
- `)}}FJ=new WeakMap;wW.NEWLINE_CHARS=new Set([`
27
- `,"\r"]);wW.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function JD(T,$){for(let X=$??0;X<T.length;X++){if(T[X]===10)return{preceding:X,index:X+1,carriage:!1};if(T[X]===13)return{preceding:X,index:X+1,carriage:!0}}return null}function Y3(T){for(let W=0;W<T.length-1;W++){if(T[W]===10&&T[W+1]===10)return W+2;if(T[W]===13&&T[W+1]===13)return W+2;if(T[W]===13&&T[W+1]===10&&W+3<T.length&&T[W+2]===13&&T[W+3]===10)return W+4}return-1}function nF(T){if(T[Symbol.asyncIterator])return T;let $=T.getReader();return{async next(){try{let J=await $.read();if(J?.done)$.releaseLock();return J}catch(J){throw $.releaseLock(),J}},async return(){let J=$.cancel();return $.releaseLock(),await J,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}class YJ{constructor(T,$){this.iterator=T,this.controller=$}static fromSSEResponse(T,$){let J=!1;async function*W(){if(J)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");J=!0;let X=!1;try{for await(let F of WD(T,$)){if(X)continue;if(F.data.startsWith("[DONE]")){X=!0;continue}if(F.event===null||F.event.startsWith("response.")||F.event.startsWith("transcript.")){let Y;try{Y=JSON.parse(F.data)}catch(G){throw console.error("Could not parse message into JSON:",F.data),console.error("From chunk:",F.raw),G}if(Y&&Y.error)throw new F$(void 0,Y.error,void 0,iF(T.headers));yield Y}else{let Y;try{Y=JSON.parse(F.data)}catch(G){throw console.error("Could not parse message into JSON:",F.data),console.error("From chunk:",F.raw),G}if(F.event=="error")throw new F$(void 0,Y.error,Y.message,void 0);yield{event:F.event,data:Y}}}X=!0}catch(F){if(F instanceof Error&&F.name==="AbortError")return;throw F}finally{if(!X)$.abort()}}return new YJ(W,$)}static fromReadableStream(T,$){let J=!1;async function*W(){let F=new wW,Y=nF(T);for await(let G of Y)for(let H of F.decode(G))yield H;for(let G of F.flush())yield G}async function*X(){if(J)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");J=!0;let F=!1;try{for await(let Y of W()){if(F)continue;if(Y)yield JSON.parse(Y)}F=!0}catch(Y){if(Y instanceof Error&&Y.name==="AbortError")return;throw Y}finally{if(!F)$.abort()}}return new YJ(X,$)}[Symbol.asyncIterator](){return this.iterator()}tee(){let T=[],$=[],J=this.iterator(),W=(X)=>{return{next:()=>{if(X.length===0){let F=J.next();T.push(F),$.push(F)}return X.shift()}}};return[new YJ(()=>W(T),this.controller),new YJ(()=>W($),this.controller)]}toReadableStream(){let T=this,$,J=new TextEncoder;return new pF({async start(){$=T[Symbol.asyncIterator]()},async pull(W){try{let{value:X,done:F}=await $.next();if(F)return W.close();let Y=J.encode(JSON.stringify(X)+`
28
- `);W.enqueue(Y)}catch(X){W.error(X)}},async cancel(){await $.return?.()}})}}async function*WD(T,$){if(!T.body)throw $.abort(),new t("Attempted to iterate over a response with no body");let J=new G3,W=new wW,X=nF(T.body);for await(let F of XD(X))for(let Y of W.decode(F)){let G=J.decode(Y);if(G)yield G}for(let F of W.flush()){let Y=J.decode(F);if(Y)yield Y}}async function*XD(T){let $=new Uint8Array;for await(let J of T){if(J==null)continue;let W=J instanceof ArrayBuffer?new Uint8Array(J):typeof J==="string"?new TextEncoder().encode(J):J,X=new Uint8Array($.length+W.length);X.set($),X.set(W,$.length),$=X;let F;while((F=Y3($))!==-1)yield $.slice(0,F),$=$.slice(F)}if($.length>0)yield $}class G3{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;let X={event:this.event,data:this.data.join(`
29
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],X}if(this.chunks.push(T),T.startsWith(":"))return null;let[$,J,W]=FD(T,":");if(W.startsWith(" "))W=W.substring(1);if($==="event")this.event=W;else if($==="data")this.data.push(W);return null}}function FD(T,$){let J=T.indexOf($);if(J!==-1)return[T.substring(0,J),$,T.substring(J+$.length)];return[T,"",""]}var H3=(T)=>T!=null&&typeof T==="object"&&typeof T.url==="string"&&typeof T.blob==="function",M3=(T)=>T!=null&&typeof T==="object"&&typeof T.name==="string"&&typeof T.lastModified==="number"&&oX(T),oX=(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",YD=(T)=>{return M3(T)||H3(T)||oF(T)};async function aF(T,$,J){if(T=await T,M3(T))return T;if(H3(T)){let X=await T.blob();$||($=new URL(T.url).pathname.split(/[\\/]/).pop()??"unknown_file");let F=oX(X)?[await X.arrayBuffer()]:[X];return new T4(F,$,J)}let W=await GD(T);if($||($=MD(T)??"unknown_file"),!J?.type){let X=W[0]?.type;if(typeof X==="string")J={...J,type:X}}return new T4(W,$,J)}async function GD(T){let $=[];if(typeof T==="string"||ArrayBuffer.isView(T)||T instanceof ArrayBuffer)$.push(T);else if(oX(T))$.push(await T.arrayBuffer());else if(zD(T))for await(let J of T)$.push(J);else throw new Error(`Unexpected data type: ${typeof T}; constructor: ${T?.constructor?.name}; props: ${HD(T)}`);return $}function HD(T){return`[${Object.getOwnPropertyNames(T).map((J)=>`"${J}"`).join(", ")}]`}function MD(T){return tF(T.name)||tF(T.filename)||tF(T.path)?.split(/[\\/]/).pop()}var tF=(T)=>{if(typeof T==="string")return T;if(typeof Buffer!=="undefined"&&T instanceof Buffer)return String(T);return},zD=(T)=>T!=null&&typeof T==="object"&&typeof T[Symbol.asyncIterator]==="function",sF=(T)=>T&&typeof T==="object"&&T.body&&T[Symbol.toStringTag]==="MultipartBody";var SJ=async(T)=>{let $=await z3(T.body);return uF($,T)},z3=async(T)=>{let $=new gF;return await Promise.all(Object.entries(T||{}).map(([J,W])=>rF($,J,W))),$};var rF=async(T,$,J)=>{if(J===void 0)return;if(J==null)throw new TypeError(`Received null for "${$}"; to pass null in FormData, you must use the string 'null'`);if(typeof J==="string"||typeof J==="number"||typeof J==="boolean")T.append($,String(J));else if(YD(J)){let W=await aF(J);T.append($,W)}else if(Array.isArray(J))await Promise.all(J.map((W)=>rF(T,$+"[]",W)));else if(typeof J==="object")await Promise.all(Object.entries(J).map(([W,X])=>rF(T,`${$}[${W}]`,X)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${J} instead`)};var wD=function(T,$,J,W,X){if(W==="m")throw new TypeError("Private method is not writable");if(W==="a"&&!X)throw new TypeError("Private accessor was defined without a setter");if(typeof $==="function"?T!==$||!X:!$.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return W==="a"?X.call(T,J):X?X.value=J:$.set(T,J),J},QD=function(T,$,J,W){if(J==="a"&&!W)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?T!==$||!W:!$.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return J==="m"?W:J==="a"?W.call(T):W?W.value:$.get(T)},w4;lF();async function _3(T){let{response:$}=T;if(T.options.stream){if(A1("response",$.status,$.url,$.headers,$.body),T.options.__streamClass)return T.options.__streamClass.fromSSEResponse($,T.controller);return YJ.fromSSEResponse($,T.controller)}if($.status===204)return null;if(T.options.__binaryResponse)return $;let W=$.headers.get("content-type")?.split(";")[0]?.trim();if(W?.includes("application/json")||W?.endsWith("+json")){let Y=await $.json();return A1("response",$.status,$.url,$.headers,Y),D3(Y,$)}let F=await $.text();return A1("response",$.status,$.url,$.headers,F),F}function D3(T,$){if(!T||typeof T!=="object"||Array.isArray(T))return T;return Object.defineProperty(T,"_request_id",{value:$.headers.get("x-request-id"),enumerable:!1})}class O4 extends Promise{constructor(T,$=_3){super((J)=>{J(null)});this.responsePromise=T,this.parseResponse=$}_thenUnwrap(T){return new O4(this.responsePromise,async($)=>D3(T(await this.parseResponse($),$),$.response))}asResponse(){return this.responsePromise.then((T)=>T.response)}async withResponse(){let[T,$]=await Promise.all([this.parse(),this.asResponse()]);return{data:T,response:$,request_id:$.headers.get("x-request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(this.parseResponse);return this.parsedPromise}then(T,$){return this.parse().then(T,$)}catch(T){return this.parse().catch(T)}finally(T){return this.parse().finally(T)}}class TY{constructor({baseURL:T,maxRetries:$=2,timeout:J=600000,httpAgent:W,fetch:X}){this.baseURL=T,this.maxRetries=eF("maxRetries",$),this.timeout=eF("timeout",J),this.httpAgent=W,this.fetch=X??mF}authHeaders(T){return{}}defaultHeaders(T){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...DD(),...this.authHeaders(T)}}validateHeaders(T,$){}defaultIdempotencyKey(){return`stainless-node-retry-${ED()}`}get(T,$){return this.methodRequest("get",T,$)}post(T,$){return this.methodRequest("post",T,$)}patch(T,$){return this.methodRequest("patch",T,$)}put(T,$){return this.methodRequest("put",T,$)}delete(T,$){return this.methodRequest("delete",T,$)}methodRequest(T,$,J){return this.request(Promise.resolve(J).then(async(W)=>{let X=W&&oX(W?.body)?new DataView(await W.body.arrayBuffer()):W?.body instanceof DataView?W.body:W?.body instanceof ArrayBuffer?new DataView(W.body):W&&ArrayBuffer.isView(W?.body)?new DataView(W.body.buffer):W?.body;return{method:T,path:$,...W,body:X}}))}getAPIList(T,$,J){return this.requestAPIList($,{method:"get",path:T,...J})}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:$=0}={}){let J={...T},{method:W,path:X,query:F,headers:Y={}}=J,G=ArrayBuffer.isView(J.body)||J.__binaryRequest&&typeof J.body==="string"?J.body:sF(J.body)?J.body.body:J.body?JSON.stringify(J.body,null,2):null,H=this.calculateContentLength(G),M=this.buildURL(X,F);if("timeout"in J)eF("timeout",J.timeout);J.timeout=J.timeout??this.timeout;let z=J.httpAgent??this.httpAgent??cF(M),A=J.timeout+1000;if(typeof z?.options?.timeout==="number"&&A>(z.options.timeout??0))z.options.timeout=A;if(this.idempotencyHeader&&W!=="get"){if(!T.idempotencyKey)T.idempotencyKey=this.defaultIdempotencyKey();Y[this.idempotencyHeader]=T.idempotencyKey}let w=this.buildHeaders({options:J,headers:Y,contentLength:H,retryCount:$});return{req:{method:W,...G&&{body:G},headers:w,...z&&{agent:z},signal:J.signal??null},url:M,timeout:J.timeout}}buildHeaders({options:T,headers:$,contentLength:J,retryCount:W}){let X={};if(J)X["content-length"]=J;let F=this.defaultHeaders(T);if(O3(X,F),O3(X,$),sF(T.body)&&D0!=="node")delete X["content-type"];if(Q4(F,"x-stainless-retry-count")===void 0&&Q4($,"x-stainless-retry-count")===void 0)X["x-stainless-retry-count"]=String(W);if(Q4(F,"x-stainless-timeout")===void 0&&Q4($,"x-stainless-timeout")===void 0&&T.timeout)X["x-stainless-timeout"]=String(Math.trunc(T.timeout/1000));return this.validateHeaders(X,$),X}async prepareOptions(T){}async prepareRequest(T,{url:$,options:J}){}parseHeaders(T){return!T?{}:(Symbol.iterator in T)?Object.fromEntries(Array.from(T).map(($)=>[...$])):{...T}}makeStatusError(T,$,J,W){return F$.generate(T,$,J,W)}request(T,$=null){return new O4(this.makeRequest(T,$))}async makeRequest(T,$){let J=await T,W=J.maxRetries??this.maxRetries;if($==null)$=W;await this.prepareOptions(J);let{req:X,url:F,timeout:Y}=this.buildRequest(J,{retryCount:W-$});if(await this.prepareRequest(X,{url:F,options:J}),A1("request",F,J,X.headers),J.signal?.aborted)throw new U$;let G=new AbortController,H=await this.fetchWithTimeout(F,X,Y,G).catch(z4);if(H instanceof Error){if(J.signal?.aborted)throw new U$;if($)return this.retryRequest(J,$);if(H.name==="AbortError")throw new S0;throw new K0({cause:H})}let M=iF(H.headers);if(!H.ok){if($&&this.shouldRetry(H)){let S=`retrying, ${$} attempts remaining`;return A1(`response (error; ${S})`,H.status,F,M),this.retryRequest(J,$,M)}let z=await H.text().catch((S)=>z4(S).message),A=KD(z),w=A?void 0:z;throw A1(`response (error; ${$?"(error; no more retries left)":"(error; not retryable)"})`,H.status,F,M,w),this.makeStatusError(H.status,A,w,M)}return{response:H,options:J,controller:G}}requestAPIList(T,$){let J=this.makeRequest($,null);return new K3(this,J,T)}buildURL(T,$){let J=VD(T)?new URL(T):new URL(this.baseURL+(this.baseURL.endsWith("/")&&T.startsWith("/")?T.slice(1):T)),W=this.defaultQuery();if(!S3(W))$={...W,...$};if(typeof $==="object"&&$&&!Array.isArray($))J.search=this.stringifyQuery($);return J.toString()}stringifyQuery(T){return Object.entries(T).filter(([$,J])=>typeof J!=="undefined").map(([$,J])=>{if(typeof J==="string"||typeof J==="number"||typeof J==="boolean")return`${encodeURIComponent($)}=${encodeURIComponent(J)}`;if(J===null)return`${encodeURIComponent($)}=`;throw new t(`Cannot stringify type ${typeof J}; 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,$,J,W){let{signal:X,...F}=$||{};if(X)X.addEventListener("abort",()=>W.abort());let Y=setTimeout(()=>W.abort(),J),G={signal:W.signal,...F};if(G.method)G.method=G.method.toUpperCase();return this.fetch.call(void 0,T,G).finally(()=>{clearTimeout(Y)})}shouldRetry(T){let $=T.headers.get("x-should-retry");if($==="true")return!0;if($==="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,$,J){let W,X=J?.["retry-after-ms"];if(X){let Y=parseFloat(X);if(!Number.isNaN(Y))W=Y}let F=J?.["retry-after"];if(F&&!W){let Y=parseFloat(F);if(!Number.isNaN(Y))W=Y*1000;else W=Date.parse(F)-Date.now()}if(!(W&&0<=W&&W<60000)){let Y=T.maxRetries??this.maxRetries;W=this.calculateDefaultRetryTimeoutMillis($,Y)}return await w1(W),this.makeRequest(T,$-1)}calculateDefaultRetryTimeoutMillis(T,$){let X=$-T,F=Math.min(0.5*Math.pow(2,X),8),Y=1-Math.random()*0.25;return F*Y*1000}getUserAgent(){return`${this.constructor.name}/JS ${_0}`}}class U4{constructor(T,$,J,W){w4.set(this,void 0),wD(this,w4,T,"f"),this.options=W,this.response=$,this.body=J}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageInfo()!=null}async getNextPage(){let T=this.nextPageInfo();if(!T)throw new t("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let $={...this.options};if("params"in T&&typeof $.query==="object")$.query={...$.query,...T.params};else if("url"in T){let J=[...Object.entries($.query||{}),...T.url.searchParams.entries()];for(let[W,X]of J)T.url.searchParams.set(W,X);$.query=void 0,$.path=T.url.toString()}return await QD(this,w4,"f").requestAPIList(this.constructor,$)}async*iterPages(){let T=this;yield T;while(T.hasNextPage())T=await T.getNextPage(),yield T}async*[(w4=new WeakMap,Symbol.asyncIterator)](){for await(let T of this.iterPages())for(let $ of T.getPaginatedItems())yield $}}class K3 extends O4{constructor(T,$,J){super($,async(W)=>new J(T,W.response,await _3(W),W.options))}async*[Symbol.asyncIterator](){let T=await this;for await(let $ of T)yield $}}var iF=(T)=>{return new Proxy(Object.fromEntries(T.entries()),{get($,J){let W=J.toString();return $[W.toLowerCase()]||$[W]}})},OD={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__metadata:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},AT=(T)=>{return typeof T==="object"&&T!==null&&!S3(T)&&Object.keys(T).every(($)=>V3(OD,$))},UD=()=>{if(typeof Deno!=="undefined"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_0,"X-Stainless-OS":w3(Deno.build.os),"X-Stainless-Arch":A3(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":_0,"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":_0,"X-Stainless-OS":w3(process.platform),"X-Stainless-Arch":A3(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let T=_D();if(T)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_0,"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":_0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function _D(){if(typeof navigator==="undefined"||!navigator)return null;let 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:$,pattern:J}of T){let W=J.exec(navigator.userAgent);if(W){let X=W[1]||0,F=W[2]||0,Y=W[3]||0;return{browser:$,version:`${X}.${F}.${Y}`}}}return null}var A3=(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"},w3=(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"},Q3,DD=()=>{return Q3??(Q3=UD())},KD=(T)=>{try{return JSON.parse(T)}catch($){return}},SD=/^[a-z][a-z0-9+.-]*:/i,VD=(T)=>{return SD.test(T)},w1=(T)=>new Promise(($)=>setTimeout($,T)),eF=(T,$)=>{if(typeof $!=="number"||!Number.isInteger($))throw new t(`${T} must be an integer`);if($<0)throw new t(`${T} must be a positive integer`);return $},z4=(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 dX=(T)=>{if(typeof process!=="undefined")return process.env?.[T]?.trim()??void 0;if(typeof Deno!=="undefined")return Deno.env?.get?.(T)?.trim();return};function S3(T){if(!T)return!0;for(let $ in T)return!1;return!0}function V3(T,$){return Object.prototype.hasOwnProperty.call(T,$)}function O3(T,$){for(let J in $){if(!V3($,J))continue;let W=J.toLowerCase();if(!W)continue;let X=$[J];if(X===null)delete T[W];else if(X!==void 0)T[W]=X}}var U3=new Set(["authorization","api-key"]);function A1(T,...$){if(typeof process!=="undefined"&&process?.env?.DEBUG==="true"){let J=$.map((W)=>{if(!W)return W;if(W.headers){let F={...W,headers:{...W.headers}};for(let Y in W.headers)if(U3.has(Y.toLowerCase()))F.headers[Y]="REDACTED";return F}let X=null;for(let F in W)if(U3.has(F.toLowerCase()))X??(X={...W}),X[F]="REDACTED";return X??W});console.log(`OpenAI:DEBUG:${T}`,...J)}}var ED=()=>{return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(T)=>{let $=Math.random()*16|0;return(T==="x"?$:$&3|8).toString(16)})},E3=()=>{return typeof window!=="undefined"&&typeof window.document!=="undefined"&&typeof navigator!=="undefined"},RD=(T)=>{return typeof T?.get==="function"};var Q4=(T,$)=>{let J=$.toLowerCase();if(RD(T)){let W=$[0]?.toUpperCase()+$.substring(1).replace(/([^\w])(\w)/g,(X,F,Y)=>F+Y.toUpperCase());for(let X of[$,J,$.toUpperCase(),W]){let F=T.get(X);if(F)return F}}for(let[W,X]of Object.entries(T))if(W.toLowerCase()===J){if(Array.isArray(X)){if(X.length<=1)return X[0];return console.warn(`Received ${X.length} entries for the ${$} header, using the first entry.`),X[0]}return X}return};var R3=(T)=>{if(typeof Buffer!=="undefined"){let $=Buffer.from(T,"base64");return Array.from(new Float32Array($.buffer,$.byteOffset,$.length/Float32Array.BYTES_PER_ELEMENT))}else{let $=atob(T),J=$.length,W=new Uint8Array(J);for(let X=0;X<J;X++)W[X]=$.charCodeAt(X);return Array.from(new Float32Array(W.buffer))}};function lX(T){return T!=null&&typeof T==="object"&&!Array.isArray(T)}class Q1 extends U4{constructor(T,$,J,W){super(T,$,J,W);this.data=J.data||[],this.object=J.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class BT extends U4{constructor(T,$,J,W){super(T,$,J,W);this.data=J.data||[],this.has_more=J.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageParams(){let T=this.nextPageInfo();if(!T)return null;if("params"in T)return T.params;let $=Object.fromEntries(T.url.searchParams);if(!Object.keys($).length)return null;return $}nextPageInfo(){let T=this.getPaginatedItems();if(!T.length)return null;let $=T[T.length-1]?.id;if(!$)return null;return{params:{after:$}}}}class b{constructor(T){this._client=T}}class nX extends b{list(T,$={},J){if(AT($))return this.list(T,{},$);return this._client.getAPIList(`/chat/completions/${T}/messages`,$Y,{query:$,...J})}}class E0 extends b{constructor(){super(...arguments);this.messages=new nX(this._client)}create(T,$){return this._client.post("/chat/completions",{body:T,...$,stream:T.stream??!1})}retrieve(T,$){return this._client.get(`/chat/completions/${T}`,$)}update(T,$,J){return this._client.post(`/chat/completions/${T}`,{body:$,...J})}list(T={},$){if(AT(T))return this.list({},T);return this._client.getAPIList("/chat/completions",R0,{query:T,...$})}del(T,$){return this._client.delete(`/chat/completions/${T}`,$)}}class R0 extends BT{}class $Y extends BT{}E0.ChatCompletionsPage=R0;E0.Messages=nX;class p1 extends b{constructor(){super(...arguments);this.completions=new E0(this._client)}}p1.Completions=E0;p1.ChatCompletionsPage=R0;class iX extends b{create(T,$){return this._client.post("/audio/speech",{body:T,...$,headers:{Accept:"application/octet-stream",...$?.headers},__binaryResponse:!0})}}class tX extends b{create(T,$){return this._client.post("/audio/transcriptions",SJ({body:T,...$,stream:T.stream??!1,__metadata:{model:T.model}}))}}class rX extends b{create(T,$){return this._client.post("/audio/translations",SJ({body:T,...$,__metadata:{model:T.model}}))}}class O1 extends b{constructor(){super(...arguments);this.transcriptions=new tX(this._client),this.translations=new rX(this._client),this.speech=new iX(this._client)}}O1.Transcriptions=tX;O1.Translations=rX;O1.Speech=iX;class L0 extends b{create(T,$){return this._client.post("/batches",{body:T,...$})}retrieve(T,$){return this._client.get(`/batches/${T}`,$)}list(T={},$){if(AT(T))return this.list({},T);return this._client.getAPIList("/batches",QW,{query:T,...$})}cancel(T,$){return this._client.post(`/batches/${T}/cancel`,$)}}class QW extends BT{}L0.BatchesPage=QW;var IJ=function(T,$,J,W,X){if(W==="m")throw new TypeError("Private method is not writable");if(W==="a"&&!X)throw new TypeError("Private accessor was defined without a setter");if(typeof $==="function"?T!==$||!X:!$.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return W==="a"?X.call(T,J):X?X.value=J:$.set(T,J),J},aT=function(T,$,J,W){if(J==="a"&&!W)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?T!==$||!W:!$.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return J==="m"?W:J==="a"?W.call(T):W?W.value:$.get(T)},JY,_4,D4,aX,sX,K4,eX,U1,T2,S4,V4,OW,L3;class B0{constructor(){JY.add(this),this.controller=new AbortController,_4.set(this,void 0),D4.set(this,()=>{}),aX.set(this,()=>{}),sX.set(this,void 0),K4.set(this,()=>{}),eX.set(this,()=>{}),U1.set(this,{}),T2.set(this,!1),S4.set(this,!1),V4.set(this,!1),OW.set(this,!1),IJ(this,_4,new Promise((T,$)=>{IJ(this,D4,T,"f"),IJ(this,aX,$,"f")}),"f"),IJ(this,sX,new Promise((T,$)=>{IJ(this,K4,T,"f"),IJ(this,eX,$,"f")}),"f"),aT(this,_4,"f").catch(()=>{}),aT(this,sX,"f").catch(()=>{})}_run(T){setTimeout(()=>{T().then(()=>{this._emitFinal(),this._emit("end")},aT(this,JY,"m",L3).bind(this))},0)}_connected(){if(this.ended)return;aT(this,D4,"f").call(this),this._emit("connect")}get ended(){return aT(this,T2,"f")}get errored(){return aT(this,S4,"f")}get aborted(){return aT(this,V4,"f")}abort(){this.controller.abort()}on(T,$){return(aT(this,U1,"f")[T]||(aT(this,U1,"f")[T]=[])).push({listener:$}),this}off(T,$){let J=aT(this,U1,"f")[T];if(!J)return this;let W=J.findIndex((X)=>X.listener===$);if(W>=0)J.splice(W,1);return this}once(T,$){return(aT(this,U1,"f")[T]||(aT(this,U1,"f")[T]=[])).push({listener:$,once:!0}),this}emitted(T){return new Promise(($,J)=>{if(IJ(this,OW,!0,"f"),T!=="error")this.once("error",J);this.once(T,$)})}async done(){IJ(this,OW,!0,"f"),await aT(this,sX,"f")}_emit(T,...$){if(aT(this,T2,"f"))return;if(T==="end")IJ(this,T2,!0,"f"),aT(this,K4,"f").call(this);let J=aT(this,U1,"f")[T];if(J)aT(this,U1,"f")[T]=J.filter((W)=>!W.once),J.forEach(({listener:W})=>W(...$));if(T==="abort"){let W=$[0];if(!aT(this,OW,"f")&&!J?.length)Promise.reject(W);aT(this,aX,"f").call(this,W),aT(this,eX,"f").call(this,W),this._emit("end");return}if(T==="error"){let W=$[0];if(!aT(this,OW,"f")&&!J?.length)Promise.reject(W);aT(this,aX,"f").call(this,W),aT(this,eX,"f").call(this,W),this._emit("end")}}_emitFinal(){}}_4=new WeakMap,D4=new WeakMap,aX=new WeakMap,sX=new WeakMap,K4=new WeakMap,eX=new WeakMap,U1=new WeakMap,T2=new WeakMap,S4=new WeakMap,V4=new WeakMap,OW=new WeakMap,JY=new WeakSet,L3=function T($){if(IJ(this,S4,!0,"f"),$ instanceof Error&&$.name==="AbortError")$=new U$;if($ instanceof U$)return IJ(this,V4,!0,"f"),this._emit("abort",$);if($ instanceof t)return this._emit("error",$);if($ instanceof Error){let J=new t($.message);return J.cause=$,this._emit("error",J)}return this._emit("error",new t(String($)))};var r=function(T,$,J,W){if(J==="a"&&!W)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?T!==$||!W:!$.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return J==="m"?W:J==="a"?W.call(T):W?W.value:$.get(T)},GJ=function(T,$,J,W,X){if(W==="m")throw new TypeError("Private method is not writable");if(W==="a"&&!X)throw new TypeError("Private accessor was defined without a setter");if(typeof $==="function"?T!==$||!X:!$.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return W==="a"?X.call(T,J):X?X.value=J:$.set(T,J),J},C$,WY,iJ,E4,jJ,N0,UW,f0,B4,HJ,R4,L4,W2,$2,J2,B3,f3,N3,C3,Z3,q3,k3;class MJ extends B0{constructor(){super(...arguments);C$.add(this),WY.set(this,[]),iJ.set(this,{}),E4.set(this,{}),jJ.set(this,void 0),N0.set(this,void 0),UW.set(this,void 0),f0.set(this,void 0),B4.set(this,void 0),HJ.set(this,void 0),R4.set(this,void 0),L4.set(this,void 0),W2.set(this,void 0)}[(WY=new WeakMap,iJ=new WeakMap,E4=new WeakMap,jJ=new WeakMap,N0=new WeakMap,UW=new WeakMap,f0=new WeakMap,B4=new WeakMap,HJ=new WeakMap,R4=new WeakMap,L4=new WeakMap,W2=new WeakMap,C$=new WeakSet,Symbol.asyncIterator)](){let T=[],$=[],J=!1;return this.on("event",(W)=>{let X=$.shift();if(X)X.resolve(W);else T.push(W)}),this.on("end",()=>{J=!0;for(let W of $)W.resolve(void 0);$.length=0}),this.on("abort",(W)=>{J=!0;for(let X of $)X.reject(W);$.length=0}),this.on("error",(W)=>{J=!0;for(let X of $)X.reject(W);$.length=0}),{next:async()=>{if(!T.length){if(J)return{value:void 0,done:!0};return new Promise((X,F)=>$.push({resolve:X,reject:F})).then((X)=>X?{value:X,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){let $=new MJ;return $._run(()=>$._fromReadableStream(T)),$}async _fromReadableStream(T,$){let J=$?.signal;if(J){if(J.aborted)this.controller.abort();J.addEventListener("abort",()=>this.controller.abort())}this._connected();let W=YJ.fromReadableStream(T,this.controller);for await(let X of W)r(this,C$,"m",$2).call(this,X);if(W.controller.signal?.aborted)throw new U$;return this._addRun(r(this,C$,"m",J2).call(this))}toReadableStream(){return new YJ(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(T,$,J,W,X){let F=new MJ;return F._run(()=>F._runToolAssistantStream(T,$,J,W,{...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"stream"}})),F}async _createToolAssistantStream(T,$,J,W,X){let F=X?.signal;if(F){if(F.aborted)this.controller.abort();F.addEventListener("abort",()=>this.controller.abort())}let Y={...W,stream:!0},G=await T.submitToolOutputs($,J,Y,{...X,signal:this.controller.signal});this._connected();for await(let H of G)r(this,C$,"m",$2).call(this,H);if(G.controller.signal?.aborted)throw new U$;return this._addRun(r(this,C$,"m",J2).call(this))}static createThreadAssistantStream(T,$,J){let W=new MJ;return W._run(()=>W._threadAssistantStream(T,$,{...J,headers:{...J?.headers,"X-Stainless-Helper-Method":"stream"}})),W}static createAssistantStream(T,$,J,W){let X=new MJ;return X._run(()=>X._runAssistantStream(T,$,J,{...W,headers:{...W?.headers,"X-Stainless-Helper-Method":"stream"}})),X}currentEvent(){return r(this,R4,"f")}currentRun(){return r(this,L4,"f")}currentMessageSnapshot(){return r(this,jJ,"f")}currentRunStepSnapshot(){return r(this,W2,"f")}async finalRunSteps(){return await this.done(),Object.values(r(this,iJ,"f"))}async finalMessages(){return await this.done(),Object.values(r(this,E4,"f"))}async finalRun(){if(await this.done(),!r(this,N0,"f"))throw Error("Final run was not received.");return r(this,N0,"f")}async _createThreadAssistantStream(T,$,J){let W=J?.signal;if(W){if(W.aborted)this.controller.abort();W.addEventListener("abort",()=>this.controller.abort())}let X={...$,stream:!0},F=await T.createAndRun(X,{...J,signal:this.controller.signal});this._connected();for await(let Y of F)r(this,C$,"m",$2).call(this,Y);if(F.controller.signal?.aborted)throw new U$;return this._addRun(r(this,C$,"m",J2).call(this))}async _createAssistantStream(T,$,J,W){let X=W?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}let F={...J,stream:!0},Y=await T.create($,F,{...W,signal:this.controller.signal});this._connected();for await(let G of Y)r(this,C$,"m",$2).call(this,G);if(Y.controller.signal?.aborted)throw new U$;return this._addRun(r(this,C$,"m",J2).call(this))}static accumulateDelta(T,$){for(let[J,W]of Object.entries($)){if(!T.hasOwnProperty(J)){T[J]=W;continue}let X=T[J];if(X===null||X===void 0){T[J]=W;continue}if(J==="index"||J==="type"){T[J]=W;continue}if(typeof X==="string"&&typeof W==="string")X+=W;else if(typeof X==="number"&&typeof W==="number")X+=W;else if(lX(X)&&lX(W))X=this.accumulateDelta(X,W);else if(Array.isArray(X)&&Array.isArray(W)){if(X.every((F)=>typeof F==="string"||typeof F==="number")){X.push(...W);continue}for(let F of W){if(!lX(F))throw new Error(`Expected array delta entry to be an object but got: ${F}`);let Y=F.index;if(Y==null)throw console.error(F),new Error("Expected array delta entry to have an `index` property");if(typeof Y!=="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${Y}`);let G=X[Y];if(G==null)X.push(F);else X[Y]=this.accumulateDelta(G,F)}continue}else throw Error(`Unhandled record type: ${J}, deltaValue: ${W}, accValue: ${X}`);T[J]=X}return T}_addRun(T){return T}async _threadAssistantStream(T,$,J){return await this._createThreadAssistantStream($,T,J)}async _runAssistantStream(T,$,J,W){return await this._createAssistantStream($,T,J,W)}async _runToolAssistantStream(T,$,J,W,X){return await this._createToolAssistantStream(J,T,$,W,X)}}$2=function T($){if(this.ended)return;switch(GJ(this,R4,$,"f"),r(this,C$,"m",N3).call(this,$),$.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.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":r(this,C$,"m",k3).call(this,$);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":r(this,C$,"m",f3).call(this,$);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":r(this,C$,"m",B3).call(this,$);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:ZD($)}},J2=function T(){if(this.ended)throw new t("stream has ended, this shouldn't happen");if(!r(this,N0,"f"))throw Error("Final run has not been received");return r(this,N0,"f")},B3=function T($){let[J,W]=r(this,C$,"m",Z3).call(this,$,r(this,jJ,"f"));GJ(this,jJ,J,"f"),r(this,E4,"f")[J.id]=J;for(let X of W){let F=J.content[X.index];if(F?.type=="text")this._emit("textCreated",F.text)}switch($.event){case"thread.message.created":this._emit("messageCreated",$.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",$.data.delta,J),$.data.delta.content)for(let X of $.data.delta.content){if(X.type=="text"&&X.text){let F=X.text,Y=J.content[X.index];if(Y&&Y.type=="text")this._emit("textDelta",F,Y.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(X.index!=r(this,UW,"f")){if(r(this,f0,"f"))switch(r(this,f0,"f").type){case"text":this._emit("textDone",r(this,f0,"f").text,r(this,jJ,"f"));break;case"image_file":this._emit("imageFileDone",r(this,f0,"f").image_file,r(this,jJ,"f"));break}GJ(this,UW,X.index,"f")}GJ(this,f0,J.content[X.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(r(this,UW,"f")!==void 0){let X=$.data.content[r(this,UW,"f")];if(X)switch(X.type){case"image_file":this._emit("imageFileDone",X.image_file,r(this,jJ,"f"));break;case"text":this._emit("textDone",X.text,r(this,jJ,"f"));break}}if(r(this,jJ,"f"))this._emit("messageDone",$.data);GJ(this,jJ,void 0,"f")}},f3=function T($){let J=r(this,C$,"m",C3).call(this,$);switch(GJ(this,W2,J,"f"),$.event){case"thread.run.step.created":this._emit("runStepCreated",$.data);break;case"thread.run.step.delta":let W=$.data.delta;if(W.step_details&&W.step_details.type=="tool_calls"&&W.step_details.tool_calls&&J.step_details.type=="tool_calls")for(let F of W.step_details.tool_calls)if(F.index==r(this,B4,"f"))this._emit("toolCallDelta",F,J.step_details.tool_calls[F.index]);else{if(r(this,HJ,"f"))this._emit("toolCallDone",r(this,HJ,"f"));if(GJ(this,B4,F.index,"f"),GJ(this,HJ,J.step_details.tool_calls[F.index],"f"),r(this,HJ,"f"))this._emit("toolCallCreated",r(this,HJ,"f"))}this._emit("runStepDelta",$.data.delta,J);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(GJ(this,W2,void 0,"f"),$.data.step_details.type=="tool_calls"){if(r(this,HJ,"f"))this._emit("toolCallDone",r(this,HJ,"f")),GJ(this,HJ,void 0,"f")}this._emit("runStepDone",$.data,J);break;case"thread.run.step.in_progress":break}},N3=function T($){r(this,WY,"f").push($),this._emit("event",$)},C3=function T($){switch($.event){case"thread.run.step.created":return r(this,iJ,"f")[$.data.id]=$.data,$.data;case"thread.run.step.delta":let J=r(this,iJ,"f")[$.data.id];if(!J)throw Error("Received a RunStepDelta before creation of a snapshot");let W=$.data;if(W.delta){let X=MJ.accumulateDelta(J,W.delta);r(this,iJ,"f")[$.data.id]=X}return r(this,iJ,"f")[$.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":r(this,iJ,"f")[$.data.id]=$.data;break}if(r(this,iJ,"f")[$.data.id])return r(this,iJ,"f")[$.data.id];throw new Error("No snapshot available")},Z3=function T($,J){let W=[];switch($.event){case"thread.message.created":return[$.data,W];case"thread.message.delta":if(!J)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let X=$.data;if(X.delta.content)for(let F of X.delta.content)if(F.index in J.content){let Y=J.content[F.index];J.content[F.index]=r(this,C$,"m",q3).call(this,F,Y)}else J.content[F.index]=F,W.push(F);return[J,W];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(J)return[J,W];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},q3=function T($,J){return MJ.accumulateDelta(J,$)},k3=function T($){switch(GJ(this,L4,$.data,"f"),$.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(GJ(this,N0,$.data,"f"),r(this,HJ,"f"))this._emit("toolCallDone",r(this,HJ,"f")),GJ(this,HJ,void 0,"f");break;case"thread.run.cancelling":break}};function ZD(T){}class _W extends b{create(T,$){return this._client.post("/assistants",{body:T,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}retrieve(T,$){return this._client.get(`/assistants/${T}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}update(T,$,J){return this._client.post(`/assistants/${T}`,{body:$,...J,headers:{"OpenAI-Beta":"assistants=v2",...J?.headers}})}list(T={},$){if(AT(T))return this.list({},T);return this._client.getAPIList("/assistants",X2,{query:T,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}del(T,$){return this._client.delete(`/assistants/${T}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}}class X2 extends BT{}_W.AssistantsPage=X2;function XY(T){return typeof T.parse==="function"}var u1=(T)=>{return T?.role==="assistant"},FY=(T)=>{return T?.role==="function"},YY=(T)=>{return T?.role==="tool"};function F2(T){return T?.$brand==="auto-parseable-response-format"}function C0(T){return T?.$brand==="auto-parseable-tool"}function y3(T,$){if(!$||!GY($))return{...T,choices:T.choices.map((J)=>({...J,message:{...J.message,parsed:null,...J.message.tool_calls?{tool_calls:J.message.tool_calls}:void 0}}))};return Y2(T,$)}function Y2(T,$){let J=T.choices.map((W)=>{if(W.finish_reason==="length")throw new uX;if(W.finish_reason==="content_filter")throw new cX;return{...W,message:{...W.message,...W.message.tool_calls?{tool_calls:W.message.tool_calls?.map((X)=>yD($,X))??void 0}:void 0,parsed:W.message.content&&!W.message.refusal?kD($,W.message.content):null}}});return{...T,choices:J}}function kD(T,$){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($);return JSON.parse($)}return null}function yD(T,$){let J=T.tools?.find((W)=>W.function?.name===$.function.name);return{...$,function:{...$.function,parsed_arguments:C0(J)?J.$parseRaw($.function.arguments):J?.function.strict?JSON.parse($.function.arguments):null}}}function I3(T,$){if(!T)return!1;let J=T.tools?.find((W)=>W.function?.name===$.function.name);return C0(J)||J?.function.strict||!1}function GY(T){if(F2(T.response_format))return!0;return T.tools?.some(($)=>C0($)||$.type==="function"&&$.function.strict===!0)??!1}function j3(T){for(let $ of T??[]){if($.type!=="function")throw new t(`Currently only \`function\` tool types support auto-parsing; Received \`${$.type}\``);if($.function.strict!==!0)throw new t(`The \`${$.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var t$=function(T,$,J,W){if(J==="a"&&!W)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?T!==$||!W:!$.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return J==="m"?W:J==="a"?W.call(T):W?W.value:$.get(T)},x$,HY,f4,MY,zY,AY,P3,wY,x3=10;class G2 extends B0{constructor(){super(...arguments);x$.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(T){this._chatCompletions.push(T),this._emit("chatCompletion",T);let $=T.choices[0]?.message;if($)this._addMessage($);return T}_addMessage(T,$=!0){if(!("content"in T))T.content=null;if(this.messages.push(T),$){if(this._emit("message",T),(FY(T)||YY(T))&&T.content)this._emit("functionCallResult",T.content);else if(u1(T)&&T.function_call)this._emit("functionCall",T.function_call);else if(u1(T)&&T.tool_calls){for(let J of T.tool_calls)if(J.type==="function")this._emit("functionCall",J.function)}}}async finalChatCompletion(){await this.done();let 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(),t$(this,x$,"m",HY).call(this)}async finalMessage(){return await this.done(),t$(this,x$,"m",f4).call(this)}async finalFunctionCall(){return await this.done(),t$(this,x$,"m",MY).call(this)}async finalFunctionCallResult(){return await this.done(),t$(this,x$,"m",zY).call(this)}async totalUsage(){return await this.done(),t$(this,x$,"m",AY).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let T=this._chatCompletions[this._chatCompletions.length-1];if(T)this._emit("finalChatCompletion",T);let $=t$(this,x$,"m",f4).call(this);if($)this._emit("finalMessage",$);let J=t$(this,x$,"m",HY).call(this);if(J)this._emit("finalContent",J);let W=t$(this,x$,"m",MY).call(this);if(W)this._emit("finalFunctionCall",W);let X=t$(this,x$,"m",zY).call(this);if(X!=null)this._emit("finalFunctionCallResult",X);if(this._chatCompletions.some((F)=>F.usage))this._emit("totalUsage",t$(this,x$,"m",AY).call(this))}async _createChatCompletion(T,$,J){let W=J?.signal;if(W){if(W.aborted)this.controller.abort();W.addEventListener("abort",()=>this.controller.abort())}t$(this,x$,"m",P3).call(this,$);let X=await T.chat.completions.create({...$,stream:!1},{...J,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Y2(X,$))}async _runChatCompletion(T,$,J){for(let W of $.messages)this._addMessage(W,!1);return await this._createChatCompletion(T,$,J)}async _runFunctions(T,$,J){let{function_call:X="auto",stream:F,...Y}=$,G=typeof X!=="string"&&X?.name,{maxChatCompletions:H=x3}=J||{},M={};for(let A of $.functions)M[A.name||A.function.name]=A;let z=$.functions.map((A)=>({name:A.name||A.function.name,parameters:A.parameters,description:A.description}));for(let A of $.messages)this._addMessage(A,!1);for(let A=0;A<H;++A){let _=(await this._createChatCompletion(T,{...Y,function_call:X,functions:z,messages:[...this.messages]},J)).choices[0]?.message;if(!_)throw new t("missing message in ChatCompletion response");if(!_.function_call)return;let{name:D,arguments:S}=_.function_call,Z=M[D];if(!Z){let V=`Invalid function_call: ${JSON.stringify(D)}. Available options are: ${z.map((f)=>JSON.stringify(f.name)).join(", ")}. Please try again`;this._addMessage({role:"function",name:D,content:V});continue}else if(G&&G!==D){let V=`Invalid function_call: ${JSON.stringify(D)}. ${JSON.stringify(G)} requested. Please try again`;this._addMessage({role:"function",name:D,content:V});continue}let q;try{q=XY(Z)?await Z.parse(S):S}catch(V){this._addMessage({role:"function",name:D,content:V instanceof Error?V.message:String(V)});continue}let N=await Z.function(q,this),y=t$(this,x$,"m",wY).call(this,N);if(this._addMessage({role:"function",name:D,content:y}),G)return}}async _runTools(T,$,J){let{tool_choice:X="auto",stream:F,...Y}=$,G=typeof X!=="string"&&X?.function?.name,{maxChatCompletions:H=x3}=J||{},M=$.tools.map((w)=>{if(C0(w)){if(!w.$callback)throw new t("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:w.$callback,name:w.function.name,description:w.function.description||"",parameters:w.function.parameters,parse:w.$parseRaw,strict:!0}}}return w}),z={};for(let w of M)if(w.type==="function")z[w.function.name||w.function.function.name]=w.function;let A="tools"in $?M.map((w)=>w.type==="function"?{type:"function",function:{name:w.function.name||w.function.function.name,parameters:w.function.parameters,description:w.function.description,strict:w.function.strict}}:w):void 0;for(let w of $.messages)this._addMessage(w,!1);for(let w=0;w<H;++w){let D=(await this._createChatCompletion(T,{...Y,tool_choice:X,tools:A,messages:[...this.messages]},J)).choices[0]?.message;if(!D)throw new t("missing message in ChatCompletion response");if(!D.tool_calls?.length)return;for(let S of D.tool_calls){if(S.type!=="function")continue;let Z=S.id,{name:q,arguments:N}=S.function,y=z[q];if(!y){let B=`Invalid tool_call: ${JSON.stringify(q)}. Available options are: ${Object.keys(z).map((m)=>JSON.stringify(m)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:Z,content:B});continue}else if(G&&G!==q){let B=`Invalid tool_call: ${JSON.stringify(q)}. ${JSON.stringify(G)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:Z,content:B});continue}let V;try{V=XY(y)?await y.parse(N):N}catch(B){let m=B instanceof Error?B.message:String(B);this._addMessage({role:"tool",tool_call_id:Z,content:m});continue}let f=await y.function(V,this),C=t$(this,x$,"m",wY).call(this,f);if(this._addMessage({role:"tool",tool_call_id:Z,content:C}),G)return}}return}}x$=new WeakSet,HY=function T(){return t$(this,x$,"m",f4).call(this).content??null},f4=function T(){let $=this.messages.length;while($-- >0){let J=this.messages[$];if(u1(J)){let{function_call:W,...X}=J,F={...X,content:J.content??null,refusal:J.refusal??null};if(W)F.function_call=W;return F}}throw new t("stream ended without producing a ChatCompletionMessage with role=assistant")},MY=function T(){for(let $=this.messages.length-1;$>=0;$--){let J=this.messages[$];if(u1(J)&&J?.function_call)return J.function_call;if(u1(J)&&J?.tool_calls?.length)return J.tool_calls.at(-1)?.function}return},zY=function T(){for(let $=this.messages.length-1;$>=0;$--){let J=this.messages[$];if(FY(J)&&J.content!=null)return J.content;if(YY(J)&&J.content!=null&&typeof J.content==="string"&&this.messages.some((W)=>W.role==="assistant"&&W.tool_calls?.some((X)=>X.type==="function"&&X.id===J.tool_call_id)))return J.content}return},AY=function T(){let $={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:J}of this._chatCompletions)if(J)$.completion_tokens+=J.completion_tokens,$.prompt_tokens+=J.prompt_tokens,$.total_tokens+=J.total_tokens;return $},P3=function T($){if($.n!=null&&$.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.")},wY=function T($){return typeof $==="string"?$:$===void 0?"undefined":JSON.stringify($)};class DW extends G2{static runFunctions(T,$,J){let W=new DW,X={...J,headers:{...J?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return W._run(()=>W._runFunctions(T,$,X)),W}static runTools(T,$,J){let W=new DW,X={...J,headers:{...J?.headers,"X-Stainless-Helper-Method":"runTools"}};return W._run(()=>W._runTools(T,$,X)),W}_addMessage(T,$=!0){if(super._addMessage(T,$),u1(T)&&T.content)this._emit("content",T.content)}}var L$={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 b3 extends Error{}class v3 extends Error{}function ID(T,$=L$.ALL){if(typeof T!=="string")throw new TypeError(`expecting str, got ${typeof T}`);if(!T.trim())throw new Error(`${T} is empty`);return jD(T.trim(),$)}var jD=(T,$)=>{let J=T.length,W=0,X=(w)=>{throw new b3(`${w} at position ${W}`)},F=(w)=>{throw new v3(`${w} at position ${W}`)},Y=()=>{if(A(),W>=J)X("Unexpected end of input");if(T[W]==='"')return G();if(T[W]==="{")return H();if(T[W]==="[")return M();if(T.substring(W,W+4)==="null"||L$.NULL&$&&J-W<4&&"null".startsWith(T.substring(W)))return W+=4,null;if(T.substring(W,W+4)==="true"||L$.BOOL&$&&J-W<4&&"true".startsWith(T.substring(W)))return W+=4,!0;if(T.substring(W,W+5)==="false"||L$.BOOL&$&&J-W<5&&"false".startsWith(T.substring(W)))return W+=5,!1;if(T.substring(W,W+8)==="Infinity"||L$.INFINITY&$&&J-W<8&&"Infinity".startsWith(T.substring(W)))return W+=8,1/0;if(T.substring(W,W+9)==="-Infinity"||L$.MINUS_INFINITY&$&&1<J-W&&J-W<9&&"-Infinity".startsWith(T.substring(W)))return W+=9,-1/0;if(T.substring(W,W+3)==="NaN"||L$.NAN&$&&J-W<3&&"NaN".startsWith(T.substring(W)))return W+=3,NaN;return z()},G=()=>{let w=W,_=!1;W++;while(W<J&&(T[W]!=='"'||_&&T[W-1]==="\\"))_=T[W]==="\\"?!_:!1,W++;if(T.charAt(W)=='"')try{return JSON.parse(T.substring(w,++W-Number(_)))}catch(D){F(String(D))}else if(L$.STR&$)try{return JSON.parse(T.substring(w,W-Number(_))+'"')}catch(D){return JSON.parse(T.substring(w,T.lastIndexOf("\\"))+'"')}X("Unterminated string literal")},H=()=>{W++,A();let w={};try{while(T[W]!=="}"){if(A(),W>=J&&L$.OBJ&$)return w;let _=G();A(),W++;try{let D=Y();Object.defineProperty(w,_,{value:D,writable:!0,enumerable:!0,configurable:!0})}catch(D){if(L$.OBJ&$)return w;else throw D}if(A(),T[W]===",")W++}}catch(_){if(L$.OBJ&$)return w;else X("Expected '}' at end of object")}return W++,w},M=()=>{W++;let w=[];try{while(T[W]!=="]")if(w.push(Y()),A(),T[W]===",")W++}catch(_){if(L$.ARR&$)return w;X("Expected ']' at end of array")}return W++,w},z=()=>{if(W===0){if(T==="-"&&L$.NUM&$)X("Not sure what '-' is");try{return JSON.parse(T)}catch(_){if(L$.NUM&$)try{if(T[T.length-1]===".")return JSON.parse(T.substring(0,T.lastIndexOf(".")));return JSON.parse(T.substring(0,T.lastIndexOf("e")))}catch(D){}F(String(_))}}let w=W;if(T[W]==="-")W++;while(T[W]&&!",]}".includes(T[W]))W++;if(W==J&&!(L$.NUM&$))X("Unterminated number literal");try{return JSON.parse(T.substring(w,W))}catch(_){if(T.substring(w,W)==="-"&&L$.NUM&$)X("Not sure what '-' is");try{return JSON.parse(T.substring(w,T.lastIndexOf("e")))}catch(D){F(String(D))}}},A=()=>{while(W<J&&`
30
- \r `.includes(T[W]))W++};return Y()},QY=(T)=>ID(T,L$.ALL^L$.NUM);var KW=function(T,$,J,W,X){if(W==="m")throw new TypeError("Private method is not writable");if(W==="a"&&!X)throw new TypeError("Private accessor was defined without a setter");if(typeof $==="function"?T!==$||!X:!$.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return W==="a"?X.call(T,J):X?X.value=J:$.set(T,J),J},jT=function(T,$,J,W){if(J==="a"&&!W)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?T!==$||!W:!$.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return J==="m"?W:J==="a"?W.call(T):W?W.value:$.get(T)},_$,_1,SW,c1,OY,N4,UY,_Y,DY,C4,KY,h3;class Z0 extends G2{constructor(T){super();_$.add(this),_1.set(this,void 0),SW.set(this,void 0),c1.set(this,void 0),KW(this,_1,T,"f"),KW(this,SW,[],"f")}get currentChatCompletionSnapshot(){return jT(this,c1,"f")}static fromReadableStream(T){let $=new Z0(null);return $._run(()=>$._fromReadableStream(T)),$}static createChatCompletion(T,$,J){let W=new Z0($);return W._run(()=>W._runChatCompletion(T,{...$,stream:!0},{...J,headers:{...J?.headers,"X-Stainless-Helper-Method":"stream"}})),W}async _createChatCompletion(T,$,J){super._createChatCompletion;let W=J?.signal;if(W){if(W.aborted)this.controller.abort();W.addEventListener("abort",()=>this.controller.abort())}jT(this,_$,"m",OY).call(this);let X=await T.chat.completions.create({...$,stream:!0},{...J,signal:this.controller.signal});this._connected();for await(let F of X)jT(this,_$,"m",UY).call(this,F);if(X.controller.signal?.aborted)throw new U$;return this._addChatCompletion(jT(this,_$,"m",C4).call(this))}async _fromReadableStream(T,$){let J=$?.signal;if(J){if(J.aborted)this.controller.abort();J.addEventListener("abort",()=>this.controller.abort())}jT(this,_$,"m",OY).call(this),this._connected();let W=YJ.fromReadableStream(T,this.controller),X;for await(let F of W){if(X&&X!==F.id)this._addChatCompletion(jT(this,_$,"m",C4).call(this));jT(this,_$,"m",UY).call(this,F),X=F.id}if(W.controller.signal?.aborted)throw new U$;return this._addChatCompletion(jT(this,_$,"m",C4).call(this))}[(_1=new WeakMap,SW=new WeakMap,c1=new WeakMap,_$=new WeakSet,OY=function T(){if(this.ended)return;KW(this,c1,void 0,"f")},N4=function T($){let J=jT(this,SW,"f")[$.index];if(J)return J;return J={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},jT(this,SW,"f")[$.index]=J,J},UY=function T($){if(this.ended)return;let J=jT(this,_$,"m",h3).call(this,$);this._emit("chunk",$,J);for(let W of $.choices){let X=J.choices[W.index];if(W.delta.content!=null&&X.message?.role==="assistant"&&X.message?.content)this._emit("content",W.delta.content,X.message.content),this._emit("content.delta",{delta:W.delta.content,snapshot:X.message.content,parsed:X.message.parsed});if(W.delta.refusal!=null&&X.message?.role==="assistant"&&X.message?.refusal)this._emit("refusal.delta",{delta:W.delta.refusal,snapshot:X.message.refusal});if(W.logprobs?.content!=null&&X.message?.role==="assistant")this._emit("logprobs.content.delta",{content:W.logprobs?.content,snapshot:X.logprobs?.content??[]});if(W.logprobs?.refusal!=null&&X.message?.role==="assistant")this._emit("logprobs.refusal.delta",{refusal:W.logprobs?.refusal,snapshot:X.logprobs?.refusal??[]});let F=jT(this,_$,"m",N4).call(this,X);if(X.finish_reason){if(jT(this,_$,"m",DY).call(this,X),F.current_tool_call_index!=null)jT(this,_$,"m",_Y).call(this,X,F.current_tool_call_index)}for(let Y of W.delta.tool_calls??[]){if(F.current_tool_call_index!==Y.index){if(jT(this,_$,"m",DY).call(this,X),F.current_tool_call_index!=null)jT(this,_$,"m",_Y).call(this,X,F.current_tool_call_index)}F.current_tool_call_index=Y.index}for(let Y of W.delta.tool_calls??[]){let G=X.message.tool_calls?.[Y.index];if(!G?.type)continue;if(G?.type==="function")this._emit("tool_calls.function.arguments.delta",{name:G.function?.name,index:Y.index,arguments:G.function.arguments,parsed_arguments:G.function.parsed_arguments,arguments_delta:Y.function?.arguments??""});else g3(G?.type)}}},_Y=function T($,J){if(jT(this,_$,"m",N4).call(this,$).done_tool_calls.has(J))return;let X=$.message.tool_calls?.[J];if(!X)throw new Error("no tool call snapshot");if(!X.type)throw new Error("tool call snapshot missing `type`");if(X.type==="function"){let F=jT(this,_1,"f")?.tools?.find((Y)=>Y.type==="function"&&Y.function.name===X.function.name);this._emit("tool_calls.function.arguments.done",{name:X.function.name,index:J,arguments:X.function.arguments,parsed_arguments:C0(F)?F.$parseRaw(X.function.arguments):F?.function.strict?JSON.parse(X.function.arguments):null})}else g3(X.type)},DY=function T($){let J=jT(this,_$,"m",N4).call(this,$);if($.message.content&&!J.content_done){J.content_done=!0;let W=jT(this,_$,"m",KY).call(this);this._emit("content.done",{content:$.message.content,parsed:W?W.$parseRaw($.message.content):null})}if($.message.refusal&&!J.refusal_done)J.refusal_done=!0,this._emit("refusal.done",{refusal:$.message.refusal});if($.logprobs?.content&&!J.logprobs_content_done)J.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:$.logprobs.content});if($.logprobs?.refusal&&!J.logprobs_refusal_done)J.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:$.logprobs.refusal})},C4=function T(){if(this.ended)throw new t("stream has ended, this shouldn't happen");let $=jT(this,c1,"f");if(!$)throw new t("request ended without sending any chunks");return KW(this,c1,void 0,"f"),KW(this,SW,[],"f"),xD($,jT(this,_1,"f"))},KY=function T(){let $=jT(this,_1,"f")?.response_format;if(F2($))return $;return null},h3=function T($){var J,W,X,F;let Y=jT(this,c1,"f"),{choices:G,...H}=$;if(!Y)Y=KW(this,c1,{...H,choices:[]},"f");else Object.assign(Y,H);for(let{delta:M,finish_reason:z,index:A,logprobs:w=null,..._}of $.choices){let D=Y.choices[A];if(!D)D=Y.choices[A]={finish_reason:z,index:A,message:{},logprobs:w,..._};if(w)if(!D.logprobs)D.logprobs=Object.assign({},w);else{let{content:f,refusal:C,...B}=w;if(m3(B),Object.assign(D.logprobs,B),f)(J=D.logprobs).content??(J.content=[]),D.logprobs.content.push(...f);if(C)(W=D.logprobs).refusal??(W.refusal=[]),D.logprobs.refusal.push(...C)}if(z){if(D.finish_reason=z,jT(this,_1,"f")&&GY(jT(this,_1,"f"))){if(z==="length")throw new uX;if(z==="content_filter")throw new cX}}if(Object.assign(D,_),!M)continue;let{content:S,refusal:Z,function_call:q,role:N,tool_calls:y,...V}=M;if(m3(V),Object.assign(D.message,V),Z)D.message.refusal=(D.message.refusal||"")+Z;if(N)D.message.role=N;if(q)if(!D.message.function_call)D.message.function_call=q;else{if(q.name)D.message.function_call.name=q.name;if(q.arguments)(X=D.message.function_call).arguments??(X.arguments=""),D.message.function_call.arguments+=q.arguments}if(S){if(D.message.content=(D.message.content||"")+S,!D.message.refusal&&jT(this,_$,"m",KY).call(this))D.message.parsed=QY(D.message.content)}if(y){if(!D.message.tool_calls)D.message.tool_calls=[];for(let{index:f,id:C,type:B,function:m,...$T}of y){let E=(F=D.message.tool_calls)[f]??(F[f]={});if(Object.assign(E,$T),C)E.id=C;if(B)E.type=B;if(m)E.function??(E.function={name:m.name??"",arguments:""});if(m?.name)E.function.name=m.name;if(m?.arguments){if(E.function.arguments+=m.arguments,I3(jT(this,_1,"f"),E))E.function.parsed_arguments=QY(E.function.arguments)}}}}return Y},Symbol.asyncIterator)](){let T=[],$=[],J=!1;return this.on("chunk",(W)=>{let X=$.shift();if(X)X.resolve(W);else T.push(W)}),this.on("end",()=>{J=!0;for(let W of $)W.resolve(void 0);$.length=0}),this.on("abort",(W)=>{J=!0;for(let X of $)X.reject(W);$.length=0}),this.on("error",(W)=>{J=!0;for(let X of $)X.reject(W);$.length=0}),{next:async()=>{if(!T.length){if(J)return{value:void 0,done:!0};return new Promise((X,F)=>$.push({resolve:X,reject:F})).then((X)=>X?{value:X,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 YJ(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function xD(T,$){let{id:J,choices:W,created:X,model:F,system_fingerprint:Y,...G}=T,H={...G,id:J,choices:W.map(({message:M,finish_reason:z,index:A,logprobs:w,..._})=>{if(!z)throw new t(`missing finish_reason for choice ${A}`);let{content:D=null,function_call:S,tool_calls:Z,...q}=M,N=M.role;if(!N)throw new t(`missing role for choice ${A}`);if(S){let{arguments:y,name:V}=S;if(y==null)throw new t(`missing function_call.arguments for choice ${A}`);if(!V)throw new t(`missing function_call.name for choice ${A}`);return{..._,message:{content:D,function_call:{arguments:y,name:V},role:N,refusal:M.refusal??null},finish_reason:z,index:A,logprobs:w}}if(Z)return{..._,index:A,finish_reason:z,logprobs:w,message:{...q,role:N,content:D,refusal:M.refusal??null,tool_calls:Z.map((y,V)=>{let{function:f,type:C,id:B,...m}=y,{arguments:$T,name:E,...XT}=f||{};if(B==null)throw new t(`missing choices[${A}].tool_calls[${V}].id
31
- ${Z4(T)}`);if(C==null)throw new t(`missing choices[${A}].tool_calls[${V}].type
32
- ${Z4(T)}`);if(E==null)throw new t(`missing choices[${A}].tool_calls[${V}].function.name
33
- ${Z4(T)}`);if($T==null)throw new t(`missing choices[${A}].tool_calls[${V}].function.arguments
34
- ${Z4(T)}`);return{...m,id:B,type:C,function:{...XT,name:E,arguments:$T}}})}};return{..._,message:{...q,content:D,role:N,refusal:M.refusal??null},finish_reason:z,index:A,logprobs:w}}),created:X,model:F,object:"chat.completion",...Y?{system_fingerprint:Y}:{}};return y3(H,$)}function Z4(T){return JSON.stringify(T)}function m3(T){return}function g3(T){}class q0 extends Z0{static fromReadableStream(T){let $=new q0(null);return $._run(()=>$._fromReadableStream(T)),$}static runFunctions(T,$,J){let W=new q0(null),X={...J,headers:{...J?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return W._run(()=>W._runFunctions(T,$,X)),W}static runTools(T,$,J){let W=new q0($),X={...J,headers:{...J?.headers,"X-Stainless-Helper-Method":"runTools"}};return W._run(()=>W._runTools(T,$,X)),W}}class q4 extends b{parse(T,$){return j3(T.tools),this._client.chat.completions.create(T,{...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap((J)=>Y2(J,T))}runFunctions(T,$){if(T.stream)return q0.runFunctions(this._client,T,$);return DW.runFunctions(this._client,T,$)}runTools(T,$){if(T.stream)return q0.runTools(this._client,T,$);return DW.runTools(this._client,T,$)}stream(T,$){return Z0.createChatCompletion(this._client,T,$)}}class H2 extends b{constructor(){super(...arguments);this.completions=new q4(this._client)}}(function(T){T.Completions=q4})(H2||(H2={}));class M2 extends b{create(T,$){return this._client.post("/realtime/sessions",{body:T,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}}class z2 extends b{create(T,$){return this._client.post("/realtime/transcription_sessions",{body:T,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}}class k0 extends b{constructor(){super(...arguments);this.sessions=new M2(this._client),this.transcriptionSessions=new z2(this._client)}}k0.Sessions=M2;k0.TranscriptionSessions=z2;class VW extends b{create(T,$,J){return this._client.post(`/threads/${T}/messages`,{body:$,...J,headers:{"OpenAI-Beta":"assistants=v2",...J?.headers}})}retrieve(T,$,J){return this._client.get(`/threads/${T}/messages/${$}`,{...J,headers:{"OpenAI-Beta":"assistants=v2",...J?.headers}})}update(T,$,J,W){return this._client.post(`/threads/${T}/messages/${$}`,{body:J,...W,headers:{"OpenAI-Beta":"assistants=v2",...W?.headers}})}list(T,$={},J){if(AT($))return this.list(T,{},$);return this._client.getAPIList(`/threads/${T}/messages`,A2,{query:$,...J,headers:{"OpenAI-Beta":"assistants=v2",...J?.headers}})}del(T,$,J){return this._client.delete(`/threads/${T}/messages/${$}`,{...J,headers:{"OpenAI-Beta":"assistants=v2",...J?.headers}})}}class A2 extends BT{}VW.MessagesPage=A2;class EW extends b{retrieve(T,$,J,W={},X){if(AT(W))return this.retrieve(T,$,J,{},W);return this._client.get(`/threads/${T}/runs/${$}/steps/${J}`,{query:W,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}list(T,$,J={},W){if(AT(J))return this.list(T,$,{},J);return this._client.getAPIList(`/threads/${T}/runs/${$}/steps`,w2,{query:J,...W,headers:{"OpenAI-Beta":"assistants=v2",...W?.headers}})}}class w2 extends BT{}EW.RunStepsPage=w2;class o1 extends b{constructor(){super(...arguments);this.steps=new EW(this._client)}create(T,$,J){let{include:W,...X}=$;return this._client.post(`/threads/${T}/runs`,{query:{include:W},body:X,...J,headers:{"OpenAI-Beta":"assistants=v2",...J?.headers},stream:$.stream??!1})}retrieve(T,$,J){return this._client.get(`/threads/${T}/runs/${$}`,{...J,headers:{"OpenAI-Beta":"assistants=v2",...J?.headers}})}update(T,$,J,W){return this._client.post(`/threads/${T}/runs/${$}`,{body:J,...W,headers:{"OpenAI-Beta":"assistants=v2",...W?.headers}})}list(T,$={},J){if(AT($))return this.list(T,{},$);return this._client.getAPIList(`/threads/${T}/runs`,Q2,{query:$,...J,headers:{"OpenAI-Beta":"assistants=v2",...J?.headers}})}cancel(T,$,J){return this._client.post(`/threads/${T}/runs/${$}/cancel`,{...J,headers:{"OpenAI-Beta":"assistants=v2",...J?.headers}})}async createAndPoll(T,$,J){let W=await this.create(T,$,J);return await this.poll(T,W.id,J)}createAndStream(T,$,J){return MJ.createAssistantStream(T,this._client.beta.threads.runs,$,J)}async poll(T,$,J){let W={...J?.headers,"X-Stainless-Poll-Helper":"true"};if(J?.pollIntervalMs)W["X-Stainless-Custom-Poll-Interval"]=J.pollIntervalMs.toString();while(!0){let{data:X,response:F}=await this.retrieve(T,$,{...J,headers:{...J?.headers,...W}}).withResponse();switch(X.status){case"queued":case"in_progress":case"cancelling":let Y=5000;if(J?.pollIntervalMs)Y=J.pollIntervalMs;else{let G=F.headers.get("openai-poll-after-ms");if(G){let H=parseInt(G);if(!isNaN(H))Y=H}}await w1(Y);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return X}}}stream(T,$,J){return MJ.createAssistantStream(T,this._client.beta.threads.runs,$,J)}submitToolOutputs(T,$,J,W){return this._client.post(`/threads/${T}/runs/${$}/submit_tool_outputs`,{body:J,...W,headers:{"OpenAI-Beta":"assistants=v2",...W?.headers},stream:J.stream??!1})}async submitToolOutputsAndPoll(T,$,J,W){let X=await this.submitToolOutputs(T,$,J,W);return await this.poll(T,X.id,W)}submitToolOutputsStream(T,$,J,W){return MJ.createToolAssistantStream(T,$,this._client.beta.threads.runs,J,W)}}class Q2 extends BT{}o1.RunsPage=Q2;o1.Steps=EW;o1.RunStepsPage=w2;class D1 extends b{constructor(){super(...arguments);this.runs=new o1(this._client),this.messages=new VW(this._client)}create(T={},$){if(AT(T))return this.create({},T);return this._client.post("/threads",{body:T,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}retrieve(T,$){return this._client.get(`/threads/${T}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}update(T,$,J){return this._client.post(`/threads/${T}`,{body:$,...J,headers:{"OpenAI-Beta":"assistants=v2",...J?.headers}})}del(T,$){return this._client.delete(`/threads/${T}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}createAndRun(T,$){return this._client.post("/threads/runs",{body:T,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers},stream:T.stream??!1})}async createAndRunPoll(T,$){let J=await this.createAndRun(T,$);return await this.runs.poll(J.thread_id,J.id,$)}createAndRunStream(T,$){return MJ.createThreadAssistantStream(T,this._client.beta.threads,$)}}D1.Runs=o1;D1.RunsPage=Q2;D1.Messages=VW;D1.MessagesPage=A2;class tJ extends b{constructor(){super(...arguments);this.realtime=new k0(this._client),this.chat=new H2(this._client),this.assistants=new _W(this._client),this.threads=new D1(this._client)}}tJ.Realtime=k0;tJ.Assistants=_W;tJ.AssistantsPage=X2;tJ.Threads=D1;class RW extends b{create(T,$){return this._client.post("/completions",{body:T,...$,stream:T.stream??!1})}}class LW extends b{create(T,$){let J=!!T.encoding_format,W=J?T.encoding_format:"base64";if(J)A1("Request","User defined encoding_format:",T.encoding_format);let X=this._client.post("/embeddings",{body:{...T,encoding_format:W},...$});if(J)return X;return A1("response","Decoding base64 embeddings to float32 array"),X._thenUnwrap((F)=>{if(F&&F.data)F.data.forEach((Y)=>{let G=Y.embedding;Y.embedding=R3(G)});return F})}}class BW extends b{retrieve(T,$,J,W){return this._client.get(`/evals/${T}/runs/${$}/output_items/${J}`,W)}list(T,$,J={},W){if(AT(J))return this.list(T,$,{},J);return this._client.getAPIList(`/evals/${T}/runs/${$}/output_items`,O2,{query:J,...W})}}class O2 extends BT{}BW.OutputItemListResponsesPage=O2;class d1 extends b{constructor(){super(...arguments);this.outputItems=new BW(this._client)}create(T,$,J){return this._client.post(`/evals/${T}/runs`,{body:$,...J})}retrieve(T,$,J){return this._client.get(`/evals/${T}/runs/${$}`,J)}list(T,$={},J){if(AT($))return this.list(T,{},$);return this._client.getAPIList(`/evals/${T}/runs`,U2,{query:$,...J})}del(T,$,J){return this._client.delete(`/evals/${T}/runs/${$}`,J)}cancel(T,$,J){return this._client.post(`/evals/${T}/runs/${$}`,J)}}class U2 extends BT{}d1.RunListResponsesPage=U2;d1.OutputItems=BW;d1.OutputItemListResponsesPage=O2;class K1 extends b{constructor(){super(...arguments);this.runs=new d1(this._client)}create(T,$){return this._client.post("/evals",{body:T,...$})}retrieve(T,$){return this._client.get(`/evals/${T}`,$)}update(T,$,J){return this._client.post(`/evals/${T}`,{body:$,...J})}list(T={},$){if(AT(T))return this.list({},T);return this._client.getAPIList("/evals",fW,{query:T,...$})}del(T,$){return this._client.delete(`/evals/${T}`,$)}}class fW extends BT{}K1.EvalListResponsesPage=fW;K1.Runs=d1;K1.RunListResponsesPage=U2;class y0 extends b{create(T,$){return this._client.post("/files",SJ({body:T,...$}))}retrieve(T,$){return this._client.get(`/files/${T}`,$)}list(T={},$){if(AT(T))return this.list({},T);return this._client.getAPIList("/files",NW,{query:T,...$})}del(T,$){return this._client.delete(`/files/${T}`,$)}content(T,$){return this._client.get(`/files/${T}/content`,{...$,headers:{Accept:"application/binary",...$?.headers},__binaryResponse:!0})}retrieveContent(T,$){return this._client.get(`/files/${T}/content`,$)}async waitForProcessing(T,{pollInterval:$=5000,maxWait:J=1800000}={}){let W=new Set(["processed","error","deleted"]),X=Date.now(),F=await this.retrieve(T);while(!F.status||!W.has(F.status))if(await w1($),F=await this.retrieve(T),Date.now()-X>J)throw new S0({message:`Giving up on waiting for file ${T} to finish processing after ${J} milliseconds.`});return F}}class NW extends BT{}y0.FileObjectsPage=NW;class CW extends b{create(T,$,J){return this._client.getAPIList(`/fine_tuning/checkpoints/${T}/permissions`,_2,{body:$,method:"post",...J})}retrieve(T,$={},J){if(AT($))return this.retrieve(T,{},$);return this._client.get(`/fine_tuning/checkpoints/${T}/permissions`,{query:$,...J})}del(T,$,J){return this._client.delete(`/fine_tuning/checkpoints/${T}/permissions/${$}`,J)}}class _2 extends Q1{}CW.PermissionCreateResponsesPage=_2;class I0 extends b{constructor(){super(...arguments);this.permissions=new CW(this._client)}}I0.Permissions=CW;I0.PermissionCreateResponsesPage=_2;class ZW extends b{list(T,$={},J){if(AT($))return this.list(T,{},$);return this._client.getAPIList(`/fine_tuning/jobs/${T}/checkpoints`,D2,{query:$,...J})}}class D2 extends BT{}ZW.FineTuningJobCheckpointsPage=D2;class S1 extends b{constructor(){super(...arguments);this.checkpoints=new ZW(this._client)}create(T,$){return this._client.post("/fine_tuning/jobs",{body:T,...$})}retrieve(T,$){return this._client.get(`/fine_tuning/jobs/${T}`,$)}list(T={},$){if(AT(T))return this.list({},T);return this._client.getAPIList("/fine_tuning/jobs",K2,{query:T,...$})}cancel(T,$){return this._client.post(`/fine_tuning/jobs/${T}/cancel`,$)}listEvents(T,$={},J){if(AT($))return this.listEvents(T,{},$);return this._client.getAPIList(`/fine_tuning/jobs/${T}/events`,S2,{query:$,...J})}}class K2 extends BT{}class S2 extends BT{}S1.FineTuningJobsPage=K2;S1.FineTuningJobEventsPage=S2;S1.Checkpoints=ZW;S1.FineTuningJobCheckpointsPage=D2;class rJ extends b{constructor(){super(...arguments);this.jobs=new S1(this._client),this.checkpoints=new I0(this._client)}}rJ.Jobs=S1;rJ.FineTuningJobsPage=K2;rJ.FineTuningJobEventsPage=S2;rJ.Checkpoints=I0;class qW extends b{createVariation(T,$){return this._client.post("/images/variations",SJ({body:T,...$}))}edit(T,$){return this._client.post("/images/edits",SJ({body:T,...$}))}generate(T,$){return this._client.post("/images/generations",{body:T,...$})}}class j0 extends b{retrieve(T,$){return this._client.get(`/models/${T}`,$)}list(T){return this._client.getAPIList("/models",kW,T)}del(T,$){return this._client.delete(`/models/${T}`,$)}}class kW extends Q1{}j0.ModelsPage=kW;class yW extends b{create(T,$){return this._client.post("/moderations",{body:T,...$})}}function p3(T,$){if(!$||!aD($))return{...T,output_parsed:null,output:T.output.map((J)=>{if(J.type==="function_call")return{...J,parsed_arguments:null};if(J.type==="message")return{...J,content:J.content.map((W)=>({...W,parsed:null}))};else return J})};return SY(T,$)}function SY(T,$){let J=T.output.map((X)=>{if(X.type==="function_call")return{...X,parsed_arguments:TK($,X)};if(X.type==="message"){let F=X.content.map((Y)=>{if(Y.type==="output_text")return{...Y,parsed:rD($,Y.text)};return Y});return{...X,content:F}}return X}),W=Object.assign({},T,{output:J});if(!Object.getOwnPropertyDescriptor(T,"output_text"))VY(W);return Object.defineProperty(W,"output_parsed",{enumerable:!0,get(){for(let X of W.output){if(X.type!=="message")continue;for(let F of X.content)if(F.type==="output_text"&&F.parsed!==null)return F.parsed}return null}}),W}function rD(T,$){if(T.text?.format?.type!=="json_schema")return null;if("$parseRaw"in T.text?.format)return(T.text?.format).$parseRaw($);return JSON.parse($)}function aD(T){if(F2(T.text?.format))return!0;return!1}function sD(T){return T?.$brand==="auto-parseable-tool"}function eD(T,$){return T.find((J)=>J.type==="function"&&J.name===$)}function TK(T,$){let J=eD(T.tools??[],$.name);return{...$,...$,parsed_arguments:sD(J)?J.$parseRaw($.arguments):J?.strict?JSON.parse($.arguments):null}}function VY(T){let $=[];for(let J of T.output){if(J.type!=="message")continue;for(let W of J.content)if(W.type==="output_text")$.push(W.text)}T.output_text=$.join("")}class V2 extends b{list(T,$={},J){if(AT($))return this.list(T,{},$);return this._client.getAPIList(`/responses/${T}/input_items`,EY,{query:$,...J})}}var IW=function(T,$,J,W,X){if(W==="m")throw new TypeError("Private method is not writable");if(W==="a"&&!X)throw new TypeError("Private accessor was defined without a setter");if(typeof $==="function"?T!==$||!X:!$.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return W==="a"?X.call(T,J):X?X.value=J:$.set(T,J),J},l1=function(T,$,J,W){if(J==="a"&&!W)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?T!==$||!W:!$.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return J==="m"?W:J==="a"?W.call(T):W?W.value:$.get(T)},jW,k4,n1,y4,u3,c3,o3,d3;class I4 extends B0{constructor(T){super();jW.add(this),k4.set(this,void 0),n1.set(this,void 0),y4.set(this,void 0),IW(this,k4,T,"f")}static createResponse(T,$,J){let W=new I4($);return W._run(()=>W._createResponse(T,$,{...J,headers:{...J?.headers,"X-Stainless-Helper-Method":"stream"}})),W}async _createResponse(T,$,J){let W=J?.signal;if(W){if(W.aborted)this.controller.abort();W.addEventListener("abort",()=>this.controller.abort())}l1(this,jW,"m",u3).call(this);let X=await T.responses.create({...$,stream:!0},{...J,signal:this.controller.signal});this._connected();for await(let F of X)l1(this,jW,"m",c3).call(this,F);if(X.controller.signal?.aborted)throw new U$;return l1(this,jW,"m",o3).call(this)}[(k4=new WeakMap,n1=new WeakMap,y4=new WeakMap,jW=new WeakSet,u3=function T(){if(this.ended)return;IW(this,n1,void 0,"f")},c3=function T($){if(this.ended)return;let J=l1(this,jW,"m",d3).call(this,$);switch(this._emit("event",$),$.type){case"response.output_text.delta":{let W=J.output[$.output_index];if(!W)throw new t(`missing output at index ${$.output_index}`);if(W.type==="message"){let X=W.content[$.content_index];if(!X)throw new t(`missing content at index ${$.content_index}`);if(X.type!=="output_text")throw new t(`expected content to be 'output_text', got ${X.type}`);this._emit("response.output_text.delta",{...$,snapshot:X.text})}break}case"response.function_call_arguments.delta":{let W=J.output[$.output_index];if(!W)throw new t(`missing output at index ${$.output_index}`);if(W.type==="function_call")this._emit("response.function_call_arguments.delta",{...$,snapshot:W.arguments});break}default:this._emit($.type,$);break}},o3=function T(){if(this.ended)throw new t("stream has ended, this shouldn't happen");let $=l1(this,n1,"f");if(!$)throw new t("request ended without sending any events");IW(this,n1,void 0,"f");let J=JK($,l1(this,k4,"f"));return IW(this,y4,J,"f"),J},d3=function T($){let J=l1(this,n1,"f");if(!J){if($.type!=="response.created")throw new t(`When snapshot hasn't been set yet, expected 'response.created' event, got ${$.type}`);return J=IW(this,n1,$.response,"f"),J}switch($.type){case"response.output_item.added":{J.output.push($.item);break}case"response.content_part.added":{let W=J.output[$.output_index];if(!W)throw new t(`missing output at index ${$.output_index}`);if(W.type==="message")W.content.push($.part);break}case"response.output_text.delta":{let W=J.output[$.output_index];if(!W)throw new t(`missing output at index ${$.output_index}`);if(W.type==="message"){let X=W.content[$.content_index];if(!X)throw new t(`missing content at index ${$.content_index}`);if(X.type!=="output_text")throw new t(`expected content to be 'output_text', got ${X.type}`);X.text+=$.delta}break}case"response.function_call_arguments.delta":{let W=J.output[$.output_index];if(!W)throw new t(`missing output at index ${$.output_index}`);if(W.type==="function_call")W.arguments+=$.delta;break}case"response.completed":{IW(this,n1,$.response,"f");break}}return J},Symbol.asyncIterator)](){let T=[],$=[],J=!1;return this.on("event",(W)=>{let X=$.shift();if(X)X.resolve(W);else T.push(W)}),this.on("end",()=>{J=!0;for(let W of $)W.resolve(void 0);$.length=0}),this.on("abort",(W)=>{J=!0;for(let X of $)X.reject(W);$.length=0}),this.on("error",(W)=>{J=!0;for(let X of $)X.reject(W);$.length=0}),{next:async()=>{if(!T.length){if(J)return{value:void 0,done:!0};return new Promise((X,F)=>$.push({resolve:X,reject:F})).then((X)=>X?{value:X,done:!1}:{value:void 0,done:!0})}return{value:T.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}async finalResponse(){await this.done();let T=l1(this,y4,"f");if(!T)throw new t("stream ended without producing a ChatCompletion");return T}}function JK(T,$){return p3(T,$)}class x0 extends b{constructor(){super(...arguments);this.inputItems=new V2(this._client)}create(T,$){return this._client.post("/responses",{body:T,...$,stream:T.stream??!1})._thenUnwrap((J)=>{if("object"in J&&J.object==="response")VY(J);return J})}retrieve(T,$={},J){if(AT($))return this.retrieve(T,{},$);return this._client.get(`/responses/${T}`,{query:$,...J})}del(T,$){return this._client.delete(`/responses/${T}`,{...$,headers:{Accept:"*/*",...$?.headers}})}parse(T,$){return this._client.responses.create(T,$)._thenUnwrap((J)=>SY(J,T))}stream(T,$){return I4.createResponse(this._client,T,$)}}class EY extends BT{}x0.InputItems=V2;class E2 extends b{create(T,$,J){return this._client.post(`/uploads/${T}/parts`,SJ({body:$,...J}))}}class P0 extends b{constructor(){super(...arguments);this.parts=new E2(this._client)}create(T,$){return this._client.post("/uploads",{body:T,...$})}cancel(T,$){return this._client.post(`/uploads/${T}/cancel`,$)}complete(T,$,J){return this._client.post(`/uploads/${T}/complete`,{body:$,...J})}}P0.Parts=E2;var l3=async(T)=>{let $=await Promise.allSettled(T),J=$.filter((X)=>X.status==="rejected");if(J.length){for(let X of J)console.error(X.reason);throw new Error(`${J.length} promise(s) failed - see the above errors`)}let W=[];for(let X of $)if(X.status==="fulfilled")W.push(X.value);return W};class b0 extends b{create(T,$,J){return this._client.post(`/vector_stores/${T}/files`,{body:$,...J,headers:{"OpenAI-Beta":"assistants=v2",...J?.headers}})}retrieve(T,$,J){return this._client.get(`/vector_stores/${T}/files/${$}`,{...J,headers:{"OpenAI-Beta":"assistants=v2",...J?.headers}})}update(T,$,J,W){return this._client.post(`/vector_stores/${T}/files/${$}`,{body:J,...W,headers:{"OpenAI-Beta":"assistants=v2",...W?.headers}})}list(T,$={},J){if(AT($))return this.list(T,{},$);return this._client.getAPIList(`/vector_stores/${T}/files`,v0,{query:$,...J,headers:{"OpenAI-Beta":"assistants=v2",...J?.headers}})}del(T,$,J){return this._client.delete(`/vector_stores/${T}/files/${$}`,{...J,headers:{"OpenAI-Beta":"assistants=v2",...J?.headers}})}async createAndPoll(T,$,J){let W=await this.create(T,$,J);return await this.poll(T,W.id,J)}async poll(T,$,J){let W={...J?.headers,"X-Stainless-Poll-Helper":"true"};if(J?.pollIntervalMs)W["X-Stainless-Custom-Poll-Interval"]=J.pollIntervalMs.toString();while(!0){let X=await this.retrieve(T,$,{...J,headers:W}).withResponse(),F=X.data;switch(F.status){case"in_progress":let Y=5000;if(J?.pollIntervalMs)Y=J.pollIntervalMs;else{let G=X.response.headers.get("openai-poll-after-ms");if(G){let H=parseInt(G);if(!isNaN(H))Y=H}}await w1(Y);break;case"failed":case"completed":return F}}}async upload(T,$,J){let W=await this._client.files.create({file:$,purpose:"assistants"},J);return this.create(T,{file_id:W.id},J)}async uploadAndPoll(T,$,J){let W=await this.upload(T,$,J);return await this.poll(T,W.id,J)}content(T,$,J){return this._client.getAPIList(`/vector_stores/${T}/files/${$}/content`,R2,{...J,headers:{"OpenAI-Beta":"assistants=v2",...J?.headers}})}}class v0 extends BT{}class R2 extends Q1{}b0.VectorStoreFilesPage=v0;b0.FileContentResponsesPage=R2;class L2 extends b{create(T,$,J){return this._client.post(`/vector_stores/${T}/file_batches`,{body:$,...J,headers:{"OpenAI-Beta":"assistants=v2",...J?.headers}})}retrieve(T,$,J){return this._client.get(`/vector_stores/${T}/file_batches/${$}`,{...J,headers:{"OpenAI-Beta":"assistants=v2",...J?.headers}})}cancel(T,$,J){return this._client.post(`/vector_stores/${T}/file_batches/${$}/cancel`,{...J,headers:{"OpenAI-Beta":"assistants=v2",...J?.headers}})}async createAndPoll(T,$,J){let W=await this.create(T,$);return await this.poll(T,W.id,J)}listFiles(T,$,J={},W){if(AT(J))return this.listFiles(T,$,{},J);return this._client.getAPIList(`/vector_stores/${T}/file_batches/${$}/files`,v0,{query:J,...W,headers:{"OpenAI-Beta":"assistants=v2",...W?.headers}})}async poll(T,$,J){let W={...J?.headers,"X-Stainless-Poll-Helper":"true"};if(J?.pollIntervalMs)W["X-Stainless-Custom-Poll-Interval"]=J.pollIntervalMs.toString();while(!0){let{data:X,response:F}=await this.retrieve(T,$,{...J,headers:W}).withResponse();switch(X.status){case"in_progress":let Y=5000;if(J?.pollIntervalMs)Y=J.pollIntervalMs;else{let G=F.headers.get("openai-poll-after-ms");if(G){let H=parseInt(G);if(!isNaN(H))Y=H}}await w1(Y);break;case"failed":case"cancelled":case"completed":return X}}}async uploadAndPoll(T,{files:$,fileIds:J=[]},W){if($==null||$.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let X=W?.maxConcurrency??5,F=Math.min(X,$.length),Y=this._client,G=$.values(),H=[...J];async function M(A){for(let w of A){let _=await Y.files.create({file:w,purpose:"assistants"},W);H.push(_.id)}}let z=Array(F).fill(G).map(M);return await l3(z),await this.createAndPoll(T,{file_ids:H})}}class VJ extends b{constructor(){super(...arguments);this.files=new b0(this._client),this.fileBatches=new L2(this._client)}create(T,$){return this._client.post("/vector_stores",{body:T,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}retrieve(T,$){return this._client.get(`/vector_stores/${T}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}update(T,$,J){return this._client.post(`/vector_stores/${T}`,{body:$,...J,headers:{"OpenAI-Beta":"assistants=v2",...J?.headers}})}list(T={},$){if(AT(T))return this.list({},T);return this._client.getAPIList("/vector_stores",xW,{query:T,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}del(T,$){return this._client.delete(`/vector_stores/${T}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}search(T,$,J){return this._client.getAPIList(`/vector_stores/${T}/search`,PW,{body:$,method:"post",...J,headers:{"OpenAI-Beta":"assistants=v2",...J?.headers}})}}class xW extends BT{}class PW extends Q1{}VJ.VectorStoresPage=xW;VJ.VectorStoreSearchResponsesPage=PW;VJ.Files=b0;VJ.VectorStoreFilesPage=v0;VJ.FileContentResponsesPage=R2;VJ.FileBatches=L2;var n3;class wT extends TY{constructor({baseURL:T=dX("OPENAI_BASE_URL"),apiKey:$=dX("OPENAI_API_KEY"),organization:J=dX("OPENAI_ORG_ID")??null,project:W=dX("OPENAI_PROJECT_ID")??null,...X}={}){if($===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' }).");let F={apiKey:$,organization:J,project:W,...X,baseURL:T||"https://api.openai.com/v1"};if(!F.dangerouslyAllowBrowser&&E3())throw new t(`It looks like you're running in a browser-like environment.
13
+ `,JSON.stringify(M.issues,null,"\t")),U.push({response:T,error:M})}return $?.error(`safegen was unable to generate well-formed data after ${F} failed attempts.`),J}}}function B3(W){return["Please generate a response in JSON that conforms to the following JSON Schema:",JSON.stringify(W,null,2)].join(`
14
+ `)}var OX="RFC3986",KX={RFC1738:(W)=>String(W).replace(/%20/g,"+"),RFC3986:(W)=>String(W)},R3="RFC1738";var UD=Array.isArray,xW=(()=>{let W=[];for(let $=0;$<256;++$)W.push("%"+(($<16?"0":"")+$.toString(16)).toUpperCase());return W})();var m9=1024,Z3=(W,$,X,Y,J)=>{if(W.length===0)return W;let G=W;if(typeof W==="symbol")G=Symbol.prototype.toString.call(W);else if(typeof W!=="string")G=String(W);if(X==="iso-8859-1")return escape(G).replace(/%u[0-9a-f]{4}/gi,function(Q){return"%26%23"+parseInt(Q.slice(2),16)+"%3B"});let H="";for(let Q=0;Q<G.length;Q+=m9){let z=G.length>=m9?G.slice(Q,Q+m9):G,F=[];for(let T=0;T<z.length;++T){let U=z.charCodeAt(T);if(U===45||U===46||U===95||U===126||U>=48&&U<=57||U>=65&&U<=90||U>=97&&U<=122||J===R3&&(U===40||U===41)){F[F.length]=z.charAt(T);continue}if(U<128){F[F.length]=xW[U];continue}if(U<2048){F[F.length]=xW[192|U>>6]+xW[128|U&63];continue}if(U<55296||U>=57344){F[F.length]=xW[224|U>>12]+xW[128|U>>6&63]+xW[128|U&63];continue}T+=1,U=65536+((U&1023)<<10|z.charCodeAt(T)&1023),F[F.length]=xW[240|U>>18]+xW[128|U>>12&63]+xW[128|U>>6&63]+xW[128|U&63]}H+=F.join("")}return H};function S3(W){if(!W||typeof W!=="object")return!1;return!!(W.constructor&&W.constructor.isBuffer&&W.constructor.isBuffer(W))}function p9(W,$){if(UD(W)){let X=[];for(let Y=0;Y<W.length;Y+=1)X.push($(W[Y]));return X}return $(W)}var wD=Object.prototype.hasOwnProperty,q3={brackets(W){return String(W)+"[]"},comma:"comma",indices(W,$){return String(W)+"["+$+"]"},repeat(W){return String(W)}},vW=Array.isArray,MD=Array.prototype.push,C3=function(W,$){MD.apply(W,vW($)?$:[$])},_D=Date.prototype.toISOString,$1={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Z3,encodeValuesOnly:!1,format:OX,formatter:KX[OX],indices:!1,serializeDate(W){return _D.call(W)},skipNulls:!1,strictNullHandling:!1};function DD(W){return typeof W==="string"||typeof W==="number"||typeof W==="boolean"||typeof W==="symbol"||typeof W==="bigint"}var u9={};function k3(W,$,X,Y,J,G,H,Q,z,F,T,U,M,V,K,N,I,C){let B=W,q=C,m=0,c=!1;while((q=q.get(u9))!==void 0&&!c){let E=q.get(W);if(m+=1,typeof E!=="undefined")if(E===m)throw new RangeError("Cyclic object value");else c=!0;if(typeof q.get(u9)==="undefined")m=0}if(typeof F==="function")B=F($,B);else if(B instanceof Date)B=M?.(B);else if(X==="comma"&&vW(B))B=p9(B,function(E){if(E instanceof Date)return M?.(E);return E});if(B===null){if(G)return z&&!N?z($,$1.encoder,I,"key",V):$;B=""}if(DD(B)||S3(B)){if(z){let E=N?$:z($,$1.encoder,I,"key",V);return[K?.(E)+"="+K?.(z(B,$1.encoder,I,"value",V))]}return[K?.($)+"="+K?.(String(B))]}let v=[];if(typeof B==="undefined")return v;let h;if(X==="comma"&&vW(B)){if(N&&z)B=p9(B,z);h=[{value:B.length>0?B.join(",")||null:void 0}]}else if(vW(F))h=F;else{let E=Object.keys(B);h=T?E.sort(T):E}let U0=Q?String($).replace(/\./g,"%2E"):String($),m0=Y&&vW(B)&&B.length===1?U0+"[]":U0;if(J&&vW(B)&&B.length===0)return m0+"[]";for(let E=0;E<h.length;++E){let _0=h[E],e=typeof _0==="object"&&typeof _0.value!=="undefined"?_0.value:B[_0];if(H&&e===null)continue;let w0=U&&Q?_0.replace(/\./g,"%2E"):_0,s0=vW(B)?typeof X==="function"?X(m0,w0):m0:m0+(U?"."+w0:"["+w0+"]");C.set(W,m);let D1=new WeakMap;D1.set(u9,C),C3(v,k3(e,s0,X,Y,J,G,H,Q,X==="comma"&&N&&vW(B)?null:z,F,T,U,M,V,K,N,I,D1))}return v}function VD(W=$1){if(typeof W.allowEmptyArrays!=="undefined"&&typeof W.allowEmptyArrays!=="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof W.encodeDotInKeys!=="undefined"&&typeof W.encodeDotInKeys!=="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(W.encoder!==null&&typeof W.encoder!=="undefined"&&typeof W.encoder!=="function")throw new TypeError("Encoder has to be a function.");let $=W.charset||$1.charset;if(typeof W.charset!=="undefined"&&W.charset!=="utf-8"&&W.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let X=OX;if(typeof W.format!=="undefined"){if(!wD.call(KX,W.format))throw new TypeError("Unknown format option provided.");X=W.format}let Y=KX[X],J=$1.filter;if(typeof W.filter==="function"||vW(W.filter))J=W.filter;let G;if(W.arrayFormat&&W.arrayFormat in q3)G=W.arrayFormat;else if("indices"in W)G=W.indices?"indices":"repeat";else G=$1.arrayFormat;if("commaRoundTrip"in W&&typeof W.commaRoundTrip!=="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let H=typeof W.allowDots==="undefined"?!!W.encodeDotInKeys===!0?!0:$1.allowDots:!!W.allowDots;return{addQueryPrefix:typeof W.addQueryPrefix==="boolean"?W.addQueryPrefix:$1.addQueryPrefix,allowDots:H,allowEmptyArrays:typeof W.allowEmptyArrays==="boolean"?!!W.allowEmptyArrays:$1.allowEmptyArrays,arrayFormat:G,charset:$,charsetSentinel:typeof W.charsetSentinel==="boolean"?W.charsetSentinel:$1.charsetSentinel,commaRoundTrip:!!W.commaRoundTrip,delimiter:typeof W.delimiter==="undefined"?$1.delimiter:W.delimiter,encode:typeof W.encode==="boolean"?W.encode:$1.encode,encodeDotInKeys:typeof W.encodeDotInKeys==="boolean"?W.encodeDotInKeys:$1.encodeDotInKeys,encoder:typeof W.encoder==="function"?W.encoder:$1.encoder,encodeValuesOnly:typeof W.encodeValuesOnly==="boolean"?W.encodeValuesOnly:$1.encodeValuesOnly,filter:J,format:X,formatter:Y,serializeDate:typeof W.serializeDate==="function"?W.serializeDate:$1.serializeDate,skipNulls:typeof W.skipNulls==="boolean"?W.skipNulls:$1.skipNulls,sort:typeof W.sort==="function"?W.sort:null,strictNullHandling:typeof W.strictNullHandling==="boolean"?W.strictNullHandling:$1.strictNullHandling}}function c9(W,$={}){let X=W,Y=VD($),J,G;if(typeof Y.filter==="function")G=Y.filter,X=G("",X);else if(vW(Y.filter))G=Y.filter,J=G;let H=[];if(typeof X!=="object"||X===null)return"";let Q=q3[Y.arrayFormat],z=Q==="comma"&&Y.commaRoundTrip;if(!J)J=Object.keys(X);if(Y.sort)J.sort(Y.sort);let F=new WeakMap;for(let M=0;M<J.length;++M){let V=J[M];if(Y.skipNulls&&X[V]===null)continue;C3(H,k3(X[V],V,Q,z,Y.allowEmptyArrays,Y.strictNullHandling,Y.skipNulls,Y.encodeDotInKeys,Y.encode?Y.encoder:null,Y.filter,Y.sort,Y.allowDots,Y.serializeDate,Y.format,Y.formatter,Y.encodeValuesOnly,Y.charset,F))}let T=H.join(Y.delimiter),U=Y.addQueryPrefix===!0?"?":"";if(Y.charsetSentinel)if(Y.charset==="iso-8859-1")U+="utf8=%26%2310003%3B&";else U+="utf8=%E2%9C%93&";return T.length>0?U+T:""}var o2="4.96.2";var I3=!1,i2=void 0,d9=void 0,KD=void 0,LD=void 0,AD=void 0,l9=void 0,ED=void 0,LX=void 0,o9=void 0,i9=void 0,n9=void 0,AX=void 0,r9=void 0;function j3(W,$={auto:!1}){if(I3)throw new Error(`you must \`import 'openai/shims/${W.kind}'\` before importing anything else from openai`);if(i2)throw new Error(`can't \`import 'openai/shims/${W.kind}'\` after \`import 'openai/shims/${i2}'\``);I3=$.auto,i2=W.kind,d9=W.fetch,KD=W.Request,LD=W.Response,AD=W.Headers,l9=W.FormData,ED=W.Blob,LX=W.File,o9=W.ReadableStream,i9=W.getMultipartRequestOptions,n9=W.getDefaultAgent,AX=W.fileFromPath,r9=W.isFsReadStream}class t9{constructor(W){this.body=W}get[Symbol.toStringTag](){return"MultipartBody"}}function f3({manuallyImported:W}={}){let $=W?"You may need to use polyfills":"Add one of these imports before your first `import \u2026 from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n",X,Y,J,G;try{X=fetch,Y=Request,J=Response,G=Headers}catch(H){throw new Error(`this environment is missing the following Web Fetch API type: ${H.message}. ${$}`)}return{kind:"web",fetch:X,Request:Y,Response:J,Headers:G,FormData:typeof FormData!=="undefined"?FormData:class H{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${$}`)}},Blob:typeof Blob!=="undefined"?Blob:class H{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${$}`)}},File:typeof File!=="undefined"?File:class H{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${$}`)}},ReadableStream:typeof ReadableStream!=="undefined"?ReadableStream:class H{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${$}`)}},getMultipartRequestOptions:async(H,Q)=>({...Q,body:new t9(H)}),getDefaultAgent:(H)=>{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:(H)=>!1}}import{ReadStream as BD}from"fs";function P3(){let W=f3();function $(X){return X instanceof BD}return{...W,isFsReadStream:$}}var a9=()=>{if(!i2)j3(P3(),{auto:!0})};a9();class o extends Error{}class r0 extends o{constructor(W,$,X,Y){super(`${r0.makeMessage(W,$,X)}`);this.status=W,this.headers=Y,this.request_id=Y?.["x-request-id"],this.error=$;let J=$;this.code=J?.code,this.param=J?.param,this.type=J?.type}static makeMessage(W,$,X){let Y=$?.message?typeof $.message==="string"?$.message:JSON.stringify($.message):$?JSON.stringify($):X;if(W&&Y)return`${W} ${Y}`;if(W)return`${W} status code (no body)`;if(Y)return Y;return"(no status code or body)"}static generate(W,$,X,Y){if(!W||!Y)return new n2({message:X,cause:kX($)});let J=$?.error;if(W===400)return new EX(W,J,X,Y);if(W===401)return new NX(W,J,X,Y);if(W===403)return new BX(W,J,X,Y);if(W===404)return new RX(W,J,X,Y);if(W===409)return new ZX(W,J,X,Y);if(W===422)return new SX(W,J,X,Y);if(W===429)return new qX(W,J,X,Y);if(W>=500)return new CX(W,J,X,Y);return new r0(W,J,X,Y)}}class X1 extends r0{constructor({message:W}={}){super(void 0,void 0,W||"Request was aborted.",void 0)}}class n2 extends r0{constructor({message:W,cause:$}){super(void 0,void 0,W||"Connection error.",void 0);if($)this.cause=$}}class r2 extends n2{constructor({message:W}={}){super({message:W??"Request timed out."})}}class EX extends r0{}class NX extends r0{}class BX extends r0{}class RX extends r0{}class ZX extends r0{}class SX extends r0{}class qX extends r0{}class CX extends r0{}class U4 extends o{constructor(){super("Could not parse response content as the length limit was reached")}}class w4 extends o{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}var IX=function(W,$,X,Y,J){if(Y==="m")throw new TypeError("Private method is not writable");if(Y==="a"&&!J)throw new TypeError("Private accessor was defined without a setter");if(typeof $==="function"?W!==$||!J:!$.has(W))throw new TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?J.call(W,X):J?J.value=X:$.set(W,X),X},t2=function(W,$,X,Y){if(X==="a"&&!Y)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?W!==$||!Y:!$.has(W))throw new TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call(W):Y?Y.value:$.get(W)},o1;class m8{constructor(){o1.set(this,void 0),this.buffer=new Uint8Array,IX(this,o1,null,"f")}decode(W){if(W==null)return[];let $=W instanceof ArrayBuffer?new Uint8Array(W):typeof W==="string"?new TextEncoder().encode(W):W,X=new Uint8Array(this.buffer.length+$.length);X.set(this.buffer),X.set($,this.buffer.length),this.buffer=X;let Y=[],J;while((J=ZD(this.buffer,t2(this,o1,"f")))!=null){if(J.carriage&&t2(this,o1,"f")==null){IX(this,o1,J.index,"f");continue}if(t2(this,o1,"f")!=null&&(J.index!==t2(this,o1,"f")+1||J.carriage)){Y.push(this.decodeText(this.buffer.slice(0,t2(this,o1,"f")-1))),this.buffer=this.buffer.slice(t2(this,o1,"f")),IX(this,o1,null,"f");continue}let G=t2(this,o1,"f")!==null?J.preceding-1:J.preceding,H=this.decodeText(this.buffer.slice(0,G));Y.push(H),this.buffer=this.buffer.slice(J.index),IX(this,o1,null,"f")}return Y}decodeText(W){if(W==null)return"";if(typeof W==="string")return W;if(typeof Buffer!=="undefined"){if(W instanceof Buffer)return W.toString();if(W instanceof Uint8Array)return Buffer.from(W).toString();throw new o(`Unexpected: received non-Uint8Array (${W.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(W instanceof Uint8Array||W instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(W);throw new o(`Unexpected: received non-Uint8Array/ArrayBuffer (${W.constructor.name}) in a web platform. Please report this error.`)}throw new o("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length)return[];return this.decode(`
15
+ `)}}o1=new WeakMap;m8.NEWLINE_CHARS=new Set([`
16
+ `,"\r"]);m8.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function ZD(W,$){for(let J=$??0;J<W.length;J++){if(W[J]===10)return{preceding:J,index:J+1,carriage:!1};if(W[J]===13)return{preceding:J,index:J+1,carriage:!0}}return null}function x3(W){for(let Y=0;Y<W.length-1;Y++){if(W[Y]===10&&W[Y+1]===10)return Y+2;if(W[Y]===13&&W[Y+1]===13)return Y+2;if(W[Y]===13&&W[Y+1]===10&&Y+3<W.length&&W[Y+2]===13&&W[Y+3]===10)return Y+4}return-1}function s9(W){if(W[Symbol.asyncIterator])return W;let $=W.getReader();return{async next(){try{let X=await $.read();if(X?.done)$.releaseLock();return X}catch(X){throw $.releaseLock(),X}},async return(){let X=$.cancel();return $.releaseLock(),await X,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}class i1{constructor(W,$){this.iterator=W,this.controller=$}static fromSSEResponse(W,$){let X=!1;async function*Y(){if(X)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");X=!0;let J=!1;try{for await(let G of SD(W,$)){if(J)continue;if(G.data.startsWith("[DONE]")){J=!0;continue}if(G.event===null||G.event.startsWith("response.")||G.event.startsWith("transcript.")){let H;try{H=JSON.parse(G.data)}catch(Q){throw console.error("Could not parse message into JSON:",G.data),console.error("From chunk:",G.raw),Q}if(H&&H.error)throw new r0(void 0,H.error,void 0,e9(W.headers));yield H}else{let H;try{H=JSON.parse(G.data)}catch(Q){throw console.error("Could not parse message into JSON:",G.data),console.error("From chunk:",G.raw),Q}if(G.event=="error")throw new r0(void 0,H.error,H.message,void 0);yield{event:G.event,data:H}}}J=!0}catch(G){if(G instanceof Error&&G.name==="AbortError")return;throw G}finally{if(!J)$.abort()}}return new i1(Y,$)}static fromReadableStream(W,$){let X=!1;async function*Y(){let G=new m8,H=s9(W);for await(let Q of H)for(let z of G.decode(Q))yield z;for(let Q of G.flush())yield Q}async function*J(){if(X)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");X=!0;let G=!1;try{for await(let H of Y()){if(G)continue;if(H)yield JSON.parse(H)}G=!0}catch(H){if(H instanceof Error&&H.name==="AbortError")return;throw H}finally{if(!G)$.abort()}}return new i1(J,$)}[Symbol.asyncIterator](){return this.iterator()}tee(){let W=[],$=[],X=this.iterator(),Y=(J)=>{return{next:()=>{if(J.length===0){let G=X.next();W.push(G),$.push(G)}return J.shift()}}};return[new i1(()=>Y(W),this.controller),new i1(()=>Y($),this.controller)]}toReadableStream(){let W=this,$,X=new TextEncoder;return new o9({async start(){$=W[Symbol.asyncIterator]()},async pull(Y){try{let{value:J,done:G}=await $.next();if(G)return Y.close();let H=X.encode(JSON.stringify(J)+`
17
+ `);Y.enqueue(H)}catch(J){Y.error(J)}},async cancel(){await $.return?.()}})}}async function*SD(W,$){if(!W.body)throw $.abort(),new o("Attempted to iterate over a response with no body");let X=new v3,Y=new m8,J=s9(W.body);for await(let G of qD(J))for(let H of Y.decode(G)){let Q=X.decode(H);if(Q)yield Q}for(let G of Y.flush()){let H=X.decode(G);if(H)yield H}}async function*qD(W){let $=new Uint8Array;for await(let X of W){if(X==null)continue;let Y=X instanceof ArrayBuffer?new Uint8Array(X):typeof X==="string"?new TextEncoder().encode(X):X,J=new Uint8Array($.length+Y.length);J.set($),J.set(Y,$.length),$=J;let G;while((G=x3($))!==-1)yield $.slice(0,G),$=$.slice(G)}if($.length>0)yield $}class v3{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(W){if(W.endsWith("\r"))W=W.substring(0,W.length-1);if(!W){if(!this.event&&!this.data.length)return null;let J={event:this.event,data:this.data.join(`
18
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],J}if(this.chunks.push(W),W.startsWith(":"))return null;let[$,X,Y]=CD(W,":");if(Y.startsWith(" "))Y=Y.substring(1);if($==="event")this.event=Y;else if($==="data")this.data.push(Y);return null}}function CD(W,$){let X=W.indexOf($);if(X!==-1)return[W.substring(0,X),$,W.substring(X+$.length)];return[W,"",""]}var b3=(W)=>W!=null&&typeof W==="object"&&typeof W.url==="string"&&typeof W.blob==="function",y3=(W)=>W!=null&&typeof W==="object"&&typeof W.name==="string"&&typeof W.lastModified==="number"&&M4(W),M4=(W)=>W!=null&&typeof W==="object"&&typeof W.size==="number"&&typeof W.type==="string"&&typeof W.text==="function"&&typeof W.slice==="function"&&typeof W.arrayBuffer==="function",kD=(W)=>{return y3(W)||b3(W)||r9(W)};async function XJ(W,$,X){if(W=await W,y3(W))return W;if(b3(W)){let J=await W.blob();$||($=new URL(W.url).pathname.split(/[\\/]/).pop()??"unknown_file");let G=M4(J)?[await J.arrayBuffer()]:[J];return new LX(G,$,X)}let Y=await ID(W);if($||($=fD(W)??"unknown_file"),!X?.type){let J=Y[0]?.type;if(typeof J==="string")X={...X,type:J}}return new LX(Y,$,X)}async function ID(W){let $=[];if(typeof W==="string"||ArrayBuffer.isView(W)||W instanceof ArrayBuffer)$.push(W);else if(M4(W))$.push(await W.arrayBuffer());else if(PD(W))for await(let X of W)$.push(X);else throw new Error(`Unexpected data type: ${typeof W}; constructor: ${W?.constructor?.name}; props: ${jD(W)}`);return $}function jD(W){return`[${Object.getOwnPropertyNames(W).map((X)=>`"${X}"`).join(", ")}]`}function fD(W){return WJ(W.name)||WJ(W.filename)||WJ(W.path)?.split(/[\\/]/).pop()}var WJ=(W)=>{if(typeof W==="string")return W;if(typeof Buffer!=="undefined"&&W instanceof Buffer)return String(W);return},PD=(W)=>W!=null&&typeof W==="object"&&typeof W[Symbol.asyncIterator]==="function",YJ=(W)=>W&&typeof W==="object"&&W.body&&W[Symbol.toStringTag]==="MultipartBody";var YW=async(W)=>{let $=await h3(W.body);return i9($,W)},h3=async(W)=>{let $=new l9;return await Promise.all(Object.entries(W||{}).map(([X,Y])=>$J($,X,Y))),$};var $J=async(W,$,X)=>{if(X===void 0)return;if(X==null)throw new TypeError(`Received null for "${$}"; to pass null in FormData, you must use the string 'null'`);if(typeof X==="string"||typeof X==="number"||typeof X==="boolean")W.append($,String(X));else if(kD(X)){let Y=await XJ(X);W.append($,Y)}else if(Array.isArray(X))await Promise.all(X.map((Y)=>$J(W,$+"[]",Y)));else if(typeof X==="object")await Promise.all(Object.entries(X).map(([Y,J])=>$J(W,`${$}[${Y}]`,J)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${X} instead`)};var vD=function(W,$,X,Y,J){if(Y==="m")throw new TypeError("Private method is not writable");if(Y==="a"&&!J)throw new TypeError("Private accessor was defined without a setter");if(typeof $==="function"?W!==$||!J:!$.has(W))throw new TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?J.call(W,X):J?J.value=X:$.set(W,X),X},bD=function(W,$,X,Y){if(X==="a"&&!Y)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?W!==$||!Y:!$.has(W))throw new TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call(W):Y?Y.value:$.get(W)},jX;a9();async function d3(W){let{response:$}=W;if(W.options.stream){if(nW("response",$.status,$.url,$.headers,$.body),W.options.__streamClass)return W.options.__streamClass.fromSSEResponse($,W.controller);return i1.fromSSEResponse($,W.controller)}if($.status===204)return null;if(W.options.__binaryResponse)return $;let Y=$.headers.get("content-type")?.split(";")[0]?.trim();if(Y?.includes("application/json")||Y?.endsWith("+json")){let H=await $.json();return nW("response",$.status,$.url,$.headers,H),l3(H,$)}let G=await $.text();return nW("response",$.status,$.url,$.headers,G),G}function l3(W,$){if(!W||typeof W!=="object"||Array.isArray(W))return W;return Object.defineProperty(W,"_request_id",{value:$.headers.get("x-request-id"),enumerable:!1})}class PX extends Promise{constructor(W,$=d3){super((X)=>{X(null)});this.responsePromise=W,this.parseResponse=$}_thenUnwrap(W){return new PX(this.responsePromise,async($)=>l3(W(await this.parseResponse($),$),$.response))}asResponse(){return this.responsePromise.then((W)=>W.response)}async withResponse(){let[W,$]=await Promise.all([this.parse(),this.asResponse()]);return{data:W,response:$,request_id:$.headers.get("x-request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(this.parseResponse);return this.parsedPromise}then(W,$){return this.parse().then(W,$)}catch(W){return this.parse().catch(W)}finally(W){return this.parse().finally(W)}}class GJ{constructor({baseURL:W,maxRetries:$=2,timeout:X=600000,httpAgent:Y,fetch:J}){this.baseURL=W,this.maxRetries=JJ("maxRetries",$),this.timeout=JJ("timeout",X),this.httpAgent=Y,this.fetch=J??d9}authHeaders(W){return{}}defaultHeaders(W){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...mD(),...this.authHeaders(W)}}validateHeaders(W,$){}defaultIdempotencyKey(){return`stainless-node-retry-${dD()}`}get(W,$){return this.methodRequest("get",W,$)}post(W,$){return this.methodRequest("post",W,$)}patch(W,$){return this.methodRequest("patch",W,$)}put(W,$){return this.methodRequest("put",W,$)}delete(W,$){return this.methodRequest("delete",W,$)}methodRequest(W,$,X){return this.request(Promise.resolve(X).then(async(Y)=>{let J=Y&&M4(Y?.body)?new DataView(await Y.body.arrayBuffer()):Y?.body instanceof DataView?Y.body:Y?.body instanceof ArrayBuffer?new DataView(Y.body):Y&&ArrayBuffer.isView(Y?.body)?new DataView(Y.body.buffer):Y?.body;return{method:W,path:$,...Y,body:J}}))}getAPIList(W,$,X){return this.requestAPIList($,{method:"get",path:W,...X})}calculateContentLength(W){if(typeof W==="string"){if(typeof Buffer!=="undefined")return Buffer.byteLength(W,"utf8").toString();if(typeof TextEncoder!=="undefined")return new TextEncoder().encode(W).length.toString()}else if(ArrayBuffer.isView(W))return W.byteLength.toString();return null}buildRequest(W,{retryCount:$=0}={}){let X={...W},{method:Y,path:J,query:G,headers:H={}}=X,Q=ArrayBuffer.isView(X.body)||X.__binaryRequest&&typeof X.body==="string"?X.body:YJ(X.body)?X.body.body:X.body?JSON.stringify(X.body,null,2):null,z=this.calculateContentLength(Q),F=this.buildURL(J,G);if("timeout"in X)JJ("timeout",X.timeout);X.timeout=X.timeout??this.timeout;let T=X.httpAgent??this.httpAgent??n9(F),U=X.timeout+1000;if(typeof T?.options?.timeout==="number"&&U>(T.options.timeout??0))T.options.timeout=U;if(this.idempotencyHeader&&Y!=="get"){if(!W.idempotencyKey)W.idempotencyKey=this.defaultIdempotencyKey();H[this.idempotencyHeader]=W.idempotencyKey}let M=this.buildHeaders({options:X,headers:H,contentLength:z,retryCount:$});return{req:{method:Y,...Q&&{body:Q},headers:M,...T&&{agent:T},signal:X.signal??null},url:F,timeout:X.timeout}}buildHeaders({options:W,headers:$,contentLength:X,retryCount:Y}){let J={};if(X)J["content-length"]=X;let G=this.defaultHeaders(W);if(u3(J,G),u3(J,$),YJ(W.body)&&i2!=="node")delete J["content-type"];if(fX(G,"x-stainless-retry-count")===void 0&&fX($,"x-stainless-retry-count")===void 0)J["x-stainless-retry-count"]=String(Y);if(fX(G,"x-stainless-timeout")===void 0&&fX($,"x-stainless-timeout")===void 0&&W.timeout)J["x-stainless-timeout"]=String(Math.trunc(W.timeout/1000));return this.validateHeaders(J,$),J}async prepareOptions(W){}async prepareRequest(W,{url:$,options:X}){}parseHeaders(W){return!W?{}:(Symbol.iterator in W)?Object.fromEntries(Array.from(W).map(($)=>[...$])):{...W}}makeStatusError(W,$,X,Y){return r0.generate(W,$,X,Y)}request(W,$=null){return new PX(this.makeRequest(W,$))}async makeRequest(W,$){let X=await W,Y=X.maxRetries??this.maxRetries;if($==null)$=Y;await this.prepareOptions(X);let{req:J,url:G,timeout:H}=this.buildRequest(X,{retryCount:Y-$});if(await this.prepareRequest(J,{url:G,options:X}),nW("request",G,X,J.headers),X.signal?.aborted)throw new X1;let Q=new AbortController,z=await this.fetchWithTimeout(G,J,H,Q).catch(kX);if(z instanceof Error){if(X.signal?.aborted)throw new X1;if($)return this.retryRequest(X,$);if(z.name==="AbortError")throw new r2;throw new n2({cause:z})}let F=e9(z.headers);if(!z.ok){if($&&this.shouldRetry(z)){let N=`retrying, ${$} attempts remaining`;return nW(`response (error; ${N})`,z.status,G,F),this.retryRequest(X,$,F)}let T=await z.text().catch((N)=>kX(N).message),U=pD(T),M=U?void 0:T;throw nW(`response (error; ${$?"(error; no more retries left)":"(error; not retryable)"})`,z.status,G,F,M),this.makeStatusError(z.status,U,M,F)}return{response:z,options:X,controller:Q}}requestAPIList(W,$){let X=this.makeRequest($,null);return new o3(this,X,W)}buildURL(W,$){let X=cD(W)?new URL(W):new URL(this.baseURL+(this.baseURL.endsWith("/")&&W.startsWith("/")?W.slice(1):W)),Y=this.defaultQuery();if(!i3(Y))$={...Y,...$};if(typeof $==="object"&&$&&!Array.isArray($))X.search=this.stringifyQuery($);return X.toString()}stringifyQuery(W){return Object.entries(W).filter(([$,X])=>typeof X!=="undefined").map(([$,X])=>{if(typeof X==="string"||typeof X==="number"||typeof X==="boolean")return`${encodeURIComponent($)}=${encodeURIComponent(X)}`;if(X===null)return`${encodeURIComponent($)}=`;throw new o(`Cannot stringify type ${typeof X}; 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(W,$,X,Y){let{signal:J,...G}=$||{};if(J)J.addEventListener("abort",()=>Y.abort());let H=setTimeout(()=>Y.abort(),X),Q={signal:Y.signal,...G};if(Q.method)Q.method=Q.method.toUpperCase();return this.fetch.call(void 0,W,Q).finally(()=>{clearTimeout(H)})}shouldRetry(W){let $=W.headers.get("x-should-retry");if($==="true")return!0;if($==="false")return!1;if(W.status===408)return!0;if(W.status===409)return!0;if(W.status===429)return!0;if(W.status>=500)return!0;return!1}async retryRequest(W,$,X){let Y,J=X?.["retry-after-ms"];if(J){let H=parseFloat(J);if(!Number.isNaN(H))Y=H}let G=X?.["retry-after"];if(G&&!Y){let H=parseFloat(G);if(!Number.isNaN(H))Y=H*1000;else Y=Date.parse(G)-Date.now()}if(!(Y&&0<=Y&&Y<60000)){let H=W.maxRetries??this.maxRetries;Y=this.calculateDefaultRetryTimeoutMillis($,H)}return await rW(Y),this.makeRequest(W,$-1)}calculateDefaultRetryTimeoutMillis(W,$){let J=$-W,G=Math.min(0.5*Math.pow(2,J),8),H=1-Math.random()*0.25;return G*H*1000}getUserAgent(){return`${this.constructor.name}/JS ${o2}`}}class xX{constructor(W,$,X,Y){jX.set(this,void 0),vD(this,jX,W,"f"),this.options=Y,this.response=$,this.body=X}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageInfo()!=null}async getNextPage(){let W=this.nextPageInfo();if(!W)throw new o("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let $={...this.options};if("params"in W&&typeof $.query==="object")$.query={...$.query,...W.params};else if("url"in W){let X=[...Object.entries($.query||{}),...W.url.searchParams.entries()];for(let[Y,J]of X)W.url.searchParams.set(Y,J);$.query=void 0,$.path=W.url.toString()}return await bD(this,jX,"f").requestAPIList(this.constructor,$)}async*iterPages(){let W=this;yield W;while(W.hasNextPage())W=await W.getNextPage(),yield W}async*[(jX=new WeakMap,Symbol.asyncIterator)](){for await(let W of this.iterPages())for(let $ of W.getPaginatedItems())yield $}}class o3 extends PX{constructor(W,$,X){super($,async(Y)=>new X(W,Y.response,await d3(Y),Y.options))}async*[Symbol.asyncIterator](){let W=await this;for await(let $ of W)yield $}}var e9=(W)=>{return new Proxy(Object.fromEntries(W.entries()),{get($,X){let Y=X.toString();return $[Y.toLowerCase()]||$[Y]}})},yD={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__metadata:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},H0=(W)=>{return typeof W==="object"&&W!==null&&!i3(W)&&Object.keys(W).every(($)=>n3(yD,$))},hD=()=>{if(typeof Deno!=="undefined"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":o2,"X-Stainless-OS":m3(Deno.build.os),"X-Stainless-Arch":g3(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":o2,"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":o2,"X-Stainless-OS":m3(process.platform),"X-Stainless-Arch":g3(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let W=gD();if(W)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":o2,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${W.browser}`,"X-Stainless-Runtime-Version":W.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":o2,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function gD(){if(typeof navigator==="undefined"||!navigator)return null;let W=[{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:$,pattern:X}of W){let Y=X.exec(navigator.userAgent);if(Y){let J=Y[1]||0,G=Y[2]||0,H=Y[3]||0;return{browser:$,version:`${J}.${G}.${H}`}}}return null}var g3=(W)=>{if(W==="x32")return"x32";if(W==="x86_64"||W==="x64")return"x64";if(W==="arm")return"arm";if(W==="aarch64"||W==="arm64")return"arm64";if(W)return`other:${W}`;return"unknown"},m3=(W)=>{if(W=W.toLowerCase(),W.includes("ios"))return"iOS";if(W==="android")return"Android";if(W==="darwin")return"MacOS";if(W==="win32")return"Windows";if(W==="freebsd")return"FreeBSD";if(W==="openbsd")return"OpenBSD";if(W==="linux")return"Linux";if(W)return`Other:${W}`;return"Unknown"},p3,mD=()=>{return p3??(p3=hD())},pD=(W)=>{try{return JSON.parse(W)}catch($){return}},uD=/^[a-z][a-z0-9+.-]*:/i,cD=(W)=>{return uD.test(W)},rW=(W)=>new Promise(($)=>setTimeout($,W)),JJ=(W,$)=>{if(typeof $!=="number"||!Number.isInteger($))throw new o(`${W} must be an integer`);if($<0)throw new o(`${W} must be a positive integer`);return $},kX=(W)=>{if(W instanceof Error)return W;if(typeof W==="object"&&W!==null)try{return new Error(JSON.stringify(W))}catch{}return new Error(W)};var _4=(W)=>{if(typeof process!=="undefined")return process.env?.[W]?.trim()??void 0;if(typeof Deno!=="undefined")return Deno.env?.get?.(W)?.trim();return};function i3(W){if(!W)return!0;for(let $ in W)return!1;return!0}function n3(W,$){return Object.prototype.hasOwnProperty.call(W,$)}function u3(W,$){for(let X in $){if(!n3($,X))continue;let Y=X.toLowerCase();if(!Y)continue;let J=$[X];if(J===null)delete W[Y];else if(J!==void 0)W[Y]=J}}var c3=new Set(["authorization","api-key"]);function nW(W,...$){if(typeof process!=="undefined"&&process?.env?.DEBUG==="true"){let X=$.map((Y)=>{if(!Y)return Y;if(Y.headers){let G={...Y,headers:{...Y.headers}};for(let H in Y.headers)if(c3.has(H.toLowerCase()))G.headers[H]="REDACTED";return G}let J=null;for(let G in Y)if(c3.has(G.toLowerCase()))J??(J={...Y}),J[G]="REDACTED";return J??Y});console.log(`OpenAI:DEBUG:${W}`,...X)}}var dD=()=>{return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(W)=>{let $=Math.random()*16|0;return(W==="x"?$:$&3|8).toString(16)})},r3=()=>{return typeof window!=="undefined"&&typeof window.document!=="undefined"&&typeof navigator!=="undefined"},lD=(W)=>{return typeof W?.get==="function"};var fX=(W,$)=>{let X=$.toLowerCase();if(lD(W)){let Y=$[0]?.toUpperCase()+$.substring(1).replace(/([^\w])(\w)/g,(J,G,H)=>G+H.toUpperCase());for(let J of[$,X,$.toUpperCase(),Y]){let G=W.get(J);if(G)return G}}for(let[Y,J]of Object.entries(W))if(Y.toLowerCase()===X){if(Array.isArray(J)){if(J.length<=1)return J[0];return console.warn(`Received ${J.length} entries for the ${$} header, using the first entry.`),J[0]}return J}return};var t3=(W)=>{if(typeof Buffer!=="undefined"){let $=Buffer.from(W,"base64");return Array.from(new Float32Array($.buffer,$.byteOffset,$.length/Float32Array.BYTES_PER_ELEMENT))}else{let $=atob(W),X=$.length,Y=new Uint8Array(X);for(let J=0;J<X;J++)Y[J]=$.charCodeAt(J);return Array.from(new Float32Array(Y.buffer))}};function D4(W){return W!=null&&typeof W==="object"&&!Array.isArray(W)}class tW extends xX{constructor(W,$,X,Y){super(W,$,X,Y);this.data=X.data||[],this.object=X.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class L0 extends xX{constructor(W,$,X,Y){super(W,$,X,Y);this.data=X.data||[],this.has_more=X.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageParams(){let W=this.nextPageInfo();if(!W)return null;if("params"in W)return W.params;let $=Object.fromEntries(W.url.searchParams);if(!Object.keys($).length)return null;return $}nextPageInfo(){let W=this.getPaginatedItems();if(!W.length)return null;let $=W[W.length-1]?.id;if(!$)return null;return{params:{after:$}}}}class f{constructor(W){this._client=W}}class V4 extends f{list(W,$={},X){if(H0($))return this.list(W,{},$);return this._client.getAPIList(`/chat/completions/${W}/messages`,HJ,{query:$,...X})}}class a2 extends f{constructor(){super(...arguments);this.messages=new V4(this._client)}create(W,$){return this._client.post("/chat/completions",{body:W,...$,stream:W.stream??!1})}retrieve(W,$){return this._client.get(`/chat/completions/${W}`,$)}update(W,$,X){return this._client.post(`/chat/completions/${W}`,{body:$,...X})}list(W={},$){if(H0(W))return this.list({},W);return this._client.getAPIList("/chat/completions",s2,{query:W,...$})}del(W,$){return this._client.delete(`/chat/completions/${W}`,$)}}class s2 extends L0{}class HJ extends L0{}a2.ChatCompletionsPage=s2;a2.Messages=V4;class B2 extends f{constructor(){super(...arguments);this.completions=new a2(this._client)}}B2.Completions=a2;B2.ChatCompletionsPage=s2;class O4 extends f{create(W,$){return this._client.post("/audio/speech",{body:W,...$,headers:{Accept:"application/octet-stream",...$?.headers},__binaryResponse:!0})}}class K4 extends f{create(W,$){return this._client.post("/audio/transcriptions",YW({body:W,...$,stream:W.stream??!1,__metadata:{model:W.model}}))}}class L4 extends f{create(W,$){return this._client.post("/audio/translations",YW({body:W,...$,__metadata:{model:W.model}}))}}class aW extends f{constructor(){super(...arguments);this.transcriptions=new K4(this._client),this.translations=new L4(this._client),this.speech=new O4(this._client)}}aW.Transcriptions=K4;aW.Translations=L4;aW.Speech=O4;class e2 extends f{create(W,$){return this._client.post("/batches",{body:W,...$})}retrieve(W,$){return this._client.get(`/batches/${W}`,$)}list(W={},$){if(H0(W))return this.list({},W);return this._client.getAPIList("/batches",p8,{query:W,...$})}cancel(W,$){return this._client.post(`/batches/${W}/cancel`,$)}}class p8 extends L0{}e2.BatchesPage=p8;var KW=function(W,$,X,Y,J){if(Y==="m")throw new TypeError("Private method is not writable");if(Y==="a"&&!J)throw new TypeError("Private accessor was defined without a setter");if(typeof $==="function"?W!==$||!J:!$.has(W))throw new TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?J.call(W,X):J?J.value=X:$.set(W,X),X},u0=function(W,$,X,Y){if(X==="a"&&!Y)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?W!==$||!Y:!$.has(W))throw new TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call(W):Y?Y.value:$.get(W)},QJ,vX,bX,A4,E4,yX,N4,sW,B4,hX,gX,u8,a3;class W8{constructor(){QJ.add(this),this.controller=new AbortController,vX.set(this,void 0),bX.set(this,()=>{}),A4.set(this,()=>{}),E4.set(this,void 0),yX.set(this,()=>{}),N4.set(this,()=>{}),sW.set(this,{}),B4.set(this,!1),hX.set(this,!1),gX.set(this,!1),u8.set(this,!1),KW(this,vX,new Promise((W,$)=>{KW(this,bX,W,"f"),KW(this,A4,$,"f")}),"f"),KW(this,E4,new Promise((W,$)=>{KW(this,yX,W,"f"),KW(this,N4,$,"f")}),"f"),u0(this,vX,"f").catch(()=>{}),u0(this,E4,"f").catch(()=>{})}_run(W){setTimeout(()=>{W().then(()=>{this._emitFinal(),this._emit("end")},u0(this,QJ,"m",a3).bind(this))},0)}_connected(){if(this.ended)return;u0(this,bX,"f").call(this),this._emit("connect")}get ended(){return u0(this,B4,"f")}get errored(){return u0(this,hX,"f")}get aborted(){return u0(this,gX,"f")}abort(){this.controller.abort()}on(W,$){return(u0(this,sW,"f")[W]||(u0(this,sW,"f")[W]=[])).push({listener:$}),this}off(W,$){let X=u0(this,sW,"f")[W];if(!X)return this;let Y=X.findIndex((J)=>J.listener===$);if(Y>=0)X.splice(Y,1);return this}once(W,$){return(u0(this,sW,"f")[W]||(u0(this,sW,"f")[W]=[])).push({listener:$,once:!0}),this}emitted(W){return new Promise(($,X)=>{if(KW(this,u8,!0,"f"),W!=="error")this.once("error",X);this.once(W,$)})}async done(){KW(this,u8,!0,"f"),await u0(this,E4,"f")}_emit(W,...$){if(u0(this,B4,"f"))return;if(W==="end")KW(this,B4,!0,"f"),u0(this,yX,"f").call(this);let X=u0(this,sW,"f")[W];if(X)u0(this,sW,"f")[W]=X.filter((Y)=>!Y.once),X.forEach(({listener:Y})=>Y(...$));if(W==="abort"){let Y=$[0];if(!u0(this,u8,"f")&&!X?.length)Promise.reject(Y);u0(this,A4,"f").call(this,Y),u0(this,N4,"f").call(this,Y),this._emit("end");return}if(W==="error"){let Y=$[0];if(!u0(this,u8,"f")&&!X?.length)Promise.reject(Y);u0(this,A4,"f").call(this,Y),u0(this,N4,"f").call(this,Y),this._emit("end")}}_emitFinal(){}}vX=new WeakMap,bX=new WeakMap,A4=new WeakMap,E4=new WeakMap,yX=new WeakMap,N4=new WeakMap,sW=new WeakMap,B4=new WeakMap,hX=new WeakMap,gX=new WeakMap,u8=new WeakMap,QJ=new WeakSet,a3=function W($){if(KW(this,hX,!0,"f"),$ instanceof Error&&$.name==="AbortError")$=new X1;if($ instanceof X1)return KW(this,gX,!0,"f"),this._emit("abort",$);if($ instanceof o)return this._emit("error",$);if($ instanceof Error){let X=new o($.message);return X.cause=$,this._emit("error",X)}return this._emit("error",new o(String($)))};var i=function(W,$,X,Y){if(X==="a"&&!Y)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?W!==$||!Y:!$.has(W))throw new TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call(W):Y?Y.value:$.get(W)},n1=function(W,$,X,Y,J){if(Y==="m")throw new TypeError("Private method is not writable");if(Y==="a"&&!J)throw new TypeError("Private accessor was defined without a setter");if(typeof $==="function"?W!==$||!J:!$.has(W))throw new TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?J.call(W,X):J?J.value=X:$.set(W,X),X},M1,zJ,bW,mX,LW,X8,c8,$8,cX,r1,pX,uX,S4,R4,Z4,s3,e3,WH,$H,XH,YH,JH;class t1 extends W8{constructor(){super(...arguments);M1.add(this),zJ.set(this,[]),bW.set(this,{}),mX.set(this,{}),LW.set(this,void 0),X8.set(this,void 0),c8.set(this,void 0),$8.set(this,void 0),cX.set(this,void 0),r1.set(this,void 0),pX.set(this,void 0),uX.set(this,void 0),S4.set(this,void 0)}[(zJ=new WeakMap,bW=new WeakMap,mX=new WeakMap,LW=new WeakMap,X8=new WeakMap,c8=new WeakMap,$8=new WeakMap,cX=new WeakMap,r1=new WeakMap,pX=new WeakMap,uX=new WeakMap,S4=new WeakMap,M1=new WeakSet,Symbol.asyncIterator)](){let W=[],$=[],X=!1;return this.on("event",(Y)=>{let J=$.shift();if(J)J.resolve(Y);else W.push(Y)}),this.on("end",()=>{X=!0;for(let Y of $)Y.resolve(void 0);$.length=0}),this.on("abort",(Y)=>{X=!0;for(let J of $)J.reject(Y);$.length=0}),this.on("error",(Y)=>{X=!0;for(let J of $)J.reject(Y);$.length=0}),{next:async()=>{if(!W.length){if(X)return{value:void 0,done:!0};return new Promise((J,G)=>$.push({resolve:J,reject:G})).then((J)=>J?{value:J,done:!1}:{value:void 0,done:!0})}return{value:W.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}static fromReadableStream(W){let $=new t1;return $._run(()=>$._fromReadableStream(W)),$}async _fromReadableStream(W,$){let X=$?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}this._connected();let Y=i1.fromReadableStream(W,this.controller);for await(let J of Y)i(this,M1,"m",R4).call(this,J);if(Y.controller.signal?.aborted)throw new X1;return this._addRun(i(this,M1,"m",Z4).call(this))}toReadableStream(){return new i1(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(W,$,X,Y,J){let G=new t1;return G._run(()=>G._runToolAssistantStream(W,$,X,Y,{...J,headers:{...J?.headers,"X-Stainless-Helper-Method":"stream"}})),G}async _createToolAssistantStream(W,$,X,Y,J){let G=J?.signal;if(G){if(G.aborted)this.controller.abort();G.addEventListener("abort",()=>this.controller.abort())}let H={...Y,stream:!0},Q=await W.submitToolOutputs($,X,H,{...J,signal:this.controller.signal});this._connected();for await(let z of Q)i(this,M1,"m",R4).call(this,z);if(Q.controller.signal?.aborted)throw new X1;return this._addRun(i(this,M1,"m",Z4).call(this))}static createThreadAssistantStream(W,$,X){let Y=new t1;return Y._run(()=>Y._threadAssistantStream(W,$,{...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"stream"}})),Y}static createAssistantStream(W,$,X,Y){let J=new t1;return J._run(()=>J._runAssistantStream(W,$,X,{...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"stream"}})),J}currentEvent(){return i(this,pX,"f")}currentRun(){return i(this,uX,"f")}currentMessageSnapshot(){return i(this,LW,"f")}currentRunStepSnapshot(){return i(this,S4,"f")}async finalRunSteps(){return await this.done(),Object.values(i(this,bW,"f"))}async finalMessages(){return await this.done(),Object.values(i(this,mX,"f"))}async finalRun(){if(await this.done(),!i(this,X8,"f"))throw Error("Final run was not received.");return i(this,X8,"f")}async _createThreadAssistantStream(W,$,X){let Y=X?.signal;if(Y){if(Y.aborted)this.controller.abort();Y.addEventListener("abort",()=>this.controller.abort())}let J={...$,stream:!0},G=await W.createAndRun(J,{...X,signal:this.controller.signal});this._connected();for await(let H of G)i(this,M1,"m",R4).call(this,H);if(G.controller.signal?.aborted)throw new X1;return this._addRun(i(this,M1,"m",Z4).call(this))}async _createAssistantStream(W,$,X,Y){let J=Y?.signal;if(J){if(J.aborted)this.controller.abort();J.addEventListener("abort",()=>this.controller.abort())}let G={...X,stream:!0},H=await W.create($,G,{...Y,signal:this.controller.signal});this._connected();for await(let Q of H)i(this,M1,"m",R4).call(this,Q);if(H.controller.signal?.aborted)throw new X1;return this._addRun(i(this,M1,"m",Z4).call(this))}static accumulateDelta(W,$){for(let[X,Y]of Object.entries($)){if(!W.hasOwnProperty(X)){W[X]=Y;continue}let J=W[X];if(J===null||J===void 0){W[X]=Y;continue}if(X==="index"||X==="type"){W[X]=Y;continue}if(typeof J==="string"&&typeof Y==="string")J+=Y;else if(typeof J==="number"&&typeof Y==="number")J+=Y;else if(D4(J)&&D4(Y))J=this.accumulateDelta(J,Y);else if(Array.isArray(J)&&Array.isArray(Y)){if(J.every((G)=>typeof G==="string"||typeof G==="number")){J.push(...Y);continue}for(let G of Y){if(!D4(G))throw new Error(`Expected array delta entry to be an object but got: ${G}`);let H=G.index;if(H==null)throw console.error(G),new Error("Expected array delta entry to have an `index` property");if(typeof H!=="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${H}`);let Q=J[H];if(Q==null)J.push(G);else J[H]=this.accumulateDelta(Q,G)}continue}else throw Error(`Unhandled record type: ${X}, deltaValue: ${Y}, accValue: ${J}`);W[X]=J}return W}_addRun(W){return W}async _threadAssistantStream(W,$,X){return await this._createThreadAssistantStream($,W,X)}async _runAssistantStream(W,$,X,Y){return await this._createAssistantStream($,W,X,Y)}async _runToolAssistantStream(W,$,X,Y,J){return await this._createToolAssistantStream(X,W,$,Y,J)}}R4=function W($){if(this.ended)return;switch(n1(this,pX,$,"f"),i(this,M1,"m",WH).call(this,$),$.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.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":i(this,M1,"m",JH).call(this,$);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":i(this,M1,"m",e3).call(this,$);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":i(this,M1,"m",s3).call(this,$);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:aD($)}},Z4=function W(){if(this.ended)throw new o("stream has ended, this shouldn't happen");if(!i(this,X8,"f"))throw Error("Final run has not been received");return i(this,X8,"f")},s3=function W($){let[X,Y]=i(this,M1,"m",XH).call(this,$,i(this,LW,"f"));n1(this,LW,X,"f"),i(this,mX,"f")[X.id]=X;for(let J of Y){let G=X.content[J.index];if(G?.type=="text")this._emit("textCreated",G.text)}switch($.event){case"thread.message.created":this._emit("messageCreated",$.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",$.data.delta,X),$.data.delta.content)for(let J of $.data.delta.content){if(J.type=="text"&&J.text){let G=J.text,H=X.content[J.index];if(H&&H.type=="text")this._emit("textDelta",G,H.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(J.index!=i(this,c8,"f")){if(i(this,$8,"f"))switch(i(this,$8,"f").type){case"text":this._emit("textDone",i(this,$8,"f").text,i(this,LW,"f"));break;case"image_file":this._emit("imageFileDone",i(this,$8,"f").image_file,i(this,LW,"f"));break}n1(this,c8,J.index,"f")}n1(this,$8,X.content[J.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(i(this,c8,"f")!==void 0){let J=$.data.content[i(this,c8,"f")];if(J)switch(J.type){case"image_file":this._emit("imageFileDone",J.image_file,i(this,LW,"f"));break;case"text":this._emit("textDone",J.text,i(this,LW,"f"));break}}if(i(this,LW,"f"))this._emit("messageDone",$.data);n1(this,LW,void 0,"f")}},e3=function W($){let X=i(this,M1,"m",$H).call(this,$);switch(n1(this,S4,X,"f"),$.event){case"thread.run.step.created":this._emit("runStepCreated",$.data);break;case"thread.run.step.delta":let Y=$.data.delta;if(Y.step_details&&Y.step_details.type=="tool_calls"&&Y.step_details.tool_calls&&X.step_details.type=="tool_calls")for(let G of Y.step_details.tool_calls)if(G.index==i(this,cX,"f"))this._emit("toolCallDelta",G,X.step_details.tool_calls[G.index]);else{if(i(this,r1,"f"))this._emit("toolCallDone",i(this,r1,"f"));if(n1(this,cX,G.index,"f"),n1(this,r1,X.step_details.tool_calls[G.index],"f"),i(this,r1,"f"))this._emit("toolCallCreated",i(this,r1,"f"))}this._emit("runStepDelta",$.data.delta,X);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(n1(this,S4,void 0,"f"),$.data.step_details.type=="tool_calls"){if(i(this,r1,"f"))this._emit("toolCallDone",i(this,r1,"f")),n1(this,r1,void 0,"f")}this._emit("runStepDone",$.data,X);break;case"thread.run.step.in_progress":break}},WH=function W($){i(this,zJ,"f").push($),this._emit("event",$)},$H=function W($){switch($.event){case"thread.run.step.created":return i(this,bW,"f")[$.data.id]=$.data,$.data;case"thread.run.step.delta":let X=i(this,bW,"f")[$.data.id];if(!X)throw Error("Received a RunStepDelta before creation of a snapshot");let Y=$.data;if(Y.delta){let J=t1.accumulateDelta(X,Y.delta);i(this,bW,"f")[$.data.id]=J}return i(this,bW,"f")[$.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":i(this,bW,"f")[$.data.id]=$.data;break}if(i(this,bW,"f")[$.data.id])return i(this,bW,"f")[$.data.id];throw new Error("No snapshot available")},XH=function W($,X){let Y=[];switch($.event){case"thread.message.created":return[$.data,Y];case"thread.message.delta":if(!X)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let J=$.data;if(J.delta.content)for(let G of J.delta.content)if(G.index in X.content){let H=X.content[G.index];X.content[G.index]=i(this,M1,"m",YH).call(this,G,H)}else X.content[G.index]=G,Y.push(G);return[X,Y];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(X)return[X,Y];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},YH=function W($,X){return t1.accumulateDelta(X,$)},JH=function W($){switch(n1(this,uX,$.data,"f"),$.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(n1(this,X8,$.data,"f"),i(this,r1,"f"))this._emit("toolCallDone",i(this,r1,"f")),n1(this,r1,void 0,"f");break;case"thread.run.cancelling":break}};function aD(W){}class d8 extends f{create(W,$){return this._client.post("/assistants",{body:W,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}retrieve(W,$){return this._client.get(`/assistants/${W}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}update(W,$,X){return this._client.post(`/assistants/${W}`,{body:$,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}list(W={},$){if(H0(W))return this.list({},W);return this._client.getAPIList("/assistants",q4,{query:W,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}del(W,$){return this._client.delete(`/assistants/${W}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}}class q4 extends L0{}d8.AssistantsPage=q4;function FJ(W){return typeof W.parse==="function"}var R2=(W)=>{return W?.role==="assistant"},TJ=(W)=>{return W?.role==="function"},UJ=(W)=>{return W?.role==="tool"};function C4(W){return W?.$brand==="auto-parseable-response-format"}function Y8(W){return W?.$brand==="auto-parseable-tool"}function GH(W,$){if(!$||!wJ($))return{...W,choices:W.choices.map((X)=>({...X,message:{...X.message,parsed:null,...X.message.tool_calls?{tool_calls:X.message.tool_calls}:void 0}}))};return k4(W,$)}function k4(W,$){let X=W.choices.map((Y)=>{if(Y.finish_reason==="length")throw new U4;if(Y.finish_reason==="content_filter")throw new w4;return{...Y,message:{...Y.message,...Y.message.tool_calls?{tool_calls:Y.message.tool_calls?.map((J)=>WV($,J))??void 0}:void 0,parsed:Y.message.content&&!Y.message.refusal?eD($,Y.message.content):null}}});return{...W,choices:X}}function eD(W,$){if(W.response_format?.type!=="json_schema")return null;if(W.response_format?.type==="json_schema"){if("$parseRaw"in W.response_format)return W.response_format.$parseRaw($);return JSON.parse($)}return null}function WV(W,$){let X=W.tools?.find((Y)=>Y.function?.name===$.function.name);return{...$,function:{...$.function,parsed_arguments:Y8(X)?X.$parseRaw($.function.arguments):X?.function.strict?JSON.parse($.function.arguments):null}}}function HH(W,$){if(!W)return!1;let X=W.tools?.find((Y)=>Y.function?.name===$.function.name);return Y8(X)||X?.function.strict||!1}function wJ(W){if(C4(W.response_format))return!0;return W.tools?.some(($)=>Y8($)||$.type==="function"&&$.function.strict===!0)??!1}function QH(W){for(let $ of W??[]){if($.type!=="function")throw new o(`Currently only \`function\` tool types support auto-parsing; Received \`${$.type}\``);if($.function.strict!==!0)throw new o(`The \`${$.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var v1=function(W,$,X,Y){if(X==="a"&&!Y)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?W!==$||!Y:!$.has(W))throw new TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call(W):Y?Y.value:$.get(W)},A1,MJ,dX,_J,DJ,VJ,FH,OJ,zH=10;class I4 extends W8{constructor(){super(...arguments);A1.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(W){this._chatCompletions.push(W),this._emit("chatCompletion",W);let $=W.choices[0]?.message;if($)this._addMessage($);return W}_addMessage(W,$=!0){if(!("content"in W))W.content=null;if(this.messages.push(W),$){if(this._emit("message",W),(TJ(W)||UJ(W))&&W.content)this._emit("functionCallResult",W.content);else if(R2(W)&&W.function_call)this._emit("functionCall",W.function_call);else if(R2(W)&&W.tool_calls){for(let X of W.tool_calls)if(X.type==="function")this._emit("functionCall",X.function)}}}async finalChatCompletion(){await this.done();let W=this._chatCompletions[this._chatCompletions.length-1];if(!W)throw new o("stream ended without producing a ChatCompletion");return W}async finalContent(){return await this.done(),v1(this,A1,"m",MJ).call(this)}async finalMessage(){return await this.done(),v1(this,A1,"m",dX).call(this)}async finalFunctionCall(){return await this.done(),v1(this,A1,"m",_J).call(this)}async finalFunctionCallResult(){return await this.done(),v1(this,A1,"m",DJ).call(this)}async totalUsage(){return await this.done(),v1(this,A1,"m",VJ).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let W=this._chatCompletions[this._chatCompletions.length-1];if(W)this._emit("finalChatCompletion",W);let $=v1(this,A1,"m",dX).call(this);if($)this._emit("finalMessage",$);let X=v1(this,A1,"m",MJ).call(this);if(X)this._emit("finalContent",X);let Y=v1(this,A1,"m",_J).call(this);if(Y)this._emit("finalFunctionCall",Y);let J=v1(this,A1,"m",DJ).call(this);if(J!=null)this._emit("finalFunctionCallResult",J);if(this._chatCompletions.some((G)=>G.usage))this._emit("totalUsage",v1(this,A1,"m",VJ).call(this))}async _createChatCompletion(W,$,X){let Y=X?.signal;if(Y){if(Y.aborted)this.controller.abort();Y.addEventListener("abort",()=>this.controller.abort())}v1(this,A1,"m",FH).call(this,$);let J=await W.chat.completions.create({...$,stream:!1},{...X,signal:this.controller.signal});return this._connected(),this._addChatCompletion(k4(J,$))}async _runChatCompletion(W,$,X){for(let Y of $.messages)this._addMessage(Y,!1);return await this._createChatCompletion(W,$,X)}async _runFunctions(W,$,X){let{function_call:J="auto",stream:G,...H}=$,Q=typeof J!=="string"&&J?.name,{maxChatCompletions:z=zH}=X||{},F={};for(let U of $.functions)F[U.name||U.function.name]=U;let T=$.functions.map((U)=>({name:U.name||U.function.name,parameters:U.parameters,description:U.description}));for(let U of $.messages)this._addMessage(U,!1);for(let U=0;U<z;++U){let V=(await this._createChatCompletion(W,{...H,function_call:J,functions:T,messages:[...this.messages]},X)).choices[0]?.message;if(!V)throw new o("missing message in ChatCompletion response");if(!V.function_call)return;let{name:K,arguments:N}=V.function_call,I=F[K];if(!I){let m=`Invalid function_call: ${JSON.stringify(K)}. Available options are: ${T.map((c)=>JSON.stringify(c.name)).join(", ")}. Please try again`;this._addMessage({role:"function",name:K,content:m});continue}else if(Q&&Q!==K){let m=`Invalid function_call: ${JSON.stringify(K)}. ${JSON.stringify(Q)} requested. Please try again`;this._addMessage({role:"function",name:K,content:m});continue}let C;try{C=FJ(I)?await I.parse(N):N}catch(m){this._addMessage({role:"function",name:K,content:m instanceof Error?m.message:String(m)});continue}let B=await I.function(C,this),q=v1(this,A1,"m",OJ).call(this,B);if(this._addMessage({role:"function",name:K,content:q}),Q)return}}async _runTools(W,$,X){let{tool_choice:J="auto",stream:G,...H}=$,Q=typeof J!=="string"&&J?.function?.name,{maxChatCompletions:z=zH}=X||{},F=$.tools.map((M)=>{if(Y8(M)){if(!M.$callback)throw new o("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:M.$callback,name:M.function.name,description:M.function.description||"",parameters:M.function.parameters,parse:M.$parseRaw,strict:!0}}}return M}),T={};for(let M of F)if(M.type==="function")T[M.function.name||M.function.function.name]=M.function;let U="tools"in $?F.map((M)=>M.type==="function"?{type:"function",function:{name:M.function.name||M.function.function.name,parameters:M.function.parameters,description:M.function.description,strict:M.function.strict}}:M):void 0;for(let M of $.messages)this._addMessage(M,!1);for(let M=0;M<z;++M){let K=(await this._createChatCompletion(W,{...H,tool_choice:J,tools:U,messages:[...this.messages]},X)).choices[0]?.message;if(!K)throw new o("missing message in ChatCompletion response");if(!K.tool_calls?.length)return;for(let N of K.tool_calls){if(N.type!=="function")continue;let I=N.id,{name:C,arguments:B}=N.function,q=T[C];if(!q){let h=`Invalid tool_call: ${JSON.stringify(C)}. Available options are: ${Object.keys(T).map((U0)=>JSON.stringify(U0)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:I,content:h});continue}else if(Q&&Q!==C){let h=`Invalid tool_call: ${JSON.stringify(C)}. ${JSON.stringify(Q)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:I,content:h});continue}let m;try{m=FJ(q)?await q.parse(B):B}catch(h){let U0=h instanceof Error?h.message:String(h);this._addMessage({role:"tool",tool_call_id:I,content:U0});continue}let c=await q.function(m,this),v=v1(this,A1,"m",OJ).call(this,c);if(this._addMessage({role:"tool",tool_call_id:I,content:v}),Q)return}}return}}A1=new WeakSet,MJ=function W(){return v1(this,A1,"m",dX).call(this).content??null},dX=function W(){let $=this.messages.length;while($-- >0){let X=this.messages[$];if(R2(X)){let{function_call:Y,...J}=X,G={...J,content:X.content??null,refusal:X.refusal??null};if(Y)G.function_call=Y;return G}}throw new o("stream ended without producing a ChatCompletionMessage with role=assistant")},_J=function W(){for(let $=this.messages.length-1;$>=0;$--){let X=this.messages[$];if(R2(X)&&X?.function_call)return X.function_call;if(R2(X)&&X?.tool_calls?.length)return X.tool_calls.at(-1)?.function}return},DJ=function W(){for(let $=this.messages.length-1;$>=0;$--){let X=this.messages[$];if(TJ(X)&&X.content!=null)return X.content;if(UJ(X)&&X.content!=null&&typeof X.content==="string"&&this.messages.some((Y)=>Y.role==="assistant"&&Y.tool_calls?.some((J)=>J.type==="function"&&J.id===X.tool_call_id)))return X.content}return},VJ=function W(){let $={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:X}of this._chatCompletions)if(X)$.completion_tokens+=X.completion_tokens,$.prompt_tokens+=X.prompt_tokens,$.total_tokens+=X.total_tokens;return $},FH=function W($){if($.n!=null&&$.n>1)throw new o("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},OJ=function W($){return typeof $==="string"?$:$===void 0?"undefined":JSON.stringify($)};class l8 extends I4{static runFunctions(W,$,X){let Y=new l8,J={...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return Y._run(()=>Y._runFunctions(W,$,J)),Y}static runTools(W,$,X){let Y=new l8,J={...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"runTools"}};return Y._run(()=>Y._runTools(W,$,J)),Y}_addMessage(W,$=!0){if(super._addMessage(W,$),R2(W)&&W.content)this._emit("content",W.content)}}var T1={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 TH extends Error{}class UH extends Error{}function $V(W,$=T1.ALL){if(typeof W!=="string")throw new TypeError(`expecting str, got ${typeof W}`);if(!W.trim())throw new Error(`${W} is empty`);return XV(W.trim(),$)}var XV=(W,$)=>{let X=W.length,Y=0,J=(M)=>{throw new TH(`${M} at position ${Y}`)},G=(M)=>{throw new UH(`${M} at position ${Y}`)},H=()=>{if(U(),Y>=X)J("Unexpected end of input");if(W[Y]==='"')return Q();if(W[Y]==="{")return z();if(W[Y]==="[")return F();if(W.substring(Y,Y+4)==="null"||T1.NULL&$&&X-Y<4&&"null".startsWith(W.substring(Y)))return Y+=4,null;if(W.substring(Y,Y+4)==="true"||T1.BOOL&$&&X-Y<4&&"true".startsWith(W.substring(Y)))return Y+=4,!0;if(W.substring(Y,Y+5)==="false"||T1.BOOL&$&&X-Y<5&&"false".startsWith(W.substring(Y)))return Y+=5,!1;if(W.substring(Y,Y+8)==="Infinity"||T1.INFINITY&$&&X-Y<8&&"Infinity".startsWith(W.substring(Y)))return Y+=8,1/0;if(W.substring(Y,Y+9)==="-Infinity"||T1.MINUS_INFINITY&$&&1<X-Y&&X-Y<9&&"-Infinity".startsWith(W.substring(Y)))return Y+=9,-1/0;if(W.substring(Y,Y+3)==="NaN"||T1.NAN&$&&X-Y<3&&"NaN".startsWith(W.substring(Y)))return Y+=3,NaN;return T()},Q=()=>{let M=Y,V=!1;Y++;while(Y<X&&(W[Y]!=='"'||V&&W[Y-1]==="\\"))V=W[Y]==="\\"?!V:!1,Y++;if(W.charAt(Y)=='"')try{return JSON.parse(W.substring(M,++Y-Number(V)))}catch(K){G(String(K))}else if(T1.STR&$)try{return JSON.parse(W.substring(M,Y-Number(V))+'"')}catch(K){return JSON.parse(W.substring(M,W.lastIndexOf("\\"))+'"')}J("Unterminated string literal")},z=()=>{Y++,U();let M={};try{while(W[Y]!=="}"){if(U(),Y>=X&&T1.OBJ&$)return M;let V=Q();U(),Y++;try{let K=H();Object.defineProperty(M,V,{value:K,writable:!0,enumerable:!0,configurable:!0})}catch(K){if(T1.OBJ&$)return M;else throw K}if(U(),W[Y]===",")Y++}}catch(V){if(T1.OBJ&$)return M;else J("Expected '}' at end of object")}return Y++,M},F=()=>{Y++;let M=[];try{while(W[Y]!=="]")if(M.push(H()),U(),W[Y]===",")Y++}catch(V){if(T1.ARR&$)return M;J("Expected ']' at end of array")}return Y++,M},T=()=>{if(Y===0){if(W==="-"&&T1.NUM&$)J("Not sure what '-' is");try{return JSON.parse(W)}catch(V){if(T1.NUM&$)try{if(W[W.length-1]===".")return JSON.parse(W.substring(0,W.lastIndexOf(".")));return JSON.parse(W.substring(0,W.lastIndexOf("e")))}catch(K){}G(String(V))}}let M=Y;if(W[Y]==="-")Y++;while(W[Y]&&!",]}".includes(W[Y]))Y++;if(Y==X&&!(T1.NUM&$))J("Unterminated number literal");try{return JSON.parse(W.substring(M,Y))}catch(V){if(W.substring(M,Y)==="-"&&T1.NUM&$)J("Not sure what '-' is");try{return JSON.parse(W.substring(M,W.lastIndexOf("e")))}catch(K){G(String(K))}}},U=()=>{while(Y<X&&`
19
+ \r `.includes(W[Y]))Y++};return H()},KJ=(W)=>$V(W,T1.ALL^T1.NUM);var o8=function(W,$,X,Y,J){if(Y==="m")throw new TypeError("Private method is not writable");if(Y==="a"&&!J)throw new TypeError("Private accessor was defined without a setter");if(typeof $==="function"?W!==$||!J:!$.has(W))throw new TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?J.call(W,X):J?J.value=X:$.set(W,X),X},B0=function(W,$,X,Y){if(X==="a"&&!Y)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?W!==$||!Y:!$.has(W))throw new TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call(W):Y?Y.value:$.get(W)},Y1,eW,i8,Z2,LJ,lX,AJ,EJ,NJ,oX,BJ,wH;class J8 extends I4{constructor(W){super();Y1.add(this),eW.set(this,void 0),i8.set(this,void 0),Z2.set(this,void 0),o8(this,eW,W,"f"),o8(this,i8,[],"f")}get currentChatCompletionSnapshot(){return B0(this,Z2,"f")}static fromReadableStream(W){let $=new J8(null);return $._run(()=>$._fromReadableStream(W)),$}static createChatCompletion(W,$,X){let Y=new J8($);return Y._run(()=>Y._runChatCompletion(W,{...$,stream:!0},{...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"stream"}})),Y}async _createChatCompletion(W,$,X){super._createChatCompletion;let Y=X?.signal;if(Y){if(Y.aborted)this.controller.abort();Y.addEventListener("abort",()=>this.controller.abort())}B0(this,Y1,"m",LJ).call(this);let J=await W.chat.completions.create({...$,stream:!0},{...X,signal:this.controller.signal});this._connected();for await(let G of J)B0(this,Y1,"m",AJ).call(this,G);if(J.controller.signal?.aborted)throw new X1;return this._addChatCompletion(B0(this,Y1,"m",oX).call(this))}async _fromReadableStream(W,$){let X=$?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}B0(this,Y1,"m",LJ).call(this),this._connected();let Y=i1.fromReadableStream(W,this.controller),J;for await(let G of Y){if(J&&J!==G.id)this._addChatCompletion(B0(this,Y1,"m",oX).call(this));B0(this,Y1,"m",AJ).call(this,G),J=G.id}if(Y.controller.signal?.aborted)throw new X1;return this._addChatCompletion(B0(this,Y1,"m",oX).call(this))}[(eW=new WeakMap,i8=new WeakMap,Z2=new WeakMap,Y1=new WeakSet,LJ=function W(){if(this.ended)return;o8(this,Z2,void 0,"f")},lX=function W($){let X=B0(this,i8,"f")[$.index];if(X)return X;return X={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},B0(this,i8,"f")[$.index]=X,X},AJ=function W($){if(this.ended)return;let X=B0(this,Y1,"m",wH).call(this,$);this._emit("chunk",$,X);for(let Y of $.choices){let J=X.choices[Y.index];if(Y.delta.content!=null&&J.message?.role==="assistant"&&J.message?.content)this._emit("content",Y.delta.content,J.message.content),this._emit("content.delta",{delta:Y.delta.content,snapshot:J.message.content,parsed:J.message.parsed});if(Y.delta.refusal!=null&&J.message?.role==="assistant"&&J.message?.refusal)this._emit("refusal.delta",{delta:Y.delta.refusal,snapshot:J.message.refusal});if(Y.logprobs?.content!=null&&J.message?.role==="assistant")this._emit("logprobs.content.delta",{content:Y.logprobs?.content,snapshot:J.logprobs?.content??[]});if(Y.logprobs?.refusal!=null&&J.message?.role==="assistant")this._emit("logprobs.refusal.delta",{refusal:Y.logprobs?.refusal,snapshot:J.logprobs?.refusal??[]});let G=B0(this,Y1,"m",lX).call(this,J);if(J.finish_reason){if(B0(this,Y1,"m",NJ).call(this,J),G.current_tool_call_index!=null)B0(this,Y1,"m",EJ).call(this,J,G.current_tool_call_index)}for(let H of Y.delta.tool_calls??[]){if(G.current_tool_call_index!==H.index){if(B0(this,Y1,"m",NJ).call(this,J),G.current_tool_call_index!=null)B0(this,Y1,"m",EJ).call(this,J,G.current_tool_call_index)}G.current_tool_call_index=H.index}for(let H of Y.delta.tool_calls??[]){let Q=J.message.tool_calls?.[H.index];if(!Q?.type)continue;if(Q?.type==="function")this._emit("tool_calls.function.arguments.delta",{name:Q.function?.name,index:H.index,arguments:Q.function.arguments,parsed_arguments:Q.function.parsed_arguments,arguments_delta:H.function?.arguments??""});else _H(Q?.type)}}},EJ=function W($,X){if(B0(this,Y1,"m",lX).call(this,$).done_tool_calls.has(X))return;let J=$.message.tool_calls?.[X];if(!J)throw new Error("no tool call snapshot");if(!J.type)throw new Error("tool call snapshot missing `type`");if(J.type==="function"){let G=B0(this,eW,"f")?.tools?.find((H)=>H.type==="function"&&H.function.name===J.function.name);this._emit("tool_calls.function.arguments.done",{name:J.function.name,index:X,arguments:J.function.arguments,parsed_arguments:Y8(G)?G.$parseRaw(J.function.arguments):G?.function.strict?JSON.parse(J.function.arguments):null})}else _H(J.type)},NJ=function W($){let X=B0(this,Y1,"m",lX).call(this,$);if($.message.content&&!X.content_done){X.content_done=!0;let Y=B0(this,Y1,"m",BJ).call(this);this._emit("content.done",{content:$.message.content,parsed:Y?Y.$parseRaw($.message.content):null})}if($.message.refusal&&!X.refusal_done)X.refusal_done=!0,this._emit("refusal.done",{refusal:$.message.refusal});if($.logprobs?.content&&!X.logprobs_content_done)X.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:$.logprobs.content});if($.logprobs?.refusal&&!X.logprobs_refusal_done)X.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:$.logprobs.refusal})},oX=function W(){if(this.ended)throw new o("stream has ended, this shouldn't happen");let $=B0(this,Z2,"f");if(!$)throw new o("request ended without sending any chunks");return o8(this,Z2,void 0,"f"),o8(this,i8,[],"f"),YV($,B0(this,eW,"f"))},BJ=function W(){let $=B0(this,eW,"f")?.response_format;if(C4($))return $;return null},wH=function W($){var X,Y,J,G;let H=B0(this,Z2,"f"),{choices:Q,...z}=$;if(!H)H=o8(this,Z2,{...z,choices:[]},"f");else Object.assign(H,z);for(let{delta:F,finish_reason:T,index:U,logprobs:M=null,...V}of $.choices){let K=H.choices[U];if(!K)K=H.choices[U]={finish_reason:T,index:U,message:{},logprobs:M,...V};if(M)if(!K.logprobs)K.logprobs=Object.assign({},M);else{let{content:c,refusal:v,...h}=M;if(MH(h),Object.assign(K.logprobs,h),c)(X=K.logprobs).content??(X.content=[]),K.logprobs.content.push(...c);if(v)(Y=K.logprobs).refusal??(Y.refusal=[]),K.logprobs.refusal.push(...v)}if(T){if(K.finish_reason=T,B0(this,eW,"f")&&wJ(B0(this,eW,"f"))){if(T==="length")throw new U4;if(T==="content_filter")throw new w4}}if(Object.assign(K,V),!F)continue;let{content:N,refusal:I,function_call:C,role:B,tool_calls:q,...m}=F;if(MH(m),Object.assign(K.message,m),I)K.message.refusal=(K.message.refusal||"")+I;if(B)K.message.role=B;if(C)if(!K.message.function_call)K.message.function_call=C;else{if(C.name)K.message.function_call.name=C.name;if(C.arguments)(J=K.message.function_call).arguments??(J.arguments=""),K.message.function_call.arguments+=C.arguments}if(N){if(K.message.content=(K.message.content||"")+N,!K.message.refusal&&B0(this,Y1,"m",BJ).call(this))K.message.parsed=KJ(K.message.content)}if(q){if(!K.message.tool_calls)K.message.tool_calls=[];for(let{index:c,id:v,type:h,function:U0,...m0}of q){let E=(G=K.message.tool_calls)[c]??(G[c]={});if(Object.assign(E,m0),v)E.id=v;if(h)E.type=h;if(U0)E.function??(E.function={name:U0.name??"",arguments:""});if(U0?.name)E.function.name=U0.name;if(U0?.arguments){if(E.function.arguments+=U0.arguments,HH(B0(this,eW,"f"),E))E.function.parsed_arguments=KJ(E.function.arguments)}}}}return H},Symbol.asyncIterator)](){let W=[],$=[],X=!1;return this.on("chunk",(Y)=>{let J=$.shift();if(J)J.resolve(Y);else W.push(Y)}),this.on("end",()=>{X=!0;for(let Y of $)Y.resolve(void 0);$.length=0}),this.on("abort",(Y)=>{X=!0;for(let J of $)J.reject(Y);$.length=0}),this.on("error",(Y)=>{X=!0;for(let J of $)J.reject(Y);$.length=0}),{next:async()=>{if(!W.length){if(X)return{value:void 0,done:!0};return new Promise((J,G)=>$.push({resolve:J,reject:G})).then((J)=>J?{value:J,done:!1}:{value:void 0,done:!0})}return{value:W.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new i1(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function YV(W,$){let{id:X,choices:Y,created:J,model:G,system_fingerprint:H,...Q}=W,z={...Q,id:X,choices:Y.map(({message:F,finish_reason:T,index:U,logprobs:M,...V})=>{if(!T)throw new o(`missing finish_reason for choice ${U}`);let{content:K=null,function_call:N,tool_calls:I,...C}=F,B=F.role;if(!B)throw new o(`missing role for choice ${U}`);if(N){let{arguments:q,name:m}=N;if(q==null)throw new o(`missing function_call.arguments for choice ${U}`);if(!m)throw new o(`missing function_call.name for choice ${U}`);return{...V,message:{content:K,function_call:{arguments:q,name:m},role:B,refusal:F.refusal??null},finish_reason:T,index:U,logprobs:M}}if(I)return{...V,index:U,finish_reason:T,logprobs:M,message:{...C,role:B,content:K,refusal:F.refusal??null,tool_calls:I.map((q,m)=>{let{function:c,type:v,id:h,...U0}=q,{arguments:m0,name:E,..._0}=c||{};if(h==null)throw new o(`missing choices[${U}].tool_calls[${m}].id
20
+ ${iX(W)}`);if(v==null)throw new o(`missing choices[${U}].tool_calls[${m}].type
21
+ ${iX(W)}`);if(E==null)throw new o(`missing choices[${U}].tool_calls[${m}].function.name
22
+ ${iX(W)}`);if(m0==null)throw new o(`missing choices[${U}].tool_calls[${m}].function.arguments
23
+ ${iX(W)}`);return{...U0,id:h,type:v,function:{..._0,name:E,arguments:m0}}})}};return{...V,message:{...C,content:K,role:B,refusal:F.refusal??null},finish_reason:T,index:U,logprobs:M}}),created:J,model:G,object:"chat.completion",...H?{system_fingerprint:H}:{}};return GH(z,$)}function iX(W){return JSON.stringify(W)}function MH(W){return}function _H(W){}class G8 extends J8{static fromReadableStream(W){let $=new G8(null);return $._run(()=>$._fromReadableStream(W)),$}static runFunctions(W,$,X){let Y=new G8(null),J={...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return Y._run(()=>Y._runFunctions(W,$,J)),Y}static runTools(W,$,X){let Y=new G8($),J={...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"runTools"}};return Y._run(()=>Y._runTools(W,$,J)),Y}}class nX extends f{parse(W,$){return QH(W.tools),this._client.chat.completions.create(W,{...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap((X)=>k4(X,W))}runFunctions(W,$){if(W.stream)return G8.runFunctions(this._client,W,$);return l8.runFunctions(this._client,W,$)}runTools(W,$){if(W.stream)return G8.runTools(this._client,W,$);return l8.runTools(this._client,W,$)}stream(W,$){return J8.createChatCompletion(this._client,W,$)}}class j4 extends f{constructor(){super(...arguments);this.completions=new nX(this._client)}}(function(W){W.Completions=nX})(j4||(j4={}));class f4 extends f{create(W,$){return this._client.post("/realtime/sessions",{body:W,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}}class P4 extends f{create(W,$){return this._client.post("/realtime/transcription_sessions",{body:W,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}}class H8 extends f{constructor(){super(...arguments);this.sessions=new f4(this._client),this.transcriptionSessions=new P4(this._client)}}H8.Sessions=f4;H8.TranscriptionSessions=P4;class n8 extends f{create(W,$,X){return this._client.post(`/threads/${W}/messages`,{body:$,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}retrieve(W,$,X){return this._client.get(`/threads/${W}/messages/${$}`,{...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}update(W,$,X,Y){return this._client.post(`/threads/${W}/messages/${$}`,{body:X,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}list(W,$={},X){if(H0($))return this.list(W,{},$);return this._client.getAPIList(`/threads/${W}/messages`,x4,{query:$,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}del(W,$,X){return this._client.delete(`/threads/${W}/messages/${$}`,{...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}}class x4 extends L0{}n8.MessagesPage=x4;class r8 extends f{retrieve(W,$,X,Y={},J){if(H0(Y))return this.retrieve(W,$,X,{},Y);return this._client.get(`/threads/${W}/runs/${$}/steps/${X}`,{query:Y,...J,headers:{"OpenAI-Beta":"assistants=v2",...J?.headers}})}list(W,$,X={},Y){if(H0(X))return this.list(W,$,{},X);return this._client.getAPIList(`/threads/${W}/runs/${$}/steps`,v4,{query:X,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}}class v4 extends L0{}r8.RunStepsPage=v4;class S2 extends f{constructor(){super(...arguments);this.steps=new r8(this._client)}create(W,$,X){let{include:Y,...J}=$;return this._client.post(`/threads/${W}/runs`,{query:{include:Y},body:J,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers},stream:$.stream??!1})}retrieve(W,$,X){return this._client.get(`/threads/${W}/runs/${$}`,{...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}update(W,$,X,Y){return this._client.post(`/threads/${W}/runs/${$}`,{body:X,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}list(W,$={},X){if(H0($))return this.list(W,{},$);return this._client.getAPIList(`/threads/${W}/runs`,b4,{query:$,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}cancel(W,$,X){return this._client.post(`/threads/${W}/runs/${$}/cancel`,{...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}async createAndPoll(W,$,X){let Y=await this.create(W,$,X);return await this.poll(W,Y.id,X)}createAndStream(W,$,X){return t1.createAssistantStream(W,this._client.beta.threads.runs,$,X)}async poll(W,$,X){let Y={...X?.headers,"X-Stainless-Poll-Helper":"true"};if(X?.pollIntervalMs)Y["X-Stainless-Custom-Poll-Interval"]=X.pollIntervalMs.toString();while(!0){let{data:J,response:G}=await this.retrieve(W,$,{...X,headers:{...X?.headers,...Y}}).withResponse();switch(J.status){case"queued":case"in_progress":case"cancelling":let H=5000;if(X?.pollIntervalMs)H=X.pollIntervalMs;else{let Q=G.headers.get("openai-poll-after-ms");if(Q){let z=parseInt(Q);if(!isNaN(z))H=z}}await rW(H);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return J}}}stream(W,$,X){return t1.createAssistantStream(W,this._client.beta.threads.runs,$,X)}submitToolOutputs(W,$,X,Y){return this._client.post(`/threads/${W}/runs/${$}/submit_tool_outputs`,{body:X,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers},stream:X.stream??!1})}async submitToolOutputsAndPoll(W,$,X,Y){let J=await this.submitToolOutputs(W,$,X,Y);return await this.poll(W,J.id,Y)}submitToolOutputsStream(W,$,X,Y){return t1.createToolAssistantStream(W,$,this._client.beta.threads.runs,X,Y)}}class b4 extends L0{}S2.RunsPage=b4;S2.Steps=r8;S2.RunStepsPage=v4;class W2 extends f{constructor(){super(...arguments);this.runs=new S2(this._client),this.messages=new n8(this._client)}create(W={},$){if(H0(W))return this.create({},W);return this._client.post("/threads",{body:W,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}retrieve(W,$){return this._client.get(`/threads/${W}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}update(W,$,X){return this._client.post(`/threads/${W}`,{body:$,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}del(W,$){return this._client.delete(`/threads/${W}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}createAndRun(W,$){return this._client.post("/threads/runs",{body:W,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers},stream:W.stream??!1})}async createAndRunPoll(W,$){let X=await this.createAndRun(W,$);return await this.runs.poll(X.thread_id,X.id,$)}createAndRunStream(W,$){return t1.createThreadAssistantStream(W,this._client.beta.threads,$)}}W2.Runs=S2;W2.RunsPage=b4;W2.Messages=n8;W2.MessagesPage=x4;class yW extends f{constructor(){super(...arguments);this.realtime=new H8(this._client),this.chat=new j4(this._client),this.assistants=new d8(this._client),this.threads=new W2(this._client)}}yW.Realtime=H8;yW.Assistants=d8;yW.AssistantsPage=q4;yW.Threads=W2;class t8 extends f{create(W,$){return this._client.post("/completions",{body:W,...$,stream:W.stream??!1})}}class a8 extends f{create(W,$){let X=!!W.encoding_format,Y=X?W.encoding_format:"base64";if(X)nW("Request","User defined encoding_format:",W.encoding_format);let J=this._client.post("/embeddings",{body:{...W,encoding_format:Y},...$});if(X)return J;return nW("response","Decoding base64 embeddings to float32 array"),J._thenUnwrap((G)=>{if(G&&G.data)G.data.forEach((H)=>{let Q=H.embedding;H.embedding=t3(Q)});return G})}}class s8 extends f{retrieve(W,$,X,Y){return this._client.get(`/evals/${W}/runs/${$}/output_items/${X}`,Y)}list(W,$,X={},Y){if(H0(X))return this.list(W,$,{},X);return this._client.getAPIList(`/evals/${W}/runs/${$}/output_items`,y4,{query:X,...Y})}}class y4 extends L0{}s8.OutputItemListResponsesPage=y4;class q2 extends f{constructor(){super(...arguments);this.outputItems=new s8(this._client)}create(W,$,X){return this._client.post(`/evals/${W}/runs`,{body:$,...X})}retrieve(W,$,X){return this._client.get(`/evals/${W}/runs/${$}`,X)}list(W,$={},X){if(H0($))return this.list(W,{},$);return this._client.getAPIList(`/evals/${W}/runs`,h4,{query:$,...X})}del(W,$,X){return this._client.delete(`/evals/${W}/runs/${$}`,X)}cancel(W,$,X){return this._client.post(`/evals/${W}/runs/${$}`,X)}}class h4 extends L0{}q2.RunListResponsesPage=h4;q2.OutputItems=s8;q2.OutputItemListResponsesPage=y4;class $2 extends f{constructor(){super(...arguments);this.runs=new q2(this._client)}create(W,$){return this._client.post("/evals",{body:W,...$})}retrieve(W,$){return this._client.get(`/evals/${W}`,$)}update(W,$,X){return this._client.post(`/evals/${W}`,{body:$,...X})}list(W={},$){if(H0(W))return this.list({},W);return this._client.getAPIList("/evals",e8,{query:W,...$})}del(W,$){return this._client.delete(`/evals/${W}`,$)}}class e8 extends L0{}$2.EvalListResponsesPage=e8;$2.Runs=q2;$2.RunListResponsesPage=h4;class Q8 extends f{create(W,$){return this._client.post("/files",YW({body:W,...$}))}retrieve(W,$){return this._client.get(`/files/${W}`,$)}list(W={},$){if(H0(W))return this.list({},W);return this._client.getAPIList("/files",W$,{query:W,...$})}del(W,$){return this._client.delete(`/files/${W}`,$)}content(W,$){return this._client.get(`/files/${W}/content`,{...$,headers:{Accept:"application/binary",...$?.headers},__binaryResponse:!0})}retrieveContent(W,$){return this._client.get(`/files/${W}/content`,$)}async waitForProcessing(W,{pollInterval:$=5000,maxWait:X=1800000}={}){let Y=new Set(["processed","error","deleted"]),J=Date.now(),G=await this.retrieve(W);while(!G.status||!Y.has(G.status))if(await rW($),G=await this.retrieve(W),Date.now()-J>X)throw new r2({message:`Giving up on waiting for file ${W} to finish processing after ${X} milliseconds.`});return G}}class W$ extends L0{}Q8.FileObjectsPage=W$;class $$ extends f{create(W,$,X){return this._client.getAPIList(`/fine_tuning/checkpoints/${W}/permissions`,g4,{body:$,method:"post",...X})}retrieve(W,$={},X){if(H0($))return this.retrieve(W,{},$);return this._client.get(`/fine_tuning/checkpoints/${W}/permissions`,{query:$,...X})}del(W,$,X){return this._client.delete(`/fine_tuning/checkpoints/${W}/permissions/${$}`,X)}}class g4 extends tW{}$$.PermissionCreateResponsesPage=g4;class z8 extends f{constructor(){super(...arguments);this.permissions=new $$(this._client)}}z8.Permissions=$$;z8.PermissionCreateResponsesPage=g4;class X$ extends f{list(W,$={},X){if(H0($))return this.list(W,{},$);return this._client.getAPIList(`/fine_tuning/jobs/${W}/checkpoints`,m4,{query:$,...X})}}class m4 extends L0{}X$.FineTuningJobCheckpointsPage=m4;class X2 extends f{constructor(){super(...arguments);this.checkpoints=new X$(this._client)}create(W,$){return this._client.post("/fine_tuning/jobs",{body:W,...$})}retrieve(W,$){return this._client.get(`/fine_tuning/jobs/${W}`,$)}list(W={},$){if(H0(W))return this.list({},W);return this._client.getAPIList("/fine_tuning/jobs",p4,{query:W,...$})}cancel(W,$){return this._client.post(`/fine_tuning/jobs/${W}/cancel`,$)}listEvents(W,$={},X){if(H0($))return this.listEvents(W,{},$);return this._client.getAPIList(`/fine_tuning/jobs/${W}/events`,u4,{query:$,...X})}}class p4 extends L0{}class u4 extends L0{}X2.FineTuningJobsPage=p4;X2.FineTuningJobEventsPage=u4;X2.Checkpoints=X$;X2.FineTuningJobCheckpointsPage=m4;class hW extends f{constructor(){super(...arguments);this.jobs=new X2(this._client),this.checkpoints=new z8(this._client)}}hW.Jobs=X2;hW.FineTuningJobsPage=p4;hW.FineTuningJobEventsPage=u4;hW.Checkpoints=z8;class Y$ extends f{createVariation(W,$){return this._client.post("/images/variations",YW({body:W,...$}))}edit(W,$){return this._client.post("/images/edits",YW({body:W,...$}))}generate(W,$){return this._client.post("/images/generations",{body:W,...$})}}class F8 extends f{retrieve(W,$){return this._client.get(`/models/${W}`,$)}list(W){return this._client.getAPIList("/models",J$,W)}del(W,$){return this._client.delete(`/models/${W}`,$)}}class J$ extends tW{}F8.ModelsPage=J$;class G$ extends f{create(W,$){return this._client.post("/moderations",{body:W,...$})}}function DH(W,$){if(!$||!AV($))return{...W,output_parsed:null,output:W.output.map((X)=>{if(X.type==="function_call")return{...X,parsed_arguments:null};if(X.type==="message")return{...X,content:X.content.map((Y)=>({...Y,parsed:null}))};else return X})};return RJ(W,$)}function RJ(W,$){let X=W.output.map((J)=>{if(J.type==="function_call")return{...J,parsed_arguments:BV($,J)};if(J.type==="message"){let G=J.content.map((H)=>{if(H.type==="output_text")return{...H,parsed:LV($,H.text)};return H});return{...J,content:G}}return J}),Y=Object.assign({},W,{output:X});if(!Object.getOwnPropertyDescriptor(W,"output_text"))ZJ(Y);return Object.defineProperty(Y,"output_parsed",{enumerable:!0,get(){for(let J of Y.output){if(J.type!=="message")continue;for(let G of J.content)if(G.type==="output_text"&&G.parsed!==null)return G.parsed}return null}}),Y}function LV(W,$){if(W.text?.format?.type!=="json_schema")return null;if("$parseRaw"in W.text?.format)return(W.text?.format).$parseRaw($);return JSON.parse($)}function AV(W){if(C4(W.text?.format))return!0;return!1}function EV(W){return W?.$brand==="auto-parseable-tool"}function NV(W,$){return W.find((X)=>X.type==="function"&&X.name===$)}function BV(W,$){let X=NV(W.tools??[],$.name);return{...$,...$,parsed_arguments:EV(X)?X.$parseRaw($.arguments):X?.strict?JSON.parse($.arguments):null}}function ZJ(W){let $=[];for(let X of W.output){if(X.type!=="message")continue;for(let Y of X.content)if(Y.type==="output_text")$.push(Y.text)}W.output_text=$.join("")}class c4 extends f{list(W,$={},X){if(H0($))return this.list(W,{},$);return this._client.getAPIList(`/responses/${W}/input_items`,SJ,{query:$,...X})}}var H$=function(W,$,X,Y,J){if(Y==="m")throw new TypeError("Private method is not writable");if(Y==="a"&&!J)throw new TypeError("Private accessor was defined without a setter");if(typeof $==="function"?W!==$||!J:!$.has(W))throw new TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?J.call(W,X):J?J.value=X:$.set(W,X),X},C2=function(W,$,X,Y){if(X==="a"&&!Y)throw new TypeError("Private accessor was defined without a getter");if(typeof $==="function"?W!==$||!Y:!$.has(W))throw new TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Y:X==="a"?Y.call(W):Y?Y.value:$.get(W)},Q$,rX,k2,tX,VH,OH,KH,LH;class aX extends W8{constructor(W){super();Q$.add(this),rX.set(this,void 0),k2.set(this,void 0),tX.set(this,void 0),H$(this,rX,W,"f")}static createResponse(W,$,X){let Y=new aX($);return Y._run(()=>Y._createResponse(W,$,{...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"stream"}})),Y}async _createResponse(W,$,X){let Y=X?.signal;if(Y){if(Y.aborted)this.controller.abort();Y.addEventListener("abort",()=>this.controller.abort())}C2(this,Q$,"m",VH).call(this);let J=await W.responses.create({...$,stream:!0},{...X,signal:this.controller.signal});this._connected();for await(let G of J)C2(this,Q$,"m",OH).call(this,G);if(J.controller.signal?.aborted)throw new X1;return C2(this,Q$,"m",KH).call(this)}[(rX=new WeakMap,k2=new WeakMap,tX=new WeakMap,Q$=new WeakSet,VH=function W(){if(this.ended)return;H$(this,k2,void 0,"f")},OH=function W($){if(this.ended)return;let X=C2(this,Q$,"m",LH).call(this,$);switch(this._emit("event",$),$.type){case"response.output_text.delta":{let Y=X.output[$.output_index];if(!Y)throw new o(`missing output at index ${$.output_index}`);if(Y.type==="message"){let J=Y.content[$.content_index];if(!J)throw new o(`missing content at index ${$.content_index}`);if(J.type!=="output_text")throw new o(`expected content to be 'output_text', got ${J.type}`);this._emit("response.output_text.delta",{...$,snapshot:J.text})}break}case"response.function_call_arguments.delta":{let Y=X.output[$.output_index];if(!Y)throw new o(`missing output at index ${$.output_index}`);if(Y.type==="function_call")this._emit("response.function_call_arguments.delta",{...$,snapshot:Y.arguments});break}default:this._emit($.type,$);break}},KH=function W(){if(this.ended)throw new o("stream has ended, this shouldn't happen");let $=C2(this,k2,"f");if(!$)throw new o("request ended without sending any events");H$(this,k2,void 0,"f");let X=ZV($,C2(this,rX,"f"));return H$(this,tX,X,"f"),X},LH=function W($){let X=C2(this,k2,"f");if(!X){if($.type!=="response.created")throw new o(`When snapshot hasn't been set yet, expected 'response.created' event, got ${$.type}`);return X=H$(this,k2,$.response,"f"),X}switch($.type){case"response.output_item.added":{X.output.push($.item);break}case"response.content_part.added":{let Y=X.output[$.output_index];if(!Y)throw new o(`missing output at index ${$.output_index}`);if(Y.type==="message")Y.content.push($.part);break}case"response.output_text.delta":{let Y=X.output[$.output_index];if(!Y)throw new o(`missing output at index ${$.output_index}`);if(Y.type==="message"){let J=Y.content[$.content_index];if(!J)throw new o(`missing content at index ${$.content_index}`);if(J.type!=="output_text")throw new o(`expected content to be 'output_text', got ${J.type}`);J.text+=$.delta}break}case"response.function_call_arguments.delta":{let Y=X.output[$.output_index];if(!Y)throw new o(`missing output at index ${$.output_index}`);if(Y.type==="function_call")Y.arguments+=$.delta;break}case"response.completed":{H$(this,k2,$.response,"f");break}}return X},Symbol.asyncIterator)](){let W=[],$=[],X=!1;return this.on("event",(Y)=>{let J=$.shift();if(J)J.resolve(Y);else W.push(Y)}),this.on("end",()=>{X=!0;for(let Y of $)Y.resolve(void 0);$.length=0}),this.on("abort",(Y)=>{X=!0;for(let J of $)J.reject(Y);$.length=0}),this.on("error",(Y)=>{X=!0;for(let J of $)J.reject(Y);$.length=0}),{next:async()=>{if(!W.length){if(X)return{value:void 0,done:!0};return new Promise((J,G)=>$.push({resolve:J,reject:G})).then((J)=>J?{value:J,done:!1}:{value:void 0,done:!0})}return{value:W.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}async finalResponse(){await this.done();let W=C2(this,tX,"f");if(!W)throw new o("stream ended without producing a ChatCompletion");return W}}function ZV(W,$){return DH(W,$)}class T8 extends f{constructor(){super(...arguments);this.inputItems=new c4(this._client)}create(W,$){return this._client.post("/responses",{body:W,...$,stream:W.stream??!1})._thenUnwrap((X)=>{if("object"in X&&X.object==="response")ZJ(X);return X})}retrieve(W,$={},X){if(H0($))return this.retrieve(W,{},$);return this._client.get(`/responses/${W}`,{query:$,...X})}del(W,$){return this._client.delete(`/responses/${W}`,{...$,headers:{Accept:"*/*",...$?.headers}})}parse(W,$){return this._client.responses.create(W,$)._thenUnwrap((X)=>RJ(X,W))}stream(W,$){return aX.createResponse(this._client,W,$)}}class SJ extends L0{}T8.InputItems=c4;class d4 extends f{create(W,$,X){return this._client.post(`/uploads/${W}/parts`,YW({body:$,...X}))}}class U8 extends f{constructor(){super(...arguments);this.parts=new d4(this._client)}create(W,$){return this._client.post("/uploads",{body:W,...$})}cancel(W,$){return this._client.post(`/uploads/${W}/cancel`,$)}complete(W,$,X){return this._client.post(`/uploads/${W}/complete`,{body:$,...X})}}U8.Parts=d4;var AH=async(W)=>{let $=await Promise.allSettled(W),X=$.filter((J)=>J.status==="rejected");if(X.length){for(let J of X)console.error(J.reason);throw new Error(`${X.length} promise(s) failed - see the above errors`)}let Y=[];for(let J of $)if(J.status==="fulfilled")Y.push(J.value);return Y};class w8 extends f{create(W,$,X){return this._client.post(`/vector_stores/${W}/files`,{body:$,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}retrieve(W,$,X){return this._client.get(`/vector_stores/${W}/files/${$}`,{...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}update(W,$,X,Y){return this._client.post(`/vector_stores/${W}/files/${$}`,{body:X,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}list(W,$={},X){if(H0($))return this.list(W,{},$);return this._client.getAPIList(`/vector_stores/${W}/files`,M8,{query:$,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}del(W,$,X){return this._client.delete(`/vector_stores/${W}/files/${$}`,{...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}async createAndPoll(W,$,X){let Y=await this.create(W,$,X);return await this.poll(W,Y.id,X)}async poll(W,$,X){let Y={...X?.headers,"X-Stainless-Poll-Helper":"true"};if(X?.pollIntervalMs)Y["X-Stainless-Custom-Poll-Interval"]=X.pollIntervalMs.toString();while(!0){let J=await this.retrieve(W,$,{...X,headers:Y}).withResponse(),G=J.data;switch(G.status){case"in_progress":let H=5000;if(X?.pollIntervalMs)H=X.pollIntervalMs;else{let Q=J.response.headers.get("openai-poll-after-ms");if(Q){let z=parseInt(Q);if(!isNaN(z))H=z}}await rW(H);break;case"failed":case"completed":return G}}}async upload(W,$,X){let Y=await this._client.files.create({file:$,purpose:"assistants"},X);return this.create(W,{file_id:Y.id},X)}async uploadAndPoll(W,$,X){let Y=await this.upload(W,$,X);return await this.poll(W,Y.id,X)}content(W,$,X){return this._client.getAPIList(`/vector_stores/${W}/files/${$}/content`,l4,{...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}}class M8 extends L0{}class l4 extends tW{}w8.VectorStoreFilesPage=M8;w8.FileContentResponsesPage=l4;class o4 extends f{create(W,$,X){return this._client.post(`/vector_stores/${W}/file_batches`,{body:$,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}retrieve(W,$,X){return this._client.get(`/vector_stores/${W}/file_batches/${$}`,{...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}cancel(W,$,X){return this._client.post(`/vector_stores/${W}/file_batches/${$}/cancel`,{...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}async createAndPoll(W,$,X){let Y=await this.create(W,$);return await this.poll(W,Y.id,X)}listFiles(W,$,X={},Y){if(H0(X))return this.listFiles(W,$,{},X);return this._client.getAPIList(`/vector_stores/${W}/file_batches/${$}/files`,M8,{query:X,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}async poll(W,$,X){let Y={...X?.headers,"X-Stainless-Poll-Helper":"true"};if(X?.pollIntervalMs)Y["X-Stainless-Custom-Poll-Interval"]=X.pollIntervalMs.toString();while(!0){let{data:J,response:G}=await this.retrieve(W,$,{...X,headers:Y}).withResponse();switch(J.status){case"in_progress":let H=5000;if(X?.pollIntervalMs)H=X.pollIntervalMs;else{let Q=G.headers.get("openai-poll-after-ms");if(Q){let z=parseInt(Q);if(!isNaN(z))H=z}}await rW(H);break;case"failed":case"cancelled":case"completed":return J}}}async uploadAndPoll(W,{files:$,fileIds:X=[]},Y){if($==null||$.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let J=Y?.maxConcurrency??5,G=Math.min(J,$.length),H=this._client,Q=$.values(),z=[...X];async function F(U){for(let M of U){let V=await H.files.create({file:M,purpose:"assistants"},Y);z.push(V.id)}}let T=Array(G).fill(Q).map(F);return await AH(T),await this.createAndPoll(W,{file_ids:z})}}class JW extends f{constructor(){super(...arguments);this.files=new w8(this._client),this.fileBatches=new o4(this._client)}create(W,$){return this._client.post("/vector_stores",{body:W,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}retrieve(W,$){return this._client.get(`/vector_stores/${W}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}update(W,$,X){return this._client.post(`/vector_stores/${W}`,{body:$,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}list(W={},$){if(H0(W))return this.list({},W);return this._client.getAPIList("/vector_stores",z$,{query:W,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}del(W,$){return this._client.delete(`/vector_stores/${W}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}search(W,$,X){return this._client.getAPIList(`/vector_stores/${W}/search`,F$,{body:$,method:"post",...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}}class z$ extends L0{}class F$ extends tW{}JW.VectorStoresPage=z$;JW.VectorStoreSearchResponsesPage=F$;JW.Files=w8;JW.VectorStoreFilesPage=M8;JW.FileContentResponsesPage=l4;JW.FileBatches=o4;var EH;class Q0 extends GJ{constructor({baseURL:W=_4("OPENAI_BASE_URL"),apiKey:$=_4("OPENAI_API_KEY"),organization:X=_4("OPENAI_ORG_ID")??null,project:Y=_4("OPENAI_PROJECT_ID")??null,...J}={}){if($===void 0)throw new o("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' }).");let G={apiKey:$,organization:X,project:Y,...J,baseURL:W||"https://api.openai.com/v1"};if(!G.dangerouslyAllowBrowser&&r3())throw new o(`It looks like you're running in a browser-like environment.
35
24
 
36
25
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
37
26
  If you understand the risks and have appropriate mitigations in place,
@@ -40,44 +29,44 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
40
29
  new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
41
30
 
42
31
  https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
43
- `);super({baseURL:F.baseURL,timeout:F.timeout??600000,httpAgent:F.httpAgent,maxRetries:F.maxRetries,fetch:F.fetch});this.completions=new RW(this),this.chat=new p1(this),this.embeddings=new LW(this),this.files=new y0(this),this.images=new qW(this),this.audio=new O1(this),this.moderations=new yW(this),this.models=new j0(this),this.fineTuning=new rJ(this),this.vectorStores=new VJ(this),this.beta=new tJ(this),this.batches=new L0(this),this.uploads=new P0(this),this.responses=new x0(this),this.evals=new K1(this),this._options=F,this.apiKey=$,this.organization=J,this.project=W}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 hF(T,{arrayFormat:"brackets"})}}n3=wT;wT.OpenAI=n3;wT.DEFAULT_TIMEOUT=600000;wT.OpenAIError=t;wT.APIError=F$;wT.APIConnectionError=K0;wT.APIConnectionTimeoutError=S0;wT.APIUserAbortError=U$;wT.NotFoundError=F4;wT.ConflictError=Y4;wT.RateLimitError=H4;wT.BadRequestError=J4;wT.AuthenticationError=W4;wT.InternalServerError=M4;wT.PermissionDeniedError=X4;wT.UnprocessableEntityError=G4;wT.toFile=aF;wT.fileFromPath=$4;wT.Completions=RW;wT.Chat=p1;wT.ChatCompletionsPage=R0;wT.Embeddings=LW;wT.Files=y0;wT.FileObjectsPage=NW;wT.Images=qW;wT.Audio=O1;wT.Moderations=yW;wT.Models=j0;wT.ModelsPage=kW;wT.FineTuning=rJ;wT.VectorStores=VJ;wT.VectorStoresPage=xW;wT.VectorStoreSearchResponsesPage=PW;wT.Beta=tJ;wT.Batches=L0;wT.BatchesPage=QW;wT.Uploads=P0;wT.Responses=x0;wT.Evals=K1;wT.EvalListResponsesPage=fW;var i3=wT;var JH=T_(a3(),1);import{createHash as wK}from"crypto";import*as r$ from"fs";import{copyFile as QK}from"fs/promises";import*as bW from"path";import{resolve as OK}from"path";import{existsSync as RY,mkdirSync as s3,readdirSync as e3,readFileSync as zK,rmSync as TH,statSync as $H,writeFileSync as AK}from"fs";import{resolve as LY}from"path";class BY{rootDir;get initialized(){return RY(this.rootDir)}initialize(){if(!this.initialized)s3(this.rootDir,{recursive:!0})}constructor(T){if(this.rootDir=T.path,T.eagerInit)this.initialize()}getItem(T){let $=LY(this.rootDir,T);if(RY($))return zK($,"utf-8");return null}setItem(T,$){this.initialize();let J=LY(this.rootDir,T);AK(J,$)}removeItem(T){let $=LY(this.rootDir,T);if(RY($))this.initialize(),TH($)}key(T){return e3(this.rootDir).sort((W,X)=>{let F=$H(W);return $H(X).ctimeMs-F.ctimeMs})[T]??null}clear(){TH(this.rootDir,{recursive:!0}),s3(this.rootDir,{recursive:!0})}get length(){return e3(this.rootDir).length}}var WH=/[^a-zA-Z0-9\-._]/g;function vW(T,$=64){let J=T.replace(WH,"-");if(J.length<=$)return J;let W=wK("sha256").update(T).digest("hex");return J.slice(-$)+"+"+W}var UK=JH.default("varmint"),N2=vW(process.cwd(),150),fY=OK(UK,N2),Y$="_-$-_-$-_",XH=`file${Y$}`,FH=`list${Y$}`,YH=`root${Y$}`,_K=`unmatched${Y$}`,PT={storage:new BY({path:fY,eagerInit:!1}),startGlobalTracking(){if(console.log(`\uD83D\uDC3F\uFE0F Starting global tracking of varmint files using project identifier "${N2}"`),PT.storage.initialized)console.error(`\uD83D\uDCA5 The global cache for the project "${N2}" was found already initialized. Clearing it and starting fresh.`),PT.storage.clear();PT.storage.initialize()},async prepareUploads(T){console.log(`\uD83D\uDC3F\uFE0F Moving unmatched inputs to /tmp/varmint-uploads using project identifier "${N2}"`);let $=[];for(let J of r$.readdirSync(PT.storage.rootDir))if(j4(`unmatched${Y$}`,J))$.push(J);if($.length===0){console.log("\uD83D\uDC3F\uFE0F ","No unmatched input files found.");return}if(console.log("\uD83D\uDC3F\uFE0F ","Found the following unmatched files:",`
32
+ `);super({baseURL:G.baseURL,timeout:G.timeout??600000,httpAgent:G.httpAgent,maxRetries:G.maxRetries,fetch:G.fetch});this.completions=new t8(this),this.chat=new B2(this),this.embeddings=new a8(this),this.files=new Q8(this),this.images=new Y$(this),this.audio=new aW(this),this.moderations=new G$(this),this.models=new F8(this),this.fineTuning=new hW(this),this.vectorStores=new JW(this),this.beta=new yW(this),this.batches=new e2(this),this.uploads=new U8(this),this.responses=new T8(this),this.evals=new $2(this),this._options=G,this.apiKey=$,this.organization=X,this.project=Y}defaultQuery(){return this._options.defaultQuery}defaultHeaders(W){return{...super.defaultHeaders(W),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(W){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(W){return c9(W,{arrayFormat:"brackets"})}}EH=Q0;Q0.OpenAI=EH;Q0.DEFAULT_TIMEOUT=600000;Q0.OpenAIError=o;Q0.APIError=r0;Q0.APIConnectionError=n2;Q0.APIConnectionTimeoutError=r2;Q0.APIUserAbortError=X1;Q0.NotFoundError=RX;Q0.ConflictError=ZX;Q0.RateLimitError=qX;Q0.BadRequestError=EX;Q0.AuthenticationError=NX;Q0.InternalServerError=CX;Q0.PermissionDeniedError=BX;Q0.UnprocessableEntityError=SX;Q0.toFile=XJ;Q0.fileFromPath=AX;Q0.Completions=t8;Q0.Chat=B2;Q0.ChatCompletionsPage=s2;Q0.Embeddings=a8;Q0.Files=Q8;Q0.FileObjectsPage=W$;Q0.Images=Y$;Q0.Audio=aW;Q0.Moderations=G$;Q0.Models=F8;Q0.ModelsPage=J$;Q0.FineTuning=hW;Q0.VectorStores=JW;Q0.VectorStoresPage=z$;Q0.VectorStoreSearchResponsesPage=F$;Q0.Beta=yW;Q0.Batches=e2;Q0.BatchesPage=p8;Q0.Uploads=U8;Q0.Responses=T8;Q0.Evals=$2;Q0.EvalListResponsesPage=e8;var NH=Q0;var jH=S_(ZH(),1);import*as b1 from"fs";import*as T$ from"path";import{resolve as vV}from"path";import{createHash as bV}from"crypto";import{copyFile as yV}from"fs/promises";import{existsSync as qJ,mkdirSync as SH,readFileSync as PV,readdirSync as qH,rmSync as CH,statSync as kH,writeFileSync as xV}from"fs";import{resolve as CJ}from"path";var IH=class{rootDir;get initialized(){return qJ(this.rootDir)}initialize(){if(!this.initialized)SH(this.rootDir,{recursive:!0})}constructor(W){if(this.rootDir=W.path,W.eagerInit)this.initialize()}getItem(W){let $=CJ(this.rootDir,W);if(qJ($))return PV($,"utf-8");return null}setItem(W,$){this.initialize();let X=CJ(this.rootDir,W);xV(X,$)}removeItem(W){let $=CJ(this.rootDir,W);if(qJ($))this.initialize(),CH($)}key(W){return qH(this.rootDir).sort((Y,J)=>{let G=kH(Y);return kH(J).ctimeMs-G.ctimeMs})[W]??null}clear(){CH(this.rootDir,{recursive:!0}),SH(this.rootDir,{recursive:!0})}get length(){return qH(this.rootDir).length}};var fH=/[^a-zA-Z0-9\-._]/g;function t4(W,$=64){if($%2===1)$+=1;let X=W.replace(fH,"-");if(X.length<=$)return X;let Y=bV("sha256").update(W).digest("base64").slice(0,8).replace("/","_"),J=X;if(J.length>$){let G=J.slice(0,$/2),H=J.slice(-$/2);J=G+"_"+H}return J+"+"+Y}var hV=jH.default("varmint"),r4=t4(process.cwd(),150),kJ=vV(hV,r4),J1="_-$-_-$-_",PH=`file${J1}`,xH=`list${J1}`,vH=`root${J1}`,gV=`unmatched${J1}`,j0={storage:new IH({path:kJ,eagerInit:!1}),startGlobalTracking(){if(console.log(`\uD83D\uDC3F\uFE0F Starting global tracking of varmint files using project identifier "${r4}"`),j0.storage.initialized)console.error(`\uD83D\uDCA5 The global cache for the project "${r4}" was found already initialized. Clearing it and starting fresh.`),j0.storage.clear();j0.storage.initialize()},async prepareUploads(W){console.log(`\uD83D\uDC3F\uFE0F Moving unmatched inputs to /tmp/varmint-uploads using project identifier "${r4}"`);let $=[];for(let X of b1.readdirSync(j0.storage.rootDir))if(sX(`unmatched${J1}`,X))$.push(X);if($.length===0){console.log("\uD83D\uDC3F\uFE0F ","No unmatched input files found.");return}if(console.log("\uD83D\uDC3F\uFE0F ","Found the following unmatched files:",`
44
33
  - ${$.join(`
45
34
  `)}
46
35
  `,`in root folder:
47
- `,fY),process.env[T])r$.mkdirSync("/tmp/varmint-uploads",{recursive:!0}),await Promise.all($.map(async(J)=>{let W=bW.join(fY,J),X=bW.join("/tmp/varmint-uploads",J);await QK(W,X)}));else console.warn("\uD83D\uDCA5 Skipping artifact upload because process.env.CI is not set.")},endGlobalTrackingAndFlushUnusedFiles(){if(console.log(`\uD83D\uDC3F\uFE0F Ending global tracking of varmint files using project identifier "${N2}" and starting cleanup of untouched files.`),!PT.storage.initialized){console.error("\uD83D\uDCA5 called flushGlobal, but the global cache wasn't initialized with startGlobalTracking");return}let T=r$.readdirSync(PT.storage.rootDir),$=new Map,J=[],W=[],X=[];for(let Y of T)if(j4(`root${Y$}`,Y))J.push(Y);else if(j4(`list${Y$}`,Y))W.push(Y);else if(j4(`file${Y$}`,Y))X.push(Y);if(PT.storage.getItem("DID_CACHE_MISS"))console.log("\uD83D\uDC3F\uFE0F ","Cache miss detected. Since this likely prevented the cache from being fully utilized, we will not attempt to flush unused files.");else{let Y=new Map;for(let G of J){let H=G.replace(YH,"");Y.set(H,new Map);let M=PT.storage.getItem(G);if(M)$.set(H,M);else console.error(`\uD83D\uDCA5 Could not find folder ${M} referenced in the global cache`)}for(let G of W){let H=G.replace(FH,""),[M,z]=H.split(Y$),A=Y.get(M);if(A)A.set(z,new Set);else console.error(`\uD83D\uDCA5 Could not find root ${M} for list ${z}`)}for(let G of X){let H=G.replace(XH,""),[M,z,A]=H.split(Y$),w=Y.get(M);if(w){let _=w.get(z);if(_)_.add(A);else console.error(`\uD83D\uDCA5 Could not find list ${z} for file ${H}`)}else console.error(`\uD83D\uDCA5 Could not find root ${M} for file ${H}`)}console.log("\uD83D\uDC3F\uFE0F ",Y);for(let[G,H]of Y.entries()){let M=$.get(G);if(!M){console.error(`\uD83D\uDCA5 Could not find root ${G}`);continue}if(!r$.existsSync(M)){console.warn(`\uD83D\uDCA5 Root folder ${M}, identified as being used during tracking, no longer exists during cleanup.`);continue}let A=r$.readdirSync(M);for(let w of A)if(w!==".ferret"&&!H.has(w)){let _=bW.join(M,w);console.log(`\uD83E\uDDF9 globalFlush: removing directory ${_}`),r$.rmSync(_,{recursive:!0})}for(let[w,_]of H.entries()){let D=bW.join(M,w);if(!r$.existsSync(D)){console.warn(`\uD83D\uDCA5 List folder ${D}, identified as being used during tracking, no longer exists.`);continue}let Z=r$.readdirSync(D);for(let q of Z){let N=q.replace(".input.json","").replace(".output.json","").replace(".stream.txt","");if(!_.has(N)){let y=bW.join(D,q);console.log(`\uD83E\uDDF9 globalFlush: removing file ${y}`),r$.rmSync(y)}}}}}r$.rmSync(PT.storage.rootDir,{recursive:!0})}};function j4(T,$){return $.startsWith(T)}import*as lT from"fs";import*as xJ from"path";import{inspect as GH}from"util";var HH=class{filenameCache=new Map;filesTouched=new Map;mode;baseDir;rootName;constructor(T="off",$=xJ.join(process.cwd(),".varmint")){if(this.mode=T,this.baseDir=$,this.rootName=vW(this.baseDir),PT.storage.initialized&&!PT.storage.getItem(`root${Y$}${this.rootName}`))PT.storage.setItem(`root${Y$}${this.rootName}`,this.baseDir)}read(T,$,J){let W=xJ.join(this.baseDir,T),X=`${$}.input.json`,F=xJ.join(W,X);if(!lT.existsSync(F)){if(!lT.existsSync(W)){if(PT.storage.initialized&&this.mode==="read")PT.storage.setItem("DID_CACHE_MISS","true");throw new Error(`Squirrel: input file for key "${T}" with "${$}" was not found. Directory "${W}" does not exist.`)}let A=lT.readdirSync(W).map((D)=>[D,lT.readFileSync(xJ.join(W,D),"utf-8")]).filter(([D])=>D.endsWith(".input.json")),w=[];for(let[D,S]of A){let Z=` ${D}`,q=` ${GH(JSON.parse(S),{depth:Number.POSITIVE_INFINITY,colors:!0}).split(`
36
+ `,kJ),process.env[W])b1.mkdirSync("/tmp/varmint-uploads",{recursive:!0}),await Promise.all($.map(async(X)=>{let Y=T$.join(kJ,X),J=T$.join("/tmp/varmint-uploads",X);await yV(Y,J)}));else console.warn("\uD83D\uDCA5 Skipping artifact upload because process.env.CI is not set.")},endGlobalTrackingAndFlushUnusedFiles(){if(console.log(`\uD83D\uDC3F\uFE0F Ending global tracking of varmint files using project identifier "${r4}" and starting cleanup of untouched files.`),!j0.storage.initialized){console.error("\uD83D\uDCA5 called flushGlobal, but the global cache wasn't initialized with startGlobalTracking");return}let W=b1.readdirSync(j0.storage.rootDir),$=new Map,X=[],Y=[],J=[];for(let H of W)if(sX(`root${J1}`,H))X.push(H);else if(sX(`list${J1}`,H))Y.push(H);else if(sX(`file${J1}`,H))J.push(H);if(j0.storage.getItem("DID_CACHE_MISS"))console.log("\uD83D\uDC3F\uFE0F ","Cache miss detected. Since this likely prevented the cache from being fully utilized, we will not attempt to flush unused files.");else{let H=new Map;for(let Q of X){let z=Q.replace(vH,"");H.set(z,new Map);let F=j0.storage.getItem(Q);if(F)$.set(z,F);else console.error(`\uD83D\uDCA5 Could not find folder ${F} referenced in the global cache`)}for(let Q of Y){let z=Q.replace(xH,""),[F,T]=z.split(J1),U=H.get(F);if(U)U.set(T,new Set);else console.error(`\uD83D\uDCA5 Could not find root ${F} for list ${T}`)}for(let Q of J){let z=Q.replace(PH,""),[F,T,U]=z.split(J1),M=H.get(F);if(M){let V=M.get(T);if(V)V.add(U);else console.error(`\uD83D\uDCA5 Could not find list ${T} for file ${z}`)}else console.error(`\uD83D\uDCA5 Could not find root ${F} for file ${z}`)}console.log("\uD83D\uDC3F\uFE0F ",H);for(let[Q,z]of H.entries()){let F=$.get(Q);if(!F){console.error(`\uD83D\uDCA5 Could not find root ${Q}`);continue}if(!b1.existsSync(F)){console.warn(`\uD83D\uDCA5 Root folder ${F}, identified as being used during tracking, no longer exists during cleanup.`);continue}let U=b1.readdirSync(F);for(let M of U)if(M!==".ferret"&&!z.has(M)){let V=T$.join(F,M);console.log(`\uD83E\uDDF9 globalFlush: removing directory ${V}`),b1.rmSync(V,{recursive:!0})}for(let[M,V]of z.entries()){let K=T$.join(F,M);if(!b1.existsSync(K)){console.warn(`\uD83D\uDCA5 List folder ${K}, identified as being used during tracking, no longer exists.`);continue}let I=b1.readdirSync(K);for(let C of I){let B=C.replace(".input.json","").replace(".output.json","").replace(".stream.txt","");if(!V.has(B)){let q=T$.join(K,C);console.log(`\uD83E\uDDF9 globalFlush: removing file ${q}`),b1.rmSync(q)}}}}}b1.rmSync(j0.storage.rootDir,{recursive:!0})}};function sX(W,$){return $.startsWith(W)}import*as o0 from"fs";import*as AW from"path";import{inspect as bH}from"util";var yH=class{filenameCache=new Map;filesTouched=new Map;mode;baseDir;rootName;constructor(W="off",$=AW.join(process.cwd(),".varmint")){if(this.mode=W,this.baseDir=$,this.rootName=t4(this.baseDir),j0.storage.initialized&&!j0.storage.getItem(`root${J1}${this.rootName}`))j0.storage.setItem(`root${J1}${this.rootName}`,this.baseDir)}read(W,$,X){let Y=AW.join(this.baseDir,W),J=`${$}.input.json`,G=AW.join(Y,J);if(!o0.existsSync(G)){if(!o0.existsSync(Y)){if(j0.storage.initialized&&this.mode==="read")j0.storage.setItem("DID_CACHE_MISS","true");throw new Error(`Squirrel: input file for key "${W}" with "${$}" was not found. Directory "${Y}" does not exist.`)}let U=o0.readdirSync(Y).map((K)=>[K,o0.readFileSync(AW.join(Y,K),"utf-8")]).filter(([K])=>K.endsWith(".input.json")),M=[];for(let[K,N]of U){let I=` ${K}`,C=` ${bH(JSON.parse(N),{depth:Number.POSITIVE_INFINITY,colors:!0}).split(`
48
37
  `).join(`
49
- `)}`;w.push(Z,q)}let _=` ${X}
50
- ${GH(J,{depth:Number.POSITIVE_INFINITY,colors:!0}).split(`
38
+ `)}`;M.push(I,C)}let V=` ${J}
39
+ ${bH(X,{depth:Number.POSITIVE_INFINITY,colors:!0}).split(`
51
40
  `).join(`
52
- `)}`;if(PT.storage.initialized&&this.mode==="read")PT.storage.setItem(`unmatched${Y$}${X}`,JSON.stringify(J,null,"\t")),PT.storage.setItem("DID_CACHE_MISS","true");throw new Error(`Squirrel: input file for key "${T}" with subKey "${$}" (${F}) was not found. Directory "${W}" exists, but the file does not. Below is a list of CACHED INPUT FILES from that directory and their contents, followed by YOUR INPUT DATA.
41
+ `)}`;if(j0.storage.initialized&&this.mode==="read")j0.storage.setItem(`unmatched${J1}${J}`,JSON.stringify(X,null,"\t")),j0.storage.setItem("DID_CACHE_MISS","true");throw new Error(`Squirrel: input file for key "${W}" with subKey "${$}" (${G}) was not found. Directory "${Y}" exists, but the file does not. Below is a list of CACHED INPUT FILES from that directory and their contents, followed by YOUR INPUT DATA.
53
42
 
54
43
  CACHED INPUT FILES:
55
- ${w.join(`
44
+ ${M.join(`
56
45
  `)}
57
46
 
58
47
  YOUR INPUT DATA:
59
- ${_}
60
- `)}let Y=lT.readFileSync(F,"utf-8"),G=JSON.stringify(J,null,"\t");if(G!==Y){if(PT.storage.initialized&&this.mode==="read")PT.storage.setItem("DID_CACHE_MISS","true");throw new Error(`Squirrel: the content of the cached input file ${F} does not match the input provided.
48
+ ${V}
49
+ `)}let H=o0.readFileSync(G,"utf-8"),Q=JSON.stringify(X,null,"\t");if(Q!==H){if(j0.storage.initialized&&this.mode==="read")j0.storage.setItem("DID_CACHE_MISS","true");throw new Error(`Squirrel: the content of the cached input file ${G} does not match the input provided.
61
50
 
62
51
  Provided:
63
- ${G}
52
+ ${Q}
64
53
 
65
54
  Cached:
66
- ${Y}`)}let H=xJ.join(this.baseDir,`${T}/${$}.output.json`);return JSON.parse(lT.readFileSync(H,"utf-8"))}async write(T,$,J,W){let X=xJ.join(this.baseDir,T),F=xJ.join(X,`${$}.input.json`),Y=xJ.join(X,`${$}.output.json`),G=JSON.stringify(J,null,"\t");if(!lT.existsSync(this.baseDir))lT.mkdirSync(this.baseDir,{recursive:!0});if(!lT.existsSync(X))lT.mkdirSync(X);if(lT.writeFileSync(F,G),lT.existsSync(Y))lT.unlinkSync(Y);let H=await W(...J),M=JSON.stringify(H,null,"\t");return lT.writeFileSync(Y,M),H}add(T,$){let J=`${this.rootName}${Y$}${vW(T)}`;return{flush:()=>{this.flush(T)},for:(W)=>{if(this.mode!=="off"){if(this.filesTouched.set(T,new Set),PT.storage.initialized&&!PT.storage.getItem(`list${Y$}${J}`))PT.storage.setItem(`list${Y$}${J}`,"true")}return{get:async(...X)=>{let F=W;if(this.mode!=="off"){let Y=this.filenameCache.get(W);if(!Y)Y=vW(W),this.filenameCache.set(W,Y);F=Y,this.filesTouched.get(T)?.add(F);let G=`${J}${Y$}${F}`,H=`file${Y$}${G}`;if(PT.storage.initialized&&!PT.storage.getItem(H))PT.storage.setItem(H,"true")}switch(this.mode){case"off":return $(...X);case"read":return this.read(T,F,X);case"write":return this.write(T,F,X,$);case"read-write":try{return this.read(T,F,X)}catch(Y){if(Y instanceof Error)return this.write(T,F,X,$);throw Y}}}}}}}flush(...T){console.log(this.filesTouched);for(let[$,J]of this.filesTouched.entries())if(T.length===0||T.includes($)){let W=xJ.join(this.baseDir,$),X=lT.readdirSync(W);for(let F of X){let Y=F.replace(".input.json","").replace(".output.json","");if(!J.has(Y))console.info(`\uD83E\uDDF9 Flushing ${Y}`),lT.unlinkSync(xJ.join(W,F))}}}};function DK(T,...$){let[J,W,X,F]=$,Y=[{role:"user",content:tG(W)},{role:"user",content:J}],G=F.at(-1);if(G)Y.push({role:"user",content:["Oops! That didn't work. Here's what was returned last time:",JSON.stringify(G.response,null,2),"Here's the error message:",JSON.stringify(G.error.issues,null,2)].join(`
67
- `)});return{model:T,messages:Y}}var NY={"gpt-4o":{promptPricePerToken:0.0000025,promptPricePerTokenCached:0.00000125,completionPricePerToken:0.00001},"gpt-4o-2024-08-06":{promptPricePerToken:0.0000025,promptPricePerTokenCached:0.00000125,completionPricePerToken:0.00001},"gpt-4o-2024-05-13":{promptPricePerToken:0.000005,promptPricePerTokenCached:0.000005,completionPricePerToken:0.000014999999999999999},"gpt-4o-mini":{promptPricePerToken:0.00000015,promptPricePerTokenCached:0.000000075,completionPricePerToken:0.0000006},"gpt-4o-mini-2024-07-18":{promptPricePerToken:0.00000015,promptPricePerTokenCached:0.000000075,completionPricePerToken:0.0000006},"o1-preview":{promptPricePerToken:0.000014999999999999999,promptPricePerTokenCached:0.000007499999999999999,completionPricePerToken:0.000059999999999999995},"o1-preview-2024-09-12":{promptPricePerToken:0.000014999999999999999,promptPricePerTokenCached:0.000007499999999999999,completionPricePerToken:0.000059999999999999995}};function KK(T){return async function $(J,W){if(!T)throw new Error("This is a bug in safegen. OpenAI client not available to the json generator.");let X=await T.chat.completions.create({...J,stream:!1,response_format:{type:"json_object"}},W),F=X.choices[0].message?.content,{usage:Y}=X;if(F&&Y){let G=Y.prompt_tokens,H=Y.prompt_tokens_details?.cached_tokens??0,M=G-H,z=Y.completion_tokens,A=G*NY[J.model].promptPricePerToken+M*NY[J.model].promptPricePerTokenCached+z*NY[J.model].completionPricePerToken;return{data:JSON.parse(F),usage:Y,usdPrice:A}}if(!F&&!Y)throw new Error("No content or usage found in completion");if(!F)throw new Error("No content found in completion");throw new Error("No usage found in completion")}}var MH=new Map,zH=class{usdBudget;usdMinimum;getUnknownJsonFromOpenAi;getUnknownJsonFromOpenAiSquirreled;squirrel;client;lastUsage;constructor({model:T,usdBudget:$,usdMinimum:J,apiKey:W,cachingMode:X,cacheKey:F="openai-safegen",logger:Y}){this.usdBudget=$,this.usdMinimum=J,this.squirrel=new HH(X);let G=MH.get(W);if(X!=="read"){if(!G)G=new i3({apiKey:W,dangerouslyAllowBrowser:!1}),MH.set(W,G);this.client=G}this.getUnknownJsonFromOpenAi=KK(this.client),this.getUnknownJsonFromOpenAiSquirreled=this.squirrel.add(F,this.getUnknownJsonFromOpenAi),this.from=iG(async(...H)=>{if(this.usdBudget<this.usdMinimum)return Y?.warn("SafeGen budget exhausted"),H[1];let M=DK(T,...H),z=H[0],A=H[3],{data:w,usage:_,usdPrice:D}=await this.getUnknownJsonFromOpenAiSquirreled.for(`${z.replace(/[^a-zA-Z0-9-_. ]/g,"_")}-${A.length}`).get(M);return this.lastUsage=_,this.usdBudget-=D,w},Y)}from};import{exec as NL}from"child_process";var CY=(T)=>{let $=XJ(T,{key:"\uD83D\uDD0D Atom Token Index (Internal)",default:()=>{let J=new Map;for(let[W,X]of T.atoms){if(v1(W))continue;let F=n$(X);if(X.family){let Y=J.get(X.family.key);if(!Y||!("familyMembers"in Y))Y={key:X.family.key,familyMembers:new Map},J.set(X.family.key,Y);Y.familyMembers.set(X.family.subKey,F)}else J.set(W,F)}return J},effects:[({setSelf:J})=>{T.on.atomCreation.subscribe("introspection",(W)=>{if(v1(W.key))return;J((X)=>{if(W.family){let{key:F,subKey:Y}=W.family,G=X.get(F);if(G===void 0||!("familyMembers"in G))G={key:F,familyMembers:new Map},X.set(F,G);G.familyMembers.set(Y,W)}else X.set(W.key,W);return X})}),T.on.atomDisposal.subscribe("introspection",(W)=>{J((X)=>{if(W.family){let{key:F,subKey:Y}=W.family,G=X.get(F);if(G&&"familyMembers"in G){if(G.familyMembers.delete(Y),G.familyMembers.size===0)X.delete(F)}}else X.delete(W.key);return X})})}]},void 0);return W1(T,{key:"\uD83D\uDD0D Atom Token Index",get:({get:J})=>J($)})};var ZY=(T)=>{let $=XJ(T,{key:"\uD83D\uDD0D Selector Token Index (Internal)",default:()=>{let J=new Map;for(let W of[T.readonlySelectors,T.selectors])for(let[X,F]of W){if(v1(X))continue;let Y=n$(F);if(F.family){let G=J.get(F.family.key);if(!G||!("familyMembers"in G))G={key:F.family.key,familyMembers:new Map},J.set(F.family.key,G);G.familyMembers.set(F.family.subKey,Y)}else J.set(X,Y)}return J},effects:[({setSelf:J})=>{T.on.selectorCreation.subscribe("introspection",(W)=>{if(v1(W.key))return;J((X)=>{if(W.family){let{key:F,subKey:Y}=W.family,G=X.get(F);if(G===void 0||!("familyMembers"in G))G={key:F,familyMembers:new Map},X.set(F,G);G.familyMembers.set(Y,W)}else X.set(W.key,W);return X})}),T.on.selectorDisposal.subscribe("introspection",(W)=>{J((X)=>{if(W.family){let{key:F,subKey:Y}=W.family,G=X.get(F);if(G&&"familyMembers"in G){if(G.familyMembers.delete(Y),G.familyMembers.size===0)X.delete(F)}}else X.delete(W.key);return X})})}]},void 0);return W1(T,{key:"\uD83D\uDD0D Selector Token Index",get:({get:J})=>J($)})};class x4{supported;constructor(T){this.supported=T}refine(T){for(let[$,J]of Object.entries(this.supported))try{if(J(T)===!0&&J!==Boolean)return{type:$,data:T}}catch(W){try{if(T instanceof J)return{type:$,data:T}}catch(X){}}return null}}var qY=new x4({number:(T)=>typeof T==="number",string:(T)=>typeof T==="string",boolean:(T)=>typeof T==="boolean",null:(T)=>T===null});function kY(T){if(!T)return!1;return Object.getPrototypeOf(T)===Object.prototype}var yY=new x4({object:kY,array:(T)=>Array.isArray(T)}),SK=new x4({...qY.supported,...yY.supported}),hW=(T)=>{if(T===void 0)return"undefined";let $=SK.refine(T);if($)return $.type;return Object.getPrototypeOf(T).constructor.name};class AH{store;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(T=KT.STORE){this.store=T,this.atomIndex=CY(this.store),this.selectorIndex=ZY(this.store),this.unsubscribeFromAtomCreation=this.store.on.atomCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:$})=>{this.statesCreatedAt.set($,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromAtomDisposal=this.store.on.atomDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:$})=>{this.statesCreatedAt.delete($)}),this.unsubscribeFromSelectorCreation=this.store.on.selectorCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:$})=>{this.statesCreatedAt.set($,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromSelectorDisposal=this.store.on.selectorDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:$})=>{this.statesCreatedAt.delete($)})}static DEFAULT_LIST_RESOURCES_PARAM={atomFamilies:!0,selectorFamilies:!0};listResources(T=AH.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");let $=WF(this.atomIndex),J=WF(this.selectorIndex),W=[...$.values()].filter((G)=>("familyMembers"in G)),X=[...J.values()].filter((G)=>("familyMembers"in G)),F=performance.now(),Y=[];if(T.atomFamilies)for(let G of W){let H=G.familyMembers.values();for(let M of H){let A=this.statesCreatedAt.get(M.key)??this.auditorCreatedAt,w=F-A;Y.push([M,w])}}if(T.selectorFamilies)for(let G of X){let H=G.familyMembers.values();for(let M of H){let A=this.statesCreatedAt.get(M.key)??this.auditorCreatedAt,w=F-A;Y.push([M,w])}}return Y}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}}var IY=(T,$)=>{let J=(W,X)=>{let Y=((H,M)=>{let z=$(H,M);if(z)return z;return null})(W,X);if(Y?.jobComplete??Y?.pathComplete)return Y;let G=Array.isArray(X)?X.map((H,M)=>[M,H]):kY(X)?Object.entries(X):[];for(let[H,M]of G){let z=J([...W,H],M);if(z?.jobComplete)return z}return{}};J([],T)};function VK(T,$){return{summary:`${T<$?"+":"-"}${Math.abs(T-$)} (${T} \u2192 ${$})`}}function EK(T,$){return{summary:`${T.length<$.length?"+":"-"}${Math.abs(T.length-$.length)} ("${T}" \u2192 "${$}")`}}function RK(T,$){return{summary:`${T} \u2192 ${$}`}}function wH(T,$,J){let W="",X=[],F=[],Y=[];return IY(T,(G,H)=>{let M;for(M of G){let z=$[M];if(z===void 0)F.push([M,JSON.stringify(H)]);else{let A=J(H,z);if(A.summary!=="No Change")Y.push([M,A])}}}),IY($,(G,H)=>{let M;for(M of G)if(T[M]===void 0)X.push([M,JSON.stringify(H)])}),W=`\uFF5E${Y.length} \uFF0B${X.length} \uFF0D${F.length}`,{summary:W,added:X,removed:F,changed:Y}}function LK(T,$,J){return wH(T,$,J)}class QH{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(T,$,J){this.leafRefinery=T,this.treeRefinery=$,this.leafDiffers={},this.treeDiffers={};for(let W of Object.keys(T.supported)){let X=J[W];this.leafDiffers[W]=X}for(let W of Object.keys($.supported)){let X=J[W];this.treeDiffers[W]=X}}diff(T,$){if(T===$)return{summary:"No Change"};let J=this.leafRefinery.refine(T)??this.treeRefinery.refine(T),W=this.leafRefinery.refine($)??this.treeRefinery.refine($);if(J!==null&&W!==null){if(J.type===W.type){if(J.type in this.leafDiffers)return this.leafDiffers[J.type](J.data,W.data);if(J.type in this.treeDiffers)return this.treeDiffers[J.type](J.data,W.data,(G,H)=>this.diff(G,H))}}let X=hW(T),F=hW($);if(X===F)return{summary:`${X} \u2192 ${F}`};return{summary:`Type change: ${X} \u2192 ${F}`}}}var Ru=new QH(qY,yY,{number:VK,string:EK,boolean:RK,null:()=>({summary:"No Change"}),object:wH,array:LK});var O=Symbol.for("drizzle:entityKind"),ku=Symbol.for("drizzle:hasOwnEntityKind");function L(T,$){if(!T||typeof T!=="object")return!1;if(T instanceof $)return!0;if(!Object.prototype.hasOwnProperty.call($,O))throw new Error(`Class "${$.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let J=Object.getPrototypeOf(T).constructor;if(J)while(J){if(O in J&&J[O]===$[O])return!0;J=Object.getPrototypeOf(J)}return!1}class bT{constructor(T,$){this.table=T,this.config=$,this.name=$.name,this.keyAsName=$.keyAsName,this.notNull=$.notNull,this.default=$.default,this.defaultFn=$.defaultFn,this.onUpdateFn=$.onUpdateFn,this.hasDefault=$.hasDefault,this.primary=$.primaryKey,this.isUnique=$.isUnique,this.uniqueName=$.uniqueName,this.uniqueType=$.uniqueType,this.dataType=$.dataType,this.columnType=$.columnType,this.generated=$.generated,this.generatedIdentity=$.generatedIdentity}static[O]="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 jY{static[O]="ColumnBuilder";config;constructor(T,$,J){this.config={name:T,keyAsName:T==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:$,columnType:J,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 PJ=Symbol.for("drizzle:Name");class xY{static[O]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(T,$){if(this.reference=()=>{let{name:J,columns:W,foreignColumns:X}=T();return{name:J,columns:W,foreignTable:X[0].table,foreignColumns:X}},$)this._onUpdate=$.onUpdate,this._onDelete=$.onDelete}onUpdate(T){return this._onUpdate=T===void 0?"no action":T,this}onDelete(T){return this._onDelete=T===void 0?"no action":T,this}build(T){return new OH(T,this)}}class OH{constructor(T,$){this.table=T,this.reference=$.reference,this.onUpdate=$._onUpdate,this.onDelete=$._onDelete}static[O]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:T,columns:$,foreignColumns:J}=this.reference(),W=$.map((Y)=>Y.name),X=J.map((Y)=>Y.name),F=[this.table[PJ],...W,J[0].table[PJ],...X];return T??`${F.join("_")}_fk`}}function P4(T,...$){return T(...$)}function UH(T,$){return`${T[PJ]}_${$.join("_")}_unique`}function _H(T,$,J){for(let W=$;W<T.length;W++){let X=T[W];if(X==="\\"){W++;continue}if(X==='"')return[T.slice($,W).replace(/\\/g,""),W+1];if(J)continue;if(X===","||X==="}")return[T.slice($,W).replace(/\\/g,""),W]}return[T.slice($).replace(/\\/g,""),T.length]}function DH(T,$=0){let J=[],W=$,X=!1;while(W<T.length){let F=T[W];if(F===","){if(X||W===$)J.push("");X=!0,W++;continue}if(X=!1,F==="\\"){W+=2;continue}if(F==='"'){let[H,M]=_H(T,W+1,!0);J.push(H),W=M;continue}if(F==="}")return[J,W+1];if(F==="{"){let[H,M]=DH(T,W+1);J.push(H),W=M;continue}let[Y,G]=_H(T,W,!1);J.push(Y),W=G}return[J,W]}function KH(T){let[$]=DH(T,1);return $}function PY(T){return`{${T.map(($)=>{if(Array.isArray($))return PY($);if(typeof $==="string")return`"${$.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${$}`}).join(",")}}`}class d extends jY{foreignKeyConfigs=[];static[O]="PgColumnBuilder";array(T){return new VH(this.config.name,this,T)}references(T,$={}){return this.foreignKeyConfigs.push({ref:T,actions:$}),this}unique(T,$){return this.config.isUnique=!0,this.config.uniqueName=T,this.config.uniqueType=$?.nulls,this}generatedAlwaysAs(T){return this.config.generated={as:T,type:"always",mode:"stored"},this}buildForeignKeys(T,$){return this.foreignKeyConfigs.map(({ref:J,actions:W})=>{return P4((X,F)=>{let Y=new xY(()=>{let G=X();return{columns:[T],foreignColumns:[G]}});if(F.onUpdate)Y.onUpdate(F.onUpdate);if(F.onDelete)Y.onDelete(F.onDelete);return Y.build($)},J,W)})}buildExtraConfigColumn(T){return new SH(T,this.config)}}class P extends bT{constructor(T,$){if(!$.uniqueName)$.uniqueName=UH(T,[$.name]);super(T,$);this.table=T}static[O]="PgColumn"}class SH extends P{static[O]="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 C2{static[O]="IndexedColumn";constructor(T,$,J,W){this.name=T,this.keyAsName=$,this.type=J,this.indexConfig=W}name;keyAsName;type;indexConfig}class VH extends d{static[O]="PgArrayBuilder";constructor(T,$,J){super(T,"array","PgArray");this.config.baseBuilder=$,this.config.size=J}build(T){let $=this.config.baseBuilder.build(T);return new bY(T,this.config,$)}}class bY extends P{constructor(T,$,J,W){super(T,$);this.baseColumn=J,this.range=W,this.size=$.size}size;static[O]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(T){if(typeof T==="string")T=KH(T);return T.map(($)=>this.baseColumn.mapFromDriverValue($))}mapToDriverValue(T,$=!1){let J=T.map((W)=>W===null?null:L(this.baseColumn,bY)?this.baseColumn.mapToDriverValue(W,!0):this.baseColumn.mapToDriverValue(W));if($)return J;return PY(J)}}class EH extends d{static[O]="PgEnumObjectColumnBuilder";constructor(T,$){super(T,"string","PgEnumObjectColumn");this.config.enum=$}build(T){return new RH(T,this.config)}}class RH extends P{static[O]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(T,$){super(T,$);this.enum=$.enum}getSQLType(){return this.enum.enumName}}var b4=Symbol.for("drizzle:isPgEnum");function LH(T){return!!T&&typeof T==="function"&&b4 in T&&T[b4]===!0}class BH extends d{static[O]="PgEnumColumnBuilder";constructor(T,$){super(T,"string","PgEnumColumn");this.config.enum=$}build(T){return new fH(T,this.config)}}class fH extends P{static[O]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(T,$){super(T,$);this.enum=$.enum}getSQLType(){return this.enum.enumName}}function v4(T,$){return Array.isArray($)?BK(T,[...$],void 0):fK(T,$,void 0)}function BK(T,$,J){let W=Object.assign((X)=>new BH(X??"",W),{enumName:T,enumValues:$,schema:J,[b4]:!0});return W}function fK(T,$,J){let W=Object.assign((X)=>new EH(X??"",W),{enumName:T,enumValues:Object.values($),schema:J,[b4]:!0});return W}class D${static[O]="Subquery";constructor(T,$,J,W=!1){this._={brand:"Subquery",sql:T,selectedFields:$,alias:J,isWith:W}}}class Z2 extends D${static[O]="WithSubquery"}var NH="0.42.0";var vY,hY,vT={startActiveSpan(T,$){if(!vY)return $();if(!hY)hY=vY.trace.getTracer("drizzle-orm",NH);return P4((J,W)=>W.startActiveSpan(T,(X)=>{try{return $(X)}catch(F){throw X.setStatus({code:J.SpanStatusCode.ERROR,message:F instanceof Error?F.message:"Unknown error"}),F}finally{X.end()}}),vY,hY)}};var pT=Symbol.for("drizzle:ViewBaseConfig");var h4=Symbol.for("drizzle:Schema"),m4=Symbol.for("drizzle:Columns"),CH=Symbol.for("drizzle:ExtraConfigColumns"),mY=Symbol.for("drizzle:OriginalName"),gY=Symbol.for("drizzle:BaseName"),q2=Symbol.for("drizzle:IsAlias"),ZH=Symbol.for("drizzle:ExtraConfigBuilder"),NK=Symbol.for("drizzle:IsDrizzleTable");class u{static[O]="Table";static Symbol={Name:PJ,Schema:h4,OriginalName:mY,Columns:m4,ExtraConfigColumns:CH,BaseName:gY,IsAlias:q2,ExtraConfigBuilder:ZH};[PJ];[mY];[h4];[m4];[CH];[gY];[q2]=!1;[NK]=!0;[ZH]=void 0;constructor(T,$,J){this[PJ]=this[mY]=T,this[h4]=$,this[gY]=J}}function B$(T){return T[PJ]}function h0(T){return`${T[h4]??"public"}.${T[PJ]}`}function pY(T){return T!==null&&T!==void 0&&typeof T.getSQL==="function"}function CK(T){let $={sql:"",params:[]};for(let J of T)if($.sql+=J.sql,$.params.push(...J.params),J.typings?.length){if(!$.typings)$.typings=[];$.typings.push(...J.typings)}return $}class K${static[O]="StringChunk";value;constructor(T){this.value=Array.isArray(T)?T:[T]}getSQL(){return new c([this])}}class c{constructor(T){this.queryChunks=T}static[O]="SQL";decoder=kH;shouldInlineParams=!1;append(T){return this.queryChunks.push(...T.queryChunks),this}toQuery(T){return vT.startActiveSpan("drizzle.buildSQL",($)=>{let J=this.buildQueryFromSourceParams(this.queryChunks,T);return $?.setAttributes({"drizzle.query.text":J.sql,"drizzle.query.params":JSON.stringify(J.params)}),J})}buildQueryFromSourceParams(T,$){let J=Object.assign({},$,{inlineParams:$.inlineParams||this.shouldInlineParams,paramStartIndex:$.paramStartIndex||{value:0}}),{casing:W,escapeName:X,escapeParam:F,prepareTyping:Y,inlineParams:G,paramStartIndex:H}=J;return CK(T.map((M)=>{if(L(M,K$))return{sql:M.value.join(""),params:[]};if(L(M,g4))return{sql:X(M.value),params:[]};if(M===void 0)return{sql:"",params:[]};if(Array.isArray(M)){let z=[new K$("(")];for(let[A,w]of M.entries())if(z.push(w),A<M.length-1)z.push(new K$(", "));return z.push(new K$(")")),this.buildQueryFromSourceParams(z,J)}if(L(M,c))return this.buildQueryFromSourceParams(M.queryChunks,{...J,inlineParams:G||M.shouldInlineParams});if(L(M,u)){let z=M[u.Symbol.Schema],A=M[u.Symbol.Name];return{sql:z===void 0||M[q2]?X(A):X(z)+"."+X(A),params:[]}}if(L(M,bT)){let z=W.getColumnCasing(M);if($.invokeSource==="indexes")return{sql:X(z),params:[]};let A=M.table[u.Symbol.Schema];return{sql:M.table[q2]||A===void 0?X(M.table[u.Symbol.Name])+"."+X(z):X(A)+"."+X(M.table[u.Symbol.Name])+"."+X(z),params:[]}}if(L(M,a$)){let z=M[pT].schema,A=M[pT].name;return{sql:z===void 0||M[pT].isAlias?X(A):X(z)+"."+X(A),params:[]}}if(L(M,zJ)){if(L(M.value,i1))return{sql:F(H.value++,M),params:[M],typings:["none"]};let z=M.value===null?null:M.encoder.mapToDriverValue(M.value);if(L(z,c))return this.buildQueryFromSourceParams([z],J);if(G)return{sql:this.mapInlineParam(z,J),params:[]};let A=["none"];if(Y)A=[Y(M.encoder)];return{sql:F(H.value++,z),params:[z],typings:A}}if(L(M,i1))return{sql:F(H.value++,M),params:[M],typings:["none"]};if(L(M,c.Aliased)&&M.fieldAlias!==void 0)return{sql:X(M.fieldAlias),params:[]};if(L(M,D$)){if(M._.isWith)return{sql:X(M._.alias),params:[]};return this.buildQueryFromSourceParams([new K$("("),M._.sql,new K$(") "),new g4(M._.alias)],J)}if(LH(M)){if(M.schema)return{sql:X(M.schema)+"."+X(M.enumName),params:[]};return{sql:X(M.enumName),params:[]}}if(pY(M)){if(M.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([M.getSQL()],J);return this.buildQueryFromSourceParams([new K$("("),M.getSQL(),new K$(")")],J)}if(G)return{sql:this.mapInlineParam(M,J),params:[]};return{sql:F(H.value++,M),params:[M],typings:["none"]}}))}mapInlineParam(T,{escapeString:$}){if(T===null)return"null";if(typeof T==="number"||typeof T==="boolean")return T.toString();if(typeof T==="string")return $(T);if(typeof T==="object"){let J=T.toString();if(J==="[object Object]")return $(JSON.stringify(T));return $(J)}throw new Error("Unexpected param value: "+T)}getSQL(){return this}as(T){if(T===void 0)return this;return new c.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 g4{constructor(T){this.value=T}static[O]="Name";brand;getSQL(){return new c([this])}}function qH(T){return typeof T==="object"&&T!==null&&"mapToDriverValue"in T&&typeof T.mapToDriverValue==="function"}var kH={mapFromDriverValue:(T)=>T},yH={mapToDriverValue:(T)=>T},Kc={...kH,...yH};class zJ{constructor(T,$=yH){this.value=T,this.encoder=$}static[O]="Param";brand;getSQL(){return new c([this])}}function U(T,...$){let J=[];if($.length>0||T.length>0&&T[0]!=="")J.push(new K$(T[0]));for(let[W,X]of $.entries())J.push(X,new K$(T[W+1]));return new c(J)}((T)=>{function $(){return new c([])}T.empty=$;function J(H){return new c(H)}T.fromList=J;function W(H){return new c([new K$(H)])}T.raw=W;function X(H,M){let z=[];for(let[A,w]of H.entries()){if(A>0&&M!==void 0)z.push(M);z.push(w)}return new c(z)}T.join=X;function F(H){return new g4(H)}T.identifier=F;function Y(H){return new i1(H)}T.placeholder=Y;function G(H,M){return new zJ(H,M)}T.param=G})(U||(U={}));((T)=>{class ${constructor(J,W){this.sql=J,this.fieldAlias=W}static[O]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new $(this.sql,this.fieldAlias)}}T.Aliased=$})(c||(c={}));class i1{constructor(T){this.name=T}static[O]="Placeholder";getSQL(){return new c([this])}}function uY(T,$){return T.map((J)=>{if(L(J,i1)){if(!(J.name in $))throw new Error(`No value for placeholder "${J.name}" was provided`);return $[J.name]}if(L(J,zJ)&&L(J.value,i1)){if(!(J.value.name in $))throw new Error(`No value for placeholder "${J.value.name}" was provided`);return J.encoder.mapToDriverValue($[J.value.name])}return J})}var ZK=Symbol.for("drizzle:IsDrizzleView");class a${static[O]="View";[pT];[ZK]=!0;constructor({name:T,schema:$,selectedFields:J,query:W}){this[pT]={name:T,originalName:T,schema:$,selectedFields:J,query:W,isExisting:!W,isAlias:!1}}getSQL(){return new c([this])}}bT.prototype.getSQL=function(){return new c([this])};u.prototype.getSQL=function(){return new c([this])};D$.prototype.getSQL=function(){return new c([this])};class mW{constructor(T){this.table=T}static[O]="ColumnAliasProxyHandler";get(T,$){if($==="table")return this.table;return T[$]}}class k2{constructor(T,$){this.alias=T,this.replaceOriginalName=$}static[O]="TableAliasProxyHandler";get(T,$){if($===u.Symbol.IsAlias)return!0;if($===u.Symbol.Name)return this.alias;if(this.replaceOriginalName&&$===u.Symbol.OriginalName)return this.alias;if($===pT)return{...T[pT],name:this.alias,isAlias:!0};if($===u.Symbol.Columns){let W=T[u.Symbol.Columns];if(!W)return W;let X={};return Object.keys(W).map((F)=>{X[F]=new Proxy(W[F],new mW(new Proxy(T,this)))}),X}let J=T[$];if(L(J,bT))return new Proxy(J,new mW(new Proxy(T,this)));return J}}function p4(T,$){return new Proxy(T,new k2($,!1))}function aJ(T,$){return new Proxy(T,new mW(new Proxy(T.table,new k2($,!1))))}function cY(T,$){return new c.Aliased(y2(T.sql,$),T.fieldAlias)}function y2(T,$){return U.join(T.queryChunks.map((J)=>{if(L(J,bT))return aJ(J,$);if(L(J,c))return y2(J,$);if(L(J,c.Aliased))return cY(J,$);return J}))}class u4 extends Error{static[O]="DrizzleError";constructor({message:T,cause:$}){super(T);this.name="DrizzleError",this.cause=$}}class oY extends u4{static[O]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class IH{static[O]="ConsoleLogWriter";write(T){console.log(T)}}class dY{static[O]="DefaultLogger";writer;constructor(T){this.writer=T?.writer??new IH}logQuery(T,$){let J=$.map((X)=>{try{return JSON.stringify(X)}catch{return String(X)}}),W=J.length?` -- params: [${J.join(", ")}]`:"";this.writer.write(`Query: ${T}${W}`)}}class lY{static[O]="NoopLogger";logQuery(){}}class u${static[O]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(T){return this.then(void 0,T)}finally(T){return this.then(($)=>{return T?.(),$},($)=>{throw T?.(),$})}then(T,$){return this.execute().then(T,$)}}function jH(T,$,J){let W={},X=T.reduce((F,{path:Y,field:G},H)=>{let M;if(L(G,bT))M=G;else if(L(G,c))M=G.decoder;else M=G.sql.decoder;let z=F;for(let[A,w]of Y.entries())if(A<Y.length-1){if(!(w in z))z[w]={};z=z[w]}else{let _=$[H],D=z[w]=_===null?null:M.mapFromDriverValue(_);if(J&&L(G,bT)&&Y.length===2){let S=Y[0];if(!(S in W))W[S]=D===null?B$(G.table):!1;else if(typeof W[S]==="string"&&W[S]!==B$(G.table))W[S]=!1}}return F},{});if(J&&Object.keys(W).length>0){for(let[F,Y]of Object.entries(W))if(typeof Y==="string"&&!J[Y])X[F]=null}return X}function EJ(T,$){return Object.entries(T).reduce((J,[W,X])=>{if(typeof W!=="string")return J;let F=$?[...$,W]:[W];if(L(X,bT)||L(X,c)||L(X,c.Aliased))J.push({path:F,field:X});else if(L(X,u))J.push(...EJ(X[u.Symbol.Columns],F));else J.push(...EJ(X,F));return J},[])}function I2(T,$){let J=Object.keys(T),W=Object.keys($);if(J.length!==W.length)return!1;for(let[X,F]of J.entries())if(F!==W[X])return!1;return!0}function c4(T,$){let J=Object.entries($).filter(([,W])=>W!==void 0).map(([W,X])=>{if(L(X,c)||L(X,bT))return[W,X];else return[W,new zJ(X,T[u.Symbol.Columns][W])]});if(J.length===0)throw new Error("No values to set");return Object.fromEntries(J)}function xH(T,$){for(let J of $)for(let W of Object.getOwnPropertyNames(J.prototype)){if(W==="constructor")continue;Object.defineProperty(T.prototype,W,Object.getOwnPropertyDescriptor(J.prototype,W)||Object.create(null))}}function PH(T){return T[u.Symbol.Columns]}function V1(T){return L(T,D$)?T._.alias:L(T,a$)?T[pT].name:L(T,c)?void 0:T[u.Symbol.IsAlias]?T[u.Symbol.Name]:T[u.Symbol.BaseName]}function VT(T,$){return{name:typeof T==="string"&&T.length>0?T:"",config:typeof T==="object"?T:$}}function bH(T){if(typeof T!=="object"||T===null)return!1;if(T.constructor.name!=="Object")return!1;if("logger"in T){let $=typeof T.logger;if($!=="boolean"&&($!=="object"||typeof T.logger.logQuery!=="function")&&$!=="undefined")return!1;return!0}if("schema"in T){let $=typeof T.schema;if($!=="object"&&$!=="undefined")return!1;return!0}if("casing"in T){let $=typeof T.casing;if($!=="string"&&$!=="undefined")return!1;return!0}if("mode"in T){if(T.mode!=="default"||T.mode!=="planetscale"||T.mode!==void 0)return!1;return!0}if("connection"in T){let $=typeof T.connection;if($!=="string"&&$!=="object"&&$!=="undefined")return!1;return!0}if("client"in T){let $=typeof T.client;if($!=="object"&&$!=="function"&&$!=="undefined")return!1;return!0}if(Object.keys(T).length===0)return!0;return!1}class t1 extends d{static[O]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(T){if(T){let{name:$,...J}=T;this.config.generatedIdentity={type:"always",sequenceName:$,sequenceOptions:J}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(T){if(T){let{name:$,...J}=T;this.config.generatedIdentity={type:"byDefault",sequenceName:$,sequenceOptions:J}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class vH extends t1{static[O]="PgBigInt53Builder";constructor(T){super(T,"number","PgBigInt53")}build(T){return new hH(T,this.config)}}class hH extends P{static[O]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class mH extends t1{static[O]="PgBigInt64Builder";constructor(T){super(T,"bigint","PgBigInt64")}build(T){return new gH(T,this.config)}}class gH extends P{static[O]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(T){return BigInt(T)}}function pH(T,$){let{name:J,config:W}=VT(T,$);if(W.mode==="number")return new vH(J);return new mH(J)}class uH extends d{static[O]="PgBigSerial53Builder";constructor(T){super(T,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new cH(T,this.config)}}class cH extends P{static[O]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class oH extends d{static[O]="PgBigSerial64Builder";constructor(T){super(T,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(T){return new dH(T,this.config)}}class dH extends P{static[O]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(T){return BigInt(T)}}function lH(T,$){let{name:J,config:W}=VT(T,$);if(W.mode==="number")return new uH(J);return new oH(J)}class nH extends d{static[O]="PgBooleanBuilder";constructor(T){super(T,"boolean","PgBoolean")}build(T){return new iH(T,this.config)}}class iH extends P{static[O]="PgBoolean";getSQLType(){return"boolean"}}function j2(T){return new nH(T??"")}class tH extends d{static[O]="PgCharBuilder";constructor(T,$){super(T,"string","PgChar");this.config.length=$.length,this.config.enumValues=$.enum}build(T){return new rH(T,this.config)}}class rH extends P{static[O]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function aH(T,$={}){let{name:J,config:W}=VT(T,$);return new tH(J,W)}class sH extends d{static[O]="PgCidrBuilder";constructor(T){super(T,"string","PgCidr")}build(T){return new eH(T,this.config)}}class eH extends P{static[O]="PgCidr";getSQLType(){return"cidr"}}function TM(T){return new sH(T??"")}class $M extends d{static[O]="PgCustomColumnBuilder";constructor(T,$,J){super(T,"custom","PgCustomColumn");this.config.fieldConfig=$,this.config.customTypeParams=J}build(T){return new JM(T,this.config)}}class JM extends P{static[O]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(T,$){super(T,$);this.sqlName=$.customTypeParams.dataType($.fieldConfig),this.mapTo=$.customTypeParams.toDriver,this.mapFrom=$.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(T){return typeof this.mapFrom==="function"?this.mapFrom(T):T}mapToDriverValue(T){return typeof this.mapTo==="function"?this.mapTo(T):T}}function WM(T){return($,J)=>{let{name:W,config:X}=VT($,J);return new $M(W,X,T)}}class E1 extends d{static[O]="PgDateColumnBaseBuilder";defaultNow(){return this.default(U`now()`)}}class XM extends E1{static[O]="PgDateBuilder";constructor(T){super(T,"date","PgDate")}build(T){return new o4(T,this.config)}}class o4 extends P{static[O]="PgDate";getSQLType(){return"date"}mapFromDriverValue(T){return new Date(T)}mapToDriverValue(T){return T.toISOString()}}class FM extends E1{static[O]="PgDateStringBuilder";constructor(T){super(T,"string","PgDateString")}build(T){return new d4(T,this.config)}}class d4 extends P{static[O]="PgDateString";getSQLType(){return"date"}}function YM(T,$){let{name:J,config:W}=VT(T,$);if(W?.mode==="date")return new XM(J);return new FM(J)}class GM extends d{static[O]="PgDoublePrecisionBuilder";constructor(T){super(T,"number","PgDoublePrecision")}build(T){return new HM(T,this.config)}}class HM extends P{static[O]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseFloat(T);return T}}function MM(T){return new GM(T??"")}class zM extends d{static[O]="PgInetBuilder";constructor(T){super(T,"string","PgInet")}build(T){return new AM(T,this.config)}}class AM extends P{static[O]="PgInet";getSQLType(){return"inet"}}function wM(T){return new zM(T??"")}class QM extends t1{static[O]="PgIntegerBuilder";constructor(T){super(T,"number","PgInteger")}build(T){return new OM(T,this.config)}}class OM extends P{static[O]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseInt(T);return T}}function l4(T){return new QM(T??"")}class UM extends d{static[O]="PgIntervalBuilder";constructor(T,$){super(T,"string","PgInterval");this.config.intervalConfig=$}build(T){return new _M(T,this.config)}}class _M extends P{static[O]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let T=this.fields?` ${this.fields}`:"",$=this.precision?`(${this.precision})`:"";return`interval${T}${$}`}}function DM(T,$={}){let{name:J,config:W}=VT(T,$);return new UM(J,W)}class KM extends d{static[O]="PgJsonBuilder";constructor(T){super(T,"json","PgJson")}build(T){return new n4(T,this.config)}}class n4 extends P{static[O]="PgJson";constructor(T,$){super(T,$)}getSQLType(){return"json"}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){if(typeof T==="string")try{return JSON.parse(T)}catch{return T}return T}}function SM(T){return new KM(T??"")}class VM extends d{static[O]="PgJsonbBuilder";constructor(T){super(T,"json","PgJsonb")}build(T){return new i4(T,this.config)}}class i4 extends P{static[O]="PgJsonb";constructor(T,$){super(T,$)}getSQLType(){return"jsonb"}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){if(typeof T==="string")try{return JSON.parse(T)}catch{return T}return T}}function EM(T){return new VM(T??"")}class RM extends d{static[O]="PgLineBuilder";constructor(T){super(T,"array","PgLine")}build(T){return new LM(T,this.config)}}class LM extends P{static[O]="PgLine";getSQLType(){return"line"}mapFromDriverValue(T){let[$,J,W]=T.slice(1,-1).split(",");return[Number.parseFloat($),Number.parseFloat(J),Number.parseFloat(W)]}mapToDriverValue(T){return`{${T[0]},${T[1]},${T[2]}}`}}class BM extends d{static[O]="PgLineABCBuilder";constructor(T){super(T,"json","PgLineABC")}build(T){return new fM(T,this.config)}}class fM extends P{static[O]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(T){let[$,J,W]=T.slice(1,-1).split(",");return{a:Number.parseFloat($),b:Number.parseFloat(J),c:Number.parseFloat(W)}}mapToDriverValue(T){return`{${T.a},${T.b},${T.c}}`}}function NM(T,$){let{name:J,config:W}=VT(T,$);if(!W?.mode||W.mode==="tuple")return new RM(J);return new BM(J)}class CM extends d{static[O]="PgMacaddrBuilder";constructor(T){super(T,"string","PgMacaddr")}build(T){return new ZM(T,this.config)}}class ZM extends P{static[O]="PgMacaddr";getSQLType(){return"macaddr"}}function qM(T){return new CM(T??"")}class kM extends d{static[O]="PgMacaddr8Builder";constructor(T){super(T,"string","PgMacaddr8")}build(T){return new yM(T,this.config)}}class yM extends P{static[O]="PgMacaddr8";getSQLType(){return"macaddr8"}}function IM(T){return new kM(T??"")}class jM extends d{static[O]="PgNumericBuilder";constructor(T,$,J){super(T,"string","PgNumeric");this.config.precision=$,this.config.scale=J}build(T){return new t4(T,this.config)}}class t4 extends P{static[O]="PgNumeric";precision;scale;constructor(T,$){super(T,$);this.precision=$.precision,this.scale=$.scale}mapFromDriverValue(T){if(typeof T==="string")return T;return String(T)}getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}class xM extends d{static[O]="PgNumericNumberBuilder";constructor(T,$,J){super(T,"number","PgNumericNumber");this.config.precision=$,this.config.scale=J}build(T){return new PM(T,this.config)}}class PM extends P{static[O]="PgNumericNumber";precision;scale;constructor(T,$){super(T,$);this.precision=$.precision,this.scale=$.scale}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}mapToDriverValue=String;getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}class bM extends d{static[O]="PgNumericBigIntBuilder";constructor(T,$,J){super(T,"bigint","PgNumericBigInt");this.config.precision=$,this.config.scale=J}build(T){return new vM(T,this.config)}}class vM extends P{static[O]="PgNumericBigInt";precision;scale;constructor(T,$){super(T,$);this.precision=$.precision,this.scale=$.scale}mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}function hM(T,$){let{name:J,config:W}=VT(T,$),X=W?.mode;return X==="number"?new xM(J,W?.precision,W?.scale):X==="bigint"?new bM(J,W?.precision,W?.scale):new jM(J,W?.precision,W?.scale)}class mM extends d{static[O]="PgPointTupleBuilder";constructor(T){super(T,"array","PgPointTuple")}build(T){return new gM(T,this.config)}}class gM extends P{static[O]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){let[$,J]=T.slice(1,-1).split(",");return[Number.parseFloat($),Number.parseFloat(J)]}return[T.x,T.y]}mapToDriverValue(T){return`(${T[0]},${T[1]})`}}class pM extends d{static[O]="PgPointObjectBuilder";constructor(T){super(T,"json","PgPointObject")}build(T){return new uM(T,this.config)}}class uM extends P{static[O]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){let[$,J]=T.slice(1,-1).split(",");return{x:Number.parseFloat($),y:Number.parseFloat(J)}}return T}mapToDriverValue(T){return`(${T.x},${T.y})`}}function cM(T,$){let{name:J,config:W}=VT(T,$);if(!W?.mode||W.mode==="tuple")return new mM(J);return new pM(J)}function qK(T){let $=[];for(let J=0;J<T.length;J+=2)$.push(Number.parseInt(T.slice(J,J+2),16));return new Uint8Array($)}function oM(T,$){let J=new ArrayBuffer(8),W=new DataView(J);for(let X=0;X<8;X++)W.setUint8(X,T[$+X]);return W.getFloat64(0,!0)}function nY(T){let $=qK(T),J=0,W=$[J];J+=1;let X=new DataView($.buffer),F=X.getUint32(J,W===1);J+=4;let Y;if(F&536870912)Y=X.getUint32(J,W===1),J+=4;if((F&65535)===1){let G=oM($,J);J+=8;let H=oM($,J);return J+=8,[G,H]}throw new Error("Unsupported geometry type")}class dM extends d{static[O]="PgGeometryBuilder";constructor(T){super(T,"array","PgGeometry")}build(T){return new lM(T,this.config)}}class lM extends P{static[O]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){return nY(T)}mapToDriverValue(T){return`point(${T[0]} ${T[1]})`}}class nM extends d{static[O]="PgGeometryObjectBuilder";constructor(T){super(T,"json","PgGeometryObject")}build(T){return new iM(T,this.config)}}class iM extends P{static[O]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){let $=nY(T);return{x:$[0],y:$[1]}}mapToDriverValue(T){return`point(${T.x} ${T.y})`}}function tM(T,$){let{name:J,config:W}=VT(T,$);if(!W?.mode||W.mode==="tuple")return new dM(J);return new nM(J)}class rM extends d{static[O]="PgRealBuilder";constructor(T,$){super(T,"number","PgReal");this.config.length=$}build(T){return new aM(T,this.config)}}class aM extends P{static[O]="PgReal";constructor(T,$){super(T,$)}getSQLType(){return"real"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number.parseFloat(T);return T}}function sM(T){return new rM(T??"")}class eM extends d{static[O]="PgSerialBuilder";constructor(T){super(T,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new Tz(T,this.config)}}class Tz extends P{static[O]="PgSerial";getSQLType(){return"serial"}}function $z(T){return new eM(T??"")}class Jz extends t1{static[O]="PgSmallIntBuilder";constructor(T){super(T,"number","PgSmallInt")}build(T){return new Wz(T,this.config)}}class Wz extends P{static[O]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number(T);return T}}function Xz(T){return new Jz(T??"")}class Fz extends d{static[O]="PgSmallSerialBuilder";constructor(T){super(T,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new Yz(T,this.config)}}class Yz extends P{static[O]="PgSmallSerial";getSQLType(){return"smallserial"}}function Gz(T){return new Fz(T??"")}class Hz extends d{static[O]="PgTextBuilder";constructor(T,$){super(T,"string","PgText");this.config.enumValues=$.enum}build(T){return new Mz(T,this.config)}}class Mz extends P{static[O]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function zz(T,$={}){let{name:J,config:W}=VT(T,$);return new Hz(J,W)}class Az extends E1{constructor(T,$,J){super(T,"string","PgTime");this.withTimezone=$,this.precision=J,this.config.withTimezone=$,this.config.precision=J}static[O]="PgTimeBuilder";build(T){return new r4(T,this.config)}}class r4 extends P{static[O]="PgTime";withTimezone;precision;constructor(T,$){super(T,$);this.withTimezone=$.withTimezone,this.precision=$.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function wz(T,$={}){let{name:J,config:W}=VT(T,$);return new Az(J,W.withTimezone??!1,W.precision)}class Qz extends E1{static[O]="PgTimestampBuilder";constructor(T,$,J){super(T,"date","PgTimestamp");this.config.withTimezone=$,this.config.precision=J}build(T){return new a4(T,this.config)}}class a4 extends P{static[O]="PgTimestamp";withTimezone;precision;constructor(T,$){super(T,$);this.withTimezone=$.withTimezone,this.precision=$.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(T)=>{return new Date(this.withTimezone?T:T+"+0000")};mapToDriverValue=(T)=>{return T.toISOString()}}class Oz extends E1{static[O]="PgTimestampStringBuilder";constructor(T,$,J){super(T,"string","PgTimestampString");this.config.withTimezone=$,this.config.precision=J}build(T){return new s4(T,this.config)}}class s4 extends P{static[O]="PgTimestampString";withTimezone;precision;constructor(T,$){super(T,$);this.withTimezone=$.withTimezone,this.precision=$.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function bJ(T,$={}){let{name:J,config:W}=VT(T,$);if(W?.mode==="string")return new Oz(J,W.withTimezone??!1,W.precision);return new Qz(J,W?.withTimezone??!1,W?.precision)}class Uz extends d{static[O]="PgUUIDBuilder";constructor(T){super(T,"string","PgUUID")}defaultRandom(){return this.default(U`gen_random_uuid()`)}build(T){return new e4(T,this.config)}}class e4 extends P{static[O]="PgUUID";getSQLType(){return"uuid"}}function AJ(T){return new Uz(T??"")}class _z extends d{static[O]="PgVarcharBuilder";constructor(T,$){super(T,"string","PgVarchar");this.config.length=$.length,this.config.enumValues=$.enum}build(T){return new Dz(T,this.config)}}class Dz extends P{static[O]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function P$(T,$={}){let{name:J,config:W}=VT(T,$);return new _z(J,W)}class Kz extends d{static[O]="PgBinaryVectorBuilder";constructor(T,$){super(T,"string","PgBinaryVector");this.config.dimensions=$.dimensions}build(T){return new Sz(T,this.config)}}class Sz extends P{static[O]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function Vz(T,$){let{name:J,config:W}=VT(T,$);return new Kz(J,W)}class Ez extends d{static[O]="PgHalfVectorBuilder";constructor(T,$){super(T,"array","PgHalfVector");this.config.dimensions=$.dimensions}build(T){return new Rz(T,this.config)}}class Rz extends P{static[O]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){return T.slice(1,-1).split(",").map(($)=>Number.parseFloat($))}}function Lz(T,$){let{name:J,config:W}=VT(T,$);return new Ez(J,W)}class Bz extends d{static[O]="PgSparseVectorBuilder";constructor(T,$){super(T,"string","PgSparseVector");this.config.dimensions=$.dimensions}build(T){return new fz(T,this.config)}}class fz extends P{static[O]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function Nz(T,$){let{name:J,config:W}=VT(T,$);return new Bz(J,W)}class Cz extends d{static[O]="PgVectorBuilder";constructor(T,$){super(T,"array","PgVector");this.config.dimensions=$.dimensions}build(T){return new Zz(T,this.config)}}class Zz extends P{static[O]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){return T.slice(1,-1).split(",").map(($)=>Number.parseFloat($))}}function qz(T,$){let{name:J,config:W}=VT(T,$);return new Cz(J,W)}function kz(){return{bigint:pH,bigserial:lH,boolean:j2,char:aH,cidr:TM,customType:WM,date:YM,doublePrecision:MM,inet:wM,integer:l4,interval:DM,json:SM,jsonb:EM,line:NM,macaddr:qM,macaddr8:IM,numeric:hM,point:cM,geometry:tM,real:sM,serial:$z,smallint:Xz,smallserial:Gz,text:zz,time:wz,timestamp:bJ,uuid:AJ,varchar:P$,bit:Vz,halfvec:Lz,sparsevec:Nz,vector:qz}}var iY=Symbol.for("drizzle:PgInlineForeignKeys"),yz=Symbol.for("drizzle:EnableRLS");class Z$ extends u{static[O]="PgTable";static Symbol=Object.assign({},u.Symbol,{InlineForeignKeys:iY,EnableRLS:yz});[iY]=[];[yz]=!1;[u.Symbol.ExtraConfigBuilder]=void 0;[u.Symbol.ExtraConfigColumns]={}}function kK(T,$,J,W,X=T){let F=new Z$(T,W,X),Y=typeof $==="function"?$(kz()):$,G=Object.fromEntries(Object.entries(Y).map(([z,A])=>{let w=A;w.setName(z);let _=w.build(F);return F[iY].push(...w.buildForeignKeys(_,F)),[z,_]})),H=Object.fromEntries(Object.entries(Y).map(([z,A])=>{let w=A;w.setName(z);let _=w.buildExtraConfigColumn(F);return[z,_]})),M=Object.assign(F,G);if(M[u.Symbol.Columns]=G,M[u.Symbol.ExtraConfigColumns]=H,J)M[Z$.Symbol.ExtraConfigBuilder]=J;return Object.assign(M,{enableRLS:()=>{return M[Z$.Symbol.EnableRLS]=!0,M}})}var r1=(T,$,J)=>{return kK(T,$,J,void 0)};function Iz(...T){if(T[0].columns)return new x2(T[0].columns,T[0].name);return new x2(T)}class x2{static[O]="PgPrimaryKeyBuilder";columns;name;constructor(T,$){this.columns=T,this.name=$}build(T){return new jz(T,this.columns,this.name)}}class jz{constructor(T,$,J){this.table=T,this.columns=$,this.name=J}static[O]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[Z$.Symbol.Name]}_${this.columns.map((T)=>T.name).join("_")}_pk`}}function s$(T,$){if(qH($)&&!pY(T)&&!L(T,zJ)&&!L(T,i1)&&!L(T,bT)&&!L(T,u)&&!L(T,a$))return new zJ(T,$);return T}var T6=(T,$)=>{return U`${T} = ${s$($,T)}`},xz=(T,$)=>{return U`${T} <> ${s$($,T)}`};function P2(...T){let $=T.filter((J)=>J!==void 0);if($.length===0)return;if($.length===1)return new c($);return new c([new K$("("),U.join($,new K$(" and ")),new K$(")")])}function Pz(...T){let $=T.filter((J)=>J!==void 0);if($.length===0)return;if($.length===1)return new c($);return new c([new K$("("),U.join($,new K$(" or ")),new K$(")")])}function bz(T){return U`not ${T}`}var $6=(T,$)=>{return U`${T} > ${s$($,T)}`},vz=(T,$)=>{return U`${T} >= ${s$($,T)}`},hz=(T,$)=>{return U`${T} < ${s$($,T)}`},mz=(T,$)=>{return U`${T} <= ${s$($,T)}`};function gz(T,$){if(Array.isArray($)){if($.length===0)return U`false`;return U`${T} in ${$.map((J)=>s$(J,T))}`}return U`${T} in ${s$($,T)}`}function pz(T,$){if(Array.isArray($)){if($.length===0)return U`true`;return U`${T} not in ${$.map((J)=>s$(J,T))}`}return U`${T} not in ${s$($,T)}`}function uz(T){return U`${T} is null`}function cz(T){return U`${T} is not null`}function oz(T){return U`exists ${T}`}function dz(T){return U`not exists ${T}`}function lz(T,$,J){return U`${T} between ${s$($,T)} and ${s$(J,T)}`}function nz(T,$,J){return U`${T} not between ${s$($,T)} and ${s$(J,T)}`}function iz(T,$){return U`${T} like ${$}`}function tz(T,$){return U`${T} not like ${$}`}function rz(T,$){return U`${T} ilike ${$}`}function az(T,$){return U`${T} not ilike ${$}`}function sz(T){return U`${T} asc`}function ez(T){return U`${T} desc`}class tY{constructor(T,$,J){this.sourceTable=T,this.referencedTable=$,this.relationName=J,this.referencedTableName=$[u.Symbol.Name]}static[O]="Relation";referencedTableName;fieldName}class TA{constructor(T,$){this.table=T,this.config=$}static[O]="Relations"}class a1 extends tY{constructor(T,$,J,W){super(T,$,J?.relationName);this.config=J,this.isNullable=W}static[O]="One";withFieldName(T){let $=new a1(this.sourceTable,this.referencedTable,this.config,this.isNullable);return $.fieldName=T,$}}class b2 extends tY{constructor(T,$,J){super(T,$,J?.relationName);this.config=J}static[O]="Many";withFieldName(T){let $=new b2(this.sourceTable,this.referencedTable,this.config);return $.fieldName=T,$}}function $A(){return{and:P2,between:lz,eq:T6,exists:oz,gt:$6,gte:vz,ilike:rz,inArray:gz,isNull:uz,isNotNull:cz,like:iz,lt:hz,lte:mz,ne:xz,not:bz,notBetween:nz,notExists:dz,notLike:tz,notIlike:az,notInArray:pz,or:Pz,sql:U}}function JA(){return{sql:U,asc:sz,desc:ez}}function WA(T,$){if(Object.keys(T).length===1&&"default"in T&&!L(T.default,u))T=T.default;let J={},W={},X={};for(let[F,Y]of Object.entries(T))if(L(Y,u)){let G=h0(Y),H=W[G];J[G]=F,X[F]={tsName:F,dbName:Y[u.Symbol.Name],schema:Y[u.Symbol.Schema],columns:Y[u.Symbol.Columns],relations:H?.relations??{},primaryKey:H?.primaryKey??[]};for(let z of Object.values(Y[u.Symbol.Columns]))if(z.primary)X[F].primaryKey.push(z);let M=Y[u.Symbol.ExtraConfigBuilder]?.(Y[u.Symbol.ExtraConfigColumns]);if(M){for(let z of Object.values(M))if(L(z,x2))X[F].primaryKey.push(...z.columns)}}else if(L(Y,TA)){let G=h0(Y.table),H=J[G],M=Y.config($(Y.table)),z;for(let[A,w]of Object.entries(M))if(H){let _=X[H];if(_.relations[A]=w,z)_.primaryKey.push(...z)}else{if(!(G in W))W[G]={relations:{},primaryKey:z};W[G].relations[A]=w}}return{tables:X,tableNamesMap:J}}function yK(T){return function $(J,W){return new a1(T,J,W,W?.fields.reduce((X,F)=>X&&F.notNull,!0)??!1)}}function IK(T){return function $(J,W){return new b2(T,J,W)}}function XA(T,$,J){if(L(J,a1)&&J.config)return{fields:J.config.fields,references:J.config.references};let W=$[h0(J.referencedTable)];if(!W)throw new Error(`Table "${J.referencedTable[u.Symbol.Name]}" not found in schema`);let X=T[W];if(!X)throw new Error(`Table "${W}" not found in schema`);let F=J.sourceTable,Y=$[h0(F)];if(!Y)throw new Error(`Table "${F[u.Symbol.Name]}" not found in schema`);let G=[];for(let H of Object.values(X.relations))if(J.relationName&&J!==H&&H.relationName===J.relationName||!J.relationName&&H.referencedTable===J.sourceTable)G.push(H);if(G.length>1)throw J.relationName?new Error(`There are multiple relations with name "${J.relationName}" in table "${W}"`):new Error(`There are multiple relations between "${W}" and "${J.sourceTable[u.Symbol.Name]}". Please specify relation name`);if(G[0]&&L(G[0],a1)&&G[0].config)return{fields:G[0].config.references,references:G[0].config.fields};throw new Error(`There is not enough information to infer relation "${Y}.${J.fieldName}"`)}function FA(T){return{one:yK(T),many:IK(T)}}function J6(T,$,J,W,X=(F)=>F){let F={};for(let[Y,G]of W.entries())if(G.isJson){let H=$.relations[G.tsKey],M=J[Y],z=typeof M==="string"?JSON.parse(M):M;F[G.tsKey]=L(H,a1)?z&&J6(T,T[G.relationTableTsKey],z,G.selection,X):z.map((A)=>J6(T,T[G.relationTableTsKey],A,G.selection,X))}else{let H=X(J[Y]),M=G.field,z;if(L(M,bT))z=M;else if(L(M,c))z=M.decoder;else z=M.sql.decoder;F[G.tsKey]=H===null?null:z.mapFromDriverValue(H)}return F}import VL from"path";import JS from"os";import WS from"fs";var W6=new Map,rY=new Map,aY=Symbol("OriginError"),gW={};class RJ extends Promise{constructor(T,$,J,W,X={}){let F,Y;super((G,H)=>{F=G,Y=H});this.tagged=Array.isArray(T.raw),this.strings=T,this.args=$,this.handler=J,this.canceller=W,this.options=X,this.state=null,this.statement=null,this.resolve=(G)=>(this.active=!1,F(G)),this.reject=(G)=>(this.active=!1,Y(G)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[aY]=this.handler.debug?new Error:this.tagged&&jK(this.strings)}get origin(){return(this.handler.debug?this[aY].stack:this.tagged&&rY.has(this.strings)?rY.get(this.strings):rY.set(this.strings,this[aY].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(T=1,$){if(this.options.simple=!1,typeof T==="function")$=T,T=1;if(this.cursorRows=T,typeof $==="function")return this.cursorFn=$,this;let J;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};J&&J();let W=new Promise((X,F)=>{this.cursorFn=(Y)=>{return X({value:Y,done:!1}),new Promise((G)=>J=G)},this.resolve=()=>(this.active=!1,X({done:!0})),this.reject=(Y)=>(this.active=!1,F(Y))});return this.execute(),W},return(){return J&&J(gW),{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 jK(T){if(W6.has(T))return W6.get(T);let $=Error.stackTraceLimit;return Error.stackTraceLimit=4,W6.set(T,new Error),Error.stackTraceLimit=$,W6.get(T)}class pW extends Error{constructor(T){super(T.message);this.name=this.constructor.name,Object.assign(this,T)}}var G$={connection:YA,postgres:GA,generic:HA,notSupported:MA};function YA(T,$,J){let{host:W,port:X}=J||$,F=Object.assign(new Error("write "+T+" "+($.path||W+":"+X)),{code:T,errno:T,address:$.path||W},$.path?{}:{port:X});return Error.captureStackTrace(F,YA),F}function GA(T){let $=new pW(T);return Error.captureStackTrace($,GA),$}function HA(T,$){let J=Object.assign(new Error(T+": "+$),{code:T});return Error.captureStackTrace(J,HA),J}function MA(T){let $=Object.assign(new Error(T+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:T});return Error.captureStackTrace($,MA),$}var xK={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 Y6{then(){sY()}catch(){sY()}finally(){sY()}}class g2 extends Y6{constructor(T){super();this.value=M6(T)}}class sJ extends Y6{constructor(T,$,J){super();this.value=T,this.type=$,this.array=J}}class G6 extends Y6{constructor(T,$){super();this.first=T,this.rest=$}build(T,$,J,W){let X=PK.map(([F,Y])=>({fn:Y,i:T.search(F)})).sort((F,Y)=>F.i-Y.i).pop();return X.i===-1?W9(this.first,W):X.fn(this.first,this.rest,$,J,W)}}function H6(T,$,J,W){let X=T instanceof sJ?T.value:T;if(X===void 0){if(T instanceof sJ?T.value=W.transform.undefined:X=T=W.transform.undefined,X===void 0)throw G$.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+J.push(T instanceof sJ?($.push(T.value),T.array?T.array[T.type||F6(T.value)]||T.type||QA(T.value):T.type):($.push(T),F6(T)))}var AA=UA(xK);function $9(T,$,J,W,X,F){for(let Y=1;Y<T.strings.length;Y++)$+=J9($,J,W,X,F)+T.strings[Y],J=T.args[Y];return $}function J9(T,$,J,W,X){return $ instanceof G6?$.build(T,J,W,X):$ instanceof RJ?T9($,J,W,X):$ instanceof g2?$.value:$&&$[0]instanceof RJ?$.reduce((F,Y)=>F+" "+T9(Y,J,W,X),""):H6($,J,W,X)}function T9(T,$,J,W){return T.fragment=!0,$9(T,T.strings[0],T.args[0],$,J,W)}function wA(T,$,J,W,X){return T.map((F)=>"("+W.map((Y)=>J9("values",F[Y],$,J,X)).join(",")+")").join(",")}function zA(T,$,J,W,X){let F=Array.isArray(T[0]),Y=$.length?$.flat():Object.keys(F?T[0]:T);return wA(F?T:[T],J,W,Y,X)}function X6(T,$,J,W,X){if(typeof T==="string"&&(T=[T].concat($)),Array.isArray(T))return W9(T,X);let F;return($.length?$.flat():Object.keys(T)).map((G)=>{return F=T[G],(F instanceof RJ?T9(F,J,W,X):F instanceof g2?F.value:H6(F,J,W,X))+" as "+M6(X.transform.column.to?X.transform.column.to(G):G)}).join(",")}var PK=Object.entries({values:zA,in:(...T)=>{let $=zA(...T);return $==="()"?"(null)":$},select:X6,as:X6,returning:X6,"\\(":X6,update(T,$,J,W,X){return($.length?$.flat():Object.keys(T)).map((F)=>M6(X.transform.column.to?X.transform.column.to(F):F)+"="+J9("values",T[F],J,W,X))},insert(T,$,J,W,X){let F=$.length?$.flat():Object.keys(Array.isArray(T)?T[0]:T);return"("+W9(F,X)+")values"+wA(Array.isArray(T)?T:[T],J,W,F,X)}}).map(([T,$])=>[new RegExp("((?:^|[\\s(])"+T+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),$]);function sY(){throw G$.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:bK,parsers:vK}=AA;function QA(T){if(Array.isArray(T))return QA(T[0]);return typeof T==="string"?1009:0}var OA=function(T){let $=UA(T||{});return{serializers:Object.assign({},bK,$.serializers),parsers:Object.assign({},vK,$.parsers)}};function UA(T){return Object.keys(T).reduce(($,J)=>{if(T[J].from&&[].concat(T[J].from).forEach((W)=>$.parsers[W]=T[J].parse),T[J].serialize)$.serializers[T[J].to]=T[J].serialize,T[J].from&&[].concat(T[J].from).forEach((W)=>$.serializers[W]=T[J].serialize);return $},{parsers:{},serializers:{}})}function W9(T,{transform:{column:$}}){return T.map((J)=>M6($.to?$.to(J):J)).join(",")}var M6=function T($){return'"'+$.replace(/"/g,'""').replace(/\./g,'"."')+'"'},F6=function T($){return $ instanceof sJ?$.type:$ instanceof Date?1184:$ instanceof Uint8Array?17:$===!0||$===!1?16:typeof $==="bigint"?20:Array.isArray($)?T($[0]):0},hK=/\\/g,mK=/"/g;function gK(T){return T.replace(hK,"\\\\").replace(mK,"\\\"")}var _A=function T($,J,W,X){if(Array.isArray($)===!1)return $;if(!$.length)return"{}";let F=$[0],Y=X===1020?";":",";if(Array.isArray(F)&&!F.type)return"{"+$.map((G)=>T(G,J,W,X)).join(Y)+"}";return"{"+$.map((G)=>{if(G===void 0){if(G=W.transform.undefined,G===void 0)throw G$.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return G===null?"null":'"'+gK(J?J(G.type?G.value:G):""+G)+'"'}).join(Y)+"}"},eY={i:0,char:null,str:"",quoted:!1,last:0},DA=function T($,J,W){return eY.i=eY.last=0,KA(eY,$,J,W)};function KA(T,$,J,W){let X=[],F=W===1020?";":",";for(;T.i<$.length;T.i++){if(T.char=$[T.i],T.quoted)if(T.char==="\\")T.str+=$[++T.i];else if(T.char==='"')X.push(J?J(T.str):T.str),T.str="",T.quoted=$[T.i+1]==='"',T.last=T.i+2;else T.str+=T.char;else if(T.char==='"')T.quoted=!0;else if(T.char==="{")T.last=++T.i,X.push(KA(T,$,J,W));else if(T.char==="}"){T.quoted=!1,T.last<T.i&&X.push(J?J($.slice(T.last,T.i)):$.slice(T.last,T.i)),T.last=T.i+1;break}else if(T.char===F&&T.p!=="}"&&T.p!=='"')X.push(J?J($.slice(T.last,T.i)):$.slice(T.last,T.i)),T.last=T.i+1;T.p=T.char}return T.last<T.i&&X.push(J?J($.slice(T.last,T.i+1)):$.slice(T.last,T.i+1)),X}var m0=(T)=>{let $=T[0];for(let J=1;J<T.length;J++)$+=T[J]==="_"?T[++J].toUpperCase():T[J];return $},g0=(T)=>{let $=T[0].toUpperCase();for(let J=1;J<T.length;J++)$+=T[J]==="_"?T[++J].toUpperCase():T[J];return $},p0=(T)=>T.replace(/_/g,"-"),v2=(T)=>T.replace(/([A-Z])/g,"_$1").toLowerCase(),h2=(T)=>(T.slice(0,1)+T.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),m2=(T)=>T.replace(/-/g,"_");function X9(T){return function $(J,W){return typeof J==="object"&&J!==null&&(W.type===114||W.type===3802)?Array.isArray(J)?J.map((X)=>$(X,W)):Object.entries(J).reduce((X,[F,Y])=>Object.assign(X,{[T(F)]:$(Y,W)}),{}):J}}m0.column={from:m0};m0.value={from:X9(m0)};v2.column={to:v2};var F9={...m0};F9.column.to=v2;g0.column={from:g0};g0.value={from:X9(g0)};h2.column={to:h2};var Y9={...g0};Y9.column.to=h2;p0.column={from:p0};p0.value={from:X9(p0)};m2.column={to:m2};var G9={...p0};G9.column.to=m2;import SA from"net";import oK from"tls";import p2 from"crypto";import H9 from"stream";import{performance as VA}from"perf_hooks";class u0 extends Array{constructor(){super();Object.defineProperties(this,{count:{value:null,writable:!0},state:{value:null,writable:!0},command:{value:null,writable:!0},columns:{value:null,writable:!0},statement:{value:null,writable:!0}})}static get[Symbol.species](){return Array}}var wJ=pK;function pK(T=[]){let $=T.slice(),J=0;return{get length(){return $.length-J},remove:(W)=>{let X=$.indexOf(W);return X===-1?null:($.splice(X,1),W)},push:(W)=>($.push(W),W),shift:()=>{let W=$[J++];if(J===$.length)J=0,$=[];else $[J-1]=void 0;return W}}}var b$=Buffer.allocUnsafe(256),uK="BCcDdEFfHPpQSX".split("").reduce((T,$)=>{let J=$.charCodeAt(0);return T[$]=()=>{return b$[0]=J,xT.i=5,xT},T},{}),xT=Object.assign(cK,uK,{N:String.fromCharCode(0),i:0,inc(T){return xT.i+=T,xT},str(T){let $=Buffer.byteLength(T);return z6($),xT.i+=b$.write(T,xT.i,$,"utf8"),xT},i16(T){return z6(2),b$.writeUInt16BE(T,xT.i),xT.i+=2,xT},i32(T,$){if($||$===0)return b$.writeUInt32BE(T,$),xT;return z6(4),b$.writeUInt32BE(T,xT.i),xT.i+=4,xT},z(T){return z6(T),b$.fill(0,xT.i,xT.i+T),xT.i+=T,xT},raw(T){return b$=Buffer.concat([b$.subarray(0,xT.i),T]),xT.i=b$.length,xT},end(T=1){b$.writeUInt32BE(xT.i-T,T);let $=b$.subarray(0,xT.i);return xT.i=0,b$=Buffer.allocUnsafe(256),$}}),s=xT;function z6(T){if(b$.length-xT.i<T){let $=b$,J=$.length;b$=Buffer.allocUnsafe(J+(J>>1)+T),$.copy(b$)}}function cK(){return xT.i=0,xT}var A9=LA,dK=1,s1=s().S().end(),EA=s().H().end(),lK=s().i32(8).i32(80877103).end(8),nK=Buffer.concat([s().E().str(s.N).i32(0).end(),s1]),iK=s().D().str("S").str(s.N).end(),uW=()=>{},tK=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),rK={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 LA(T,$={},{onopen:J=uW,onend:W=uW,onclose:X=uW}={}){let{ssl:F,max:Y,user:G,host:H,port:M,database:z,parsers:A,transform:w,onnotice:_,onnotify:D,onparameter:S,max_pipeline:Z,keep_alive:q,backoff:N,target_session_attrs:y}=T,V=wJ(),f=dK++,C={pid:null,secret:null},B=z9(e6,T.idle_timeout),m=z9(e6,T.max_lifetime),$T=z9(MU,T.connect_timeout),E=null,XT,n=new u0,MT=Buffer.alloc(0),kT=T.fetch_types,eT={},l$={},J1=Math.random().toString(36).slice(2),I=1,a=0,NT=0,tT=0,M$=0,UT=0,mT=0,X$=0,rT=null,oT=null,q$=!1,gT=null,CJ=null,k$=null,x1=null,z$=null,dT=null,ZJ=null,pJ=null,h=null,AX=null,y$={queue:$.closed,idleTimer:B,connect(Q){k$=Q||!0,$7()},terminate:QX,execute:wX,cancel:FU,end:e6,count:0,id:f};return $.closed&&$.closed.push(y$),y$;async function XU(){let Q;try{Q=T.socket?await Promise.resolve(T.socket(T)):new SA.Socket}catch(K){s0(K);return}return Q.on("error",s0),Q.on("close",J7),Q.on("drain",e5),Q}async function FU({pid:Q,secret:K},TT,CT){try{XT=s().i32(16).i32(80877102).i32(Q).i32(K).end(16),await T7(),E.once("error",CT),E.once("close",TT)}catch(T$){CT(T$)}}function wX(Q){if(q$)return L8(Q,G$.connection("CONNECTION_DESTROYED",T));if(Q.cancelled)return;try{return Q.state=C,h?V.push(Q):(h=Q,h.active=!0),HU(Q),f$(YU(Q))&&!Q.describeFirst&&!Q.cursorFn&&V.length<Z&&(!Q.options.onexecute||Q.options.onexecute(y$))}catch(K){return V.length===0&&f$(s1),uJ(K),!0}}function YU(Q){if(Q.parameters.length>=65534)throw G$.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return Q.options.simple?s().Q().str(Q.statement.string+s.N).end():Q.describeFirst?Buffer.concat([r5(Q),EA]):Q.prepare?Q.prepared?R8(Q):Buffer.concat([r5(Q),R8(Q)]):GU(Q)}function r5(Q){return Buffer.concat([X7(Q.statement.string,Q.parameters,Q.statement.types,Q.statement.name),nU("S",Q.statement.name)])}function R8(Q){return Buffer.concat([lU(Q.parameters,Q.statement.types,Q.statement.name,Q.cursorName),Q.cursorFn?F7("",Q.cursorRows):nK])}function GU(Q){return Buffer.concat([X7(Q.statement.string,Q.parameters,Q.statement.types),iK,R8(Q)])}function HU(Q){let K=[],TT=[],CT=$9(Q,Q.strings[0],Q.args[0],K,TT,T);!Q.tagged&&Q.args.forEach((T$)=>H6(T$,K,TT,T)),Q.prepare=T.prepare&&("prepare"in Q.options?Q.options.prepare:!0),Q.string=CT,Q.signature=Q.prepare&&TT+CT,Q.onlyDescribe&&delete l$[Q.signature],Q.parameters=Q.parameters||K,Q.prepared=Q.prepare&&Q.signature in l$,Q.describeFirst=Q.onlyDescribe||K.length&&!Q.prepared,Q.statement=Q.prepared?l$[Q.signature]:{string:CT,types:TT,name:Q.prepare?J1+I++:""},typeof T.debug==="function"&&T.debug(f,CT,K,TT)}function f$(Q,K){if(dT=dT?Buffer.concat([dT,Q]):Buffer.from(Q),K||dT.length>=1024)return a5(K);return oT===null&&(oT=setImmediate(a5)),!0}function a5(Q){let K=E.write(dT,Q);return oT!==null&&clearImmediate(oT),dT=oT=null,K}function MU(){uJ(G$.connection("CONNECT_TIMEOUT",T,E)),E.destroy()}async function s5(){if(f$(lK),!await new Promise((K)=>E.once("data",(TT)=>K(TT[0]===83)))&&F==="prefer")return a0();E.removeAllListeners(),E=oK.connect({socket:E,servername:SA.isIP(E.host)?void 0:E.host,...F==="require"||F==="allow"||F==="prefer"?{rejectUnauthorized:!1}:F==="verify-full"?{}:typeof F==="object"?F:{}}),E.on("secureConnect",a0),E.on("error",s0),E.on("close",J7),E.on("drain",e5)}function e5(){!h&&J(y$)}function s6(Q){if(gT){if(gT.push(Q),NT-=Q.length,NT>=0)return}MT=gT?Buffer.concat(gT,UT-NT):MT.length===0?Q:Buffer.concat([MT,Q],MT.length+Q.length);while(MT.length>4){if(UT=MT.readUInt32BE(1),UT>=MT.length){NT=UT-MT.length,gT=[MT];break}try{zU(MT.subarray(0,UT+1))}catch(K){h&&(h.cursorFn||h.describeFirst)&&f$(s1),uJ(K)}MT=MT.subarray(UT+1),NT=0,gT=null}}async function T7(){if(q$=!1,eT={},E||(E=await XU()),!E)return;if($T.start(),T.socket)return F?s5():a0();if(E.on("connect",F?s5:a0),T.path)return E.connect(T.path);E.ssl=F,E.connect(M[tT],H[tT]),E.host=H[tT],E.port=M[tT],tT=(tT+1)%M.length}function $7(){setTimeout(T7,a?a+mT-VA.now():0)}function a0(){try{l$={},kT=T.fetch_types,J1=Math.random().toString(36).slice(2),I=1,m.start(),E.on("data",s6),q&&E.setKeepAlive&&E.setKeepAlive(!0,1000*q);let Q=tU();f$(Q)}catch(Q){s0(Q)}}function s0(Q){if(y$.queue===$.connecting&&T.host[M$+1])return;uJ(Q);while(V.length)L8(V.shift(),Q)}function uJ(Q){z$&&(z$.destroy(Q),z$=null),h&&L8(h,Q),k$&&(L8(k$,Q),k$=null)}function L8(Q,K){"query"in K||"parameters"in K||Object.defineProperties(K,{stack:{value:K.stack+Q.origin.replace(/.*\n/,`
68
- `),enumerable:T.debug},query:{value:Q.string,enumerable:T.debug},parameters:{value:Q.parameters,enumerable:T.debug},args:{value:Q.args,enumerable:T.debug},types:{value:Q.statement&&Q.statement.types,enumerable:T.debug}}),Q.reject(K)}function e6(){return x1||(!y$.reserved&&W(y$),!y$.reserved&&!k$&&!h&&V.length===0?(QX(),new Promise((Q)=>E&&E.readyState!=="closed"?E.once("close",Q):Q())):x1=new Promise((Q)=>ZJ=Q))}function QX(){if(q$=!0,z$||h||k$||V.length)s0(G$.connection("CONNECTION_DESTROYED",T));if(clearImmediate(oT),E)E.removeListener("data",s6),E.removeListener("connect",a0),E.readyState==="open"&&E.end(s().X().end());ZJ&&(ZJ(),x1=ZJ=null)}async function J7(Q){if(MT=Buffer.alloc(0),NT=0,gT=null,clearImmediate(oT),E.removeListener("data",s6),E.removeListener("connect",a0),B.cancel(),m.cancel(),$T.cancel(),E.removeAllListeners(),E=null,k$)return $7();!Q&&(h||V.length)&&s0(G$.connection("CONNECTION_CLOSED",T,E)),a=VA.now(),Q&&T.shared.retries++,mT=(typeof N==="function"?N(T.shared.retries):N)*1000,X(y$,G$.connection("CONNECTION_CLOSED",T,E))}function zU(Q,K=Q[0]){(K===68?AU:K===100?hU:K===65?IU:K===83?wU:K===90?QU:K===67?OU:K===50?W7:K===49?UU:K===116?_U:K===84?DU:K===82?KU:K===110?BU:K===75?fU:K===69?kU:K===115?jU:K===51?xU:K===71?PU:K===78?gU:K===72?bU:K===99?mU:K===73?pU:K===86?uU:K===118?cU:K===87?vU:oU)(Q)}function AU(Q){let K=7,TT,CT,T$,I$=h.isRaw?new Array(h.statement.columns.length):{};for(let m$=0;m$<h.statement.columns.length;m$++)CT=h.statement.columns[m$],TT=Q.readInt32BE(K),K+=4,T$=TT===-1?null:h.isRaw===!0?Q.subarray(K,K+=TT):CT.parser===void 0?Q.toString("utf8",K,K+=TT):CT.parser.array===!0?CT.parser(Q.toString("utf8",K+1,K+=TT)):CT.parser(Q.toString("utf8",K,K+=TT)),h.isRaw?I$[m$]=h.isRaw===!0?T$:w.value.from?w.value.from(T$,CT):T$:I$[CT.name]=w.value.from?w.value.from(T$,CT):T$;h.forEachFn?h.forEachFn(w.row.from?w.row.from(I$):I$,n):n[X$++]=w.row.from?w.row.from(I$):I$}function wU(Q){let[K,TT]=Q.toString("utf8",5,Q.length-1).split(s.N);if(eT[K]=TT,T.parameters[K]!==TT)T.parameters[K]=TT,S&&S(K,TT)}function QU(Q){if(h&&h.options.simple&&h.resolve(CJ||n),h=CJ=null,n=new u0,$T.cancel(),k$){if(y){if(!eT.in_hot_standby||!eT.default_transaction_read_only)return qU();else if(ZU(y,eT))return QX()}if(kT)return k$===!0&&(k$=null),NU();k$!==!0&&wX(k$),T.shared.retries=M$=0,k$=null;return}while(V.length&&(h=V.shift())&&(h.active=!0,h.cancelled))LA(T).cancel(h.state,h.cancelled.resolve,h.cancelled.reject);if(h)return;y$.reserved?!y$.reserved.release&&Q[5]===73?x1?QX():(y$.reserved=null,J(y$)):y$.reserved():x1?QX():J(y$)}function OU(Q){X$=0;for(let K=Q.length-1;K>0;K--){if(Q[K]===32&&Q[K+1]<58&&n.count===null)n.count=+Q.toString("utf8",K+1,Q.length-1);if(Q[K-1]>=65){n.command=Q.toString("utf8",5,K),n.state=C;break}}if(AX&&(AX(),AX=null),n.command==="BEGIN"&&Y!==1&&!y$.reserved)return uJ(G$.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(h.options.simple)return W7();if(h.cursorFn)n.count&&h.cursorFn(n),f$(s1);h.resolve(n)}function UU(){h.parsing=!1}function W7(){!n.statement&&(n.statement=h.statement),n.columns=h.statement.columns}function _U(Q){let K=Q.readUInt16BE(5);for(let TT=0;TT<K;++TT)!h.statement.types[TT]&&(h.statement.types[TT]=Q.readUInt32BE(7+TT*4));h.prepare&&(l$[h.signature]=h.statement),h.describeFirst&&!h.onlyDescribe&&(f$(R8(h)),h.describeFirst=!1)}function DU(Q){if(n.command)CJ=CJ||[n],CJ.push(n=new u0),n.count=null,h.statement.columns=null;let K=Q.readUInt16BE(5),TT=7,CT;h.statement.columns=Array(K);for(let T$=0;T$<K;++T$){CT=TT;while(Q[TT++]!==0);let I$=Q.readUInt32BE(TT),m$=Q.readUInt16BE(TT+4),P1=Q.readUInt32BE(TT+6);h.statement.columns[T$]={name:w.column.from?w.column.from(Q.toString("utf8",CT,TT-1)):Q.toString("utf8",CT,TT-1),parser:A[P1],table:I$,number:m$,type:P1},TT+=18}if(n.statement=h.statement,h.onlyDescribe)return h.resolve(h.statement),f$(s1)}async function KU(Q,K=Q.readUInt32BE(5)){(K===3?SU:K===5?VU:K===10?EU:K===11?RU:K===12?LU:K!==0?dU:uW)(Q,K)}async function SU(){let Q=await TF();f$(s().p().str(Q).z(1).end())}async function VU(Q){let K="md5"+await RA(Buffer.concat([Buffer.from(await RA(await TF()+G)),Q.subarray(9)]));f$(s().p().str(K).z(1).end())}async function EU(){pJ=(await p2.randomBytes(18)).toString("base64"),s().p().str("SCRAM-SHA-256"+s.N);let Q=s.i;f$(s.inc(4).str("n,,n=*,r="+pJ).i32(s.i-Q-4,Q).end())}async function RU(Q){let K=Q.toString("utf8",9).split(",").reduce((m$,P1)=>(m$[P1[0]]=P1.slice(2),m$),{}),TT=await p2.pbkdf2Sync(await TF(),Buffer.from(K.s,"base64"),parseInt(K.i),32,"sha256"),CT=await A6(TT,"Client Key"),T$="n=*,r="+pJ+",r="+K.r+",s="+K.s+",i="+K.i+",c=biws,r="+K.r;rT=(await A6(await A6(TT,"Server Key"),T$)).toString("base64");let I$="c=biws,r="+K.r+",p="+sK(CT,Buffer.from(await A6(await aK(CT),T$))).toString("base64");f$(s().p().str(I$).end())}function LU(Q){if(Q.toString("utf8",9).split(s.N,1)[0].slice(2)===rT)return;uJ(G$.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),E.destroy()}function TF(){return Promise.resolve(typeof T.pass==="function"?T.pass():T.pass)}function BU(){if(n.statement=h.statement,n.statement.columns=[],h.onlyDescribe)return h.resolve(h.statement),f$(s1)}function fU(Q){C.pid=Q.readUInt32BE(5),C.secret=Q.readUInt32BE(9)}async function NU(){kT=!1,(await new RJ([`
55
+ ${H}`)}let z=AW.join(this.baseDir,`${W}/${$}.output.json`);return JSON.parse(o0.readFileSync(z,"utf-8"))}async write(W,$,X,Y){let J=AW.join(this.baseDir,W),G=AW.join(J,`${$}.input.json`),H=AW.join(J,`${$}.output.json`),Q=JSON.stringify(X,null,"\t");if(!o0.existsSync(this.baseDir))o0.mkdirSync(this.baseDir,{recursive:!0});if(!o0.existsSync(J))o0.mkdirSync(J);if(o0.writeFileSync(G,Q),o0.existsSync(H))o0.unlinkSync(H);let z=await Y(...X),F=JSON.stringify(z,null,"\t");return o0.writeFileSync(H,F),z}add(W,$){let X=`${this.rootName}${J1}${t4(W)}`;return{flush:()=>{this.flush(W)},for:(Y)=>{if(this.mode!=="off"){if(this.filesTouched.set(W,new Set),j0.storage.initialized&&!j0.storage.getItem(`list${J1}${X}`))j0.storage.setItem(`list${J1}${X}`,"true")}return{get:async(...J)=>{let G=Y;if(this.mode!=="off"){let H=this.filenameCache.get(Y);if(!H)H=t4(Y),this.filenameCache.set(Y,H);G=H,this.filesTouched.get(W)?.add(G);let Q=`${X}${J1}${G}`,z=`file${J1}${Q}`;if(j0.storage.initialized&&!j0.storage.getItem(z))j0.storage.setItem(z,"true")}switch(this.mode){case"off":return $(...J);case"read":return this.read(W,G,J);case"write":return this.write(W,G,J,$);case"read-write":try{return this.read(W,G,J)}catch(H){if(H instanceof Error)return this.write(W,G,J,$);throw H}}}}}}}flush(...W){console.log(this.filesTouched);for(let[$,X]of this.filesTouched.entries())if(W.length===0||W.includes($)){let Y=AW.join(this.baseDir,$),J=o0.readdirSync(Y);for(let G of J){let H=G.replace(".input.json","").replace(".output.json","");if(!X.has(H))console.info(`\uD83E\uDDF9 Flushing ${H}`),o0.unlinkSync(AW.join(Y,G))}}}};function mV(W,...$){let[X,Y,J,G]=$,H=[{role:"user",content:B3(Y)},{role:"user",content:X}],Q=G.at(-1);if(Q)H.push({role:"user",content:["Oops! That didn't work. Here's what was returned last time:",JSON.stringify(Q.response,null,2),"Here's the error message:",JSON.stringify(Q.error.issues,null,2)].join(`
56
+ `)});return{model:W,messages:H}}var IJ={"gpt-4o":{promptPricePerToken:0.0000025,promptPricePerTokenCached:0.00000125,completionPricePerToken:0.00001},"gpt-4o-2024-08-06":{promptPricePerToken:0.0000025,promptPricePerTokenCached:0.00000125,completionPricePerToken:0.00001},"gpt-4o-2024-05-13":{promptPricePerToken:0.000005,promptPricePerTokenCached:0.000005,completionPricePerToken:0.000014999999999999999},"gpt-4o-mini":{promptPricePerToken:0.00000015,promptPricePerTokenCached:0.000000075,completionPricePerToken:0.0000006},"gpt-4o-mini-2024-07-18":{promptPricePerToken:0.00000015,promptPricePerTokenCached:0.000000075,completionPricePerToken:0.0000006},"o1-preview":{promptPricePerToken:0.000014999999999999999,promptPricePerTokenCached:0.000007499999999999999,completionPricePerToken:0.000059999999999999995},"o1-preview-2024-09-12":{promptPricePerToken:0.000014999999999999999,promptPricePerTokenCached:0.000007499999999999999,completionPricePerToken:0.000059999999999999995}};function pV(W){return async function $(X,Y){if(!W)throw new Error("This is a bug in safegen. OpenAI client not available to the json generator.");let J=await W.chat.completions.create({...X,stream:!1,response_format:{type:"json_object"}},Y),G=J.choices[0].message?.content,{usage:H}=J;if(G&&H){let Q=H.prompt_tokens,z=H.prompt_tokens_details?.cached_tokens??0,F=Q-z,T=H.completion_tokens,U=Q*IJ[X.model].promptPricePerToken+F*IJ[X.model].promptPricePerTokenCached+T*IJ[X.model].completionPricePerToken;return{data:JSON.parse(G),usage:H,usdPrice:U}}if(!G&&!H)throw new Error("No content or usage found in completion");if(!G)throw new Error("No content found in completion");throw new Error("No usage found in completion")}}var hH=new Map,gH=class{usdBudget;usdMinimum;getUnknownJsonFromOpenAi;getUnknownJsonFromOpenAiSquirreled;squirrel;client;lastUsage;constructor({model:W,usdBudget:$,usdMinimum:X,apiKey:Y,cachingMode:J,cacheKey:G="openai-safegen",logger:H}){this.usdBudget=$,this.usdMinimum=X,this.squirrel=new yH(J);let Q=hH.get(Y);if(J!=="read"){if(!Q)Q=new NH({apiKey:Y,dangerouslyAllowBrowser:!1}),hH.set(Y,Q);this.client=Q}this.getUnknownJsonFromOpenAi=pV(this.client),this.getUnknownJsonFromOpenAiSquirreled=this.squirrel.add(G,this.getUnknownJsonFromOpenAi),this.from=N3(async(...z)=>{if(this.usdBudget<this.usdMinimum)return H?.warn("SafeGen budget exhausted"),z[1];let F=mV(W,...z),T=z[0],U=z[3],{data:M,usage:V,usdPrice:K}=await this.getUnknownJsonFromOpenAiSquirreled.for(`${T.replace(/[^a-zA-Z0-9-_. ]/g,"_")}-${U.length}`).get(F);return this.lastUsage=V,this.usdBudget-=K,M},H)}from};import{exec as rE}from"child_process";class eX{supported;constructor(W){this.supported=W}refine(W){for(let[$,X]of Object.entries(this.supported))try{if(X(W)===!0&&X!==Boolean)return{type:$,data:W}}catch(Y){try{if(W instanceof X)return{type:$,data:W}}catch(J){}}return null}}var uV=new eX({number:(W)=>typeof W==="number",string:(W)=>typeof W==="string",boolean:(W)=>typeof W==="boolean",null:(W)=>W===null});function cV(W){if(!W)return!1;return Object.getPrototypeOf(W)===Object.prototype}var dV=new eX({object:cV,array:(W)=>Array.isArray(W)}),lV=new eX({...uV.supported,...dV.supported}),mH=(W)=>{if(W===void 0)return"undefined";let $=lV.refine(W);if($)return $.type;return Object.getPrototypeOf(W).constructor.name};var _=Symbol.for("drizzle:entityKind"),ZP=Symbol.for("drizzle:hasOwnEntityKind");function A(W,$){if(!W||typeof W!=="object")return!1;if(W instanceof $)return!0;if(!Object.prototype.hasOwnProperty.call($,_))throw new Error(`Class "${$.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let X=Object.getPrototypeOf(W).constructor;if(X)while(X){if(_ in X&&X[_]===$[_])return!0;X=Object.getPrototypeOf(X)}return!1}class S0{constructor(W,$){this.table=W,this.config=$,this.name=$.name,this.keyAsName=$.keyAsName,this.notNull=$.notNull,this.default=$.default,this.defaultFn=$.defaultFn,this.onUpdateFn=$.onUpdateFn,this.hasDefault=$.hasDefault,this.primary=$.primaryKey,this.isUnique=$.isUnique,this.uniqueName=$.uniqueName,this.uniqueType=$.uniqueType,this.dataType=$.dataType,this.columnType=$.columnType,this.generated=$.generated,this.generatedIdentity=$.generatedIdentity}static[_]="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(W){return W}mapToDriverValue(W){return W}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class jJ{static[_]="ColumnBuilder";config;constructor(W,$,X){this.config={name:W,keyAsName:W==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:$,columnType:X,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(W){return this.config.default=W,this.config.hasDefault=!0,this}$defaultFn(W){return this.config.defaultFn=W,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(W){return this.config.onUpdateFn=W,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(W){if(this.config.name!=="")return;this.config.name=W}}var EW=Symbol.for("drizzle:Name");class fJ{static[_]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(W,$){if(this.reference=()=>{let{name:X,columns:Y,foreignColumns:J}=W();return{name:X,columns:Y,foreignTable:J[0].table,foreignColumns:J}},$)this._onUpdate=$.onUpdate,this._onDelete=$.onDelete}onUpdate(W){return this._onUpdate=W===void 0?"no action":W,this}onDelete(W){return this._onDelete=W===void 0?"no action":W,this}build(W){return new pH(W,this)}}class pH{constructor(W,$){this.table=W,this.reference=$.reference,this.onUpdate=$._onUpdate,this.onDelete=$._onDelete}static[_]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:W,columns:$,foreignColumns:X}=this.reference(),Y=$.map((H)=>H.name),J=X.map((H)=>H.name),G=[this.table[EW],...Y,X[0].table[EW],...J];return W??`${G.join("_")}_fk`}}function WY(W,...$){return W(...$)}function uH(W,$){return`${W[EW]}_${$.join("_")}_unique`}function cH(W,$,X){for(let Y=$;Y<W.length;Y++){let J=W[Y];if(J==="\\"){Y++;continue}if(J==='"')return[W.slice($,Y).replace(/\\/g,""),Y+1];if(X)continue;if(J===","||J==="}")return[W.slice($,Y).replace(/\\/g,""),Y]}return[W.slice($).replace(/\\/g,""),W.length]}function dH(W,$=0){let X=[],Y=$,J=!1;while(Y<W.length){let G=W[Y];if(G===","){if(J||Y===$)X.push("");J=!0,Y++;continue}if(J=!1,G==="\\"){Y+=2;continue}if(G==='"'){let[z,F]=cH(W,Y+1,!0);X.push(z),Y=F;continue}if(G==="}")return[X,Y+1];if(G==="{"){let[z,F]=dH(W,Y+1);X.push(z),Y=F;continue}let[H,Q]=cH(W,Y,!1);X.push(H),Y=Q}return[X,Y]}function lH(W){let[$]=dH(W,1);return $}function PJ(W){return`{${W.map(($)=>{if(Array.isArray($))return PJ($);if(typeof $==="string")return`"${$.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${$}`}).join(",")}}`}class u extends jJ{foreignKeyConfigs=[];static[_]="PgColumnBuilder";array(W){return new iH(this.config.name,this,W)}references(W,$={}){return this.foreignKeyConfigs.push({ref:W,actions:$}),this}unique(W,$){return this.config.isUnique=!0,this.config.uniqueName=W,this.config.uniqueType=$?.nulls,this}generatedAlwaysAs(W){return this.config.generated={as:W,type:"always",mode:"stored"},this}buildForeignKeys(W,$){return this.foreignKeyConfigs.map(({ref:X,actions:Y})=>{return WY((J,G)=>{let H=new fJ(()=>{let Q=J();return{columns:[W],foreignColumns:[Q]}});if(G.onUpdate)H.onUpdate(G.onUpdate);if(G.onDelete)H.onDelete(G.onDelete);return H.build($)},X,Y)})}buildExtraConfigColumn(W){return new oH(W,this.config)}}class j extends S0{constructor(W,$){if(!$.uniqueName)$.uniqueName=uH(W,[$.name]);super(W,$);this.table=W}static[_]="PgColumn"}class oH extends j{static[_]="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(W){return this.indexConfig.opClass=W,this}}class a4{static[_]="IndexedColumn";constructor(W,$,X,Y){this.name=W,this.keyAsName=$,this.type=X,this.indexConfig=Y}name;keyAsName;type;indexConfig}class iH extends u{static[_]="PgArrayBuilder";constructor(W,$,X){super(W,"array","PgArray");this.config.baseBuilder=$,this.config.size=X}build(W){let $=this.config.baseBuilder.build(W);return new xJ(W,this.config,$)}}class xJ extends j{constructor(W,$,X,Y){super(W,$);this.baseColumn=X,this.range=Y,this.size=$.size}size;static[_]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(W){if(typeof W==="string")W=lH(W);return W.map(($)=>this.baseColumn.mapFromDriverValue($))}mapToDriverValue(W,$=!1){let X=W.map((Y)=>Y===null?null:A(this.baseColumn,xJ)?this.baseColumn.mapToDriverValue(Y,!0):this.baseColumn.mapToDriverValue(Y));if($)return X;return PJ(X)}}class nH extends u{static[_]="PgEnumObjectColumnBuilder";constructor(W,$){super(W,"string","PgEnumObjectColumn");this.config.enum=$}build(W){return new rH(W,this.config)}}class rH extends j{static[_]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(W,$){super(W,$);this.enum=$.enum}getSQLType(){return this.enum.enumName}}var $Y=Symbol.for("drizzle:isPgEnum");function tH(W){return!!W&&typeof W==="function"&&$Y in W&&W[$Y]===!0}class aH extends u{static[_]="PgEnumColumnBuilder";constructor(W,$){super(W,"string","PgEnumColumn");this.config.enum=$}build(W){return new sH(W,this.config)}}class sH extends j{static[_]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(W,$){super(W,$);this.enum=$.enum}getSQLType(){return this.enum.enumName}}function s4(W,$){return Array.isArray($)?oV(W,[...$],void 0):iV(W,$,void 0)}function oV(W,$,X){let Y=Object.assign((J)=>new aH(J??"",Y),{enumName:W,enumValues:$,schema:X,[$Y]:!0});return Y}function iV(W,$,X){let Y=Object.assign((J)=>new nH(J??"",Y),{enumName:W,enumValues:Object.values($),schema:X,[$Y]:!0});return Y}class G1{static[_]="Subquery";constructor(W,$,X,Y=!1){this._={brand:"Subquery",sql:W,selectedFields:$,alias:X,isWith:Y}}}class e4 extends G1{static[_]="WithSubquery"}var eH="0.43.1";var vJ,bJ,q0={startActiveSpan(W,$){if(!vJ)return $();if(!bJ)bJ=vJ.trace.getTracer("drizzle-orm",eH);return WY((X,Y)=>Y.startActiveSpan(W,(J)=>{try{return $(J)}catch(G){throw J.setStatus({code:X.SpanStatusCode.ERROR,message:G instanceof Error?G.message:"Unknown error"}),G}finally{J.end()}}),vJ,bJ)}};var f0=Symbol.for("drizzle:ViewBaseConfig");var XY=Symbol.for("drizzle:Schema"),YY=Symbol.for("drizzle:Columns"),WQ=Symbol.for("drizzle:ExtraConfigColumns"),yJ=Symbol.for("drizzle:OriginalName"),hJ=Symbol.for("drizzle:BaseName"),W6=Symbol.for("drizzle:IsAlias"),$Q=Symbol.for("drizzle:ExtraConfigBuilder"),nV=Symbol.for("drizzle:IsDrizzleTable");class y{static[_]="Table";static Symbol={Name:EW,Schema:XY,OriginalName:yJ,Columns:YY,ExtraConfigColumns:WQ,BaseName:hJ,IsAlias:W6,ExtraConfigBuilder:$Q};[EW];[yJ];[XY];[YY];[WQ];[hJ];[W6]=!1;[nV]=!0;[$Q]=void 0;constructor(W,$,X){this[EW]=this[yJ]=W,this[XY]=$,this[hJ]=X}}function U1(W){return W[EW]}function _8(W){return`${W[XY]??"public"}.${W[EW]}`}function gJ(W){return W!==null&&W!==void 0&&typeof W.getSQL==="function"}function rV(W){let $={sql:"",params:[]};for(let X of W)if($.sql+=X.sql,$.params.push(...X.params),X.typings?.length){if(!$.typings)$.typings=[];$.typings.push(...X.typings)}return $}class H1{static[_]="StringChunk";value;constructor(W){this.value=Array.isArray(W)?W:[W]}getSQL(){return new g([this])}}class g{constructor(W){this.queryChunks=W}static[_]="SQL";decoder=YQ;shouldInlineParams=!1;append(W){return this.queryChunks.push(...W.queryChunks),this}toQuery(W){return q0.startActiveSpan("drizzle.buildSQL",($)=>{let X=this.buildQueryFromSourceParams(this.queryChunks,W);return $?.setAttributes({"drizzle.query.text":X.sql,"drizzle.query.params":JSON.stringify(X.params)}),X})}buildQueryFromSourceParams(W,$){let X=Object.assign({},$,{inlineParams:$.inlineParams||this.shouldInlineParams,paramStartIndex:$.paramStartIndex||{value:0}}),{casing:Y,escapeName:J,escapeParam:G,prepareTyping:H,inlineParams:Q,paramStartIndex:z}=X;return rV(W.map((F)=>{if(A(F,H1))return{sql:F.value.join(""),params:[]};if(A(F,JY))return{sql:J(F.value),params:[]};if(F===void 0)return{sql:"",params:[]};if(Array.isArray(F)){let T=[new H1("(")];for(let[U,M]of F.entries())if(T.push(M),U<F.length-1)T.push(new H1(", "));return T.push(new H1(")")),this.buildQueryFromSourceParams(T,X)}if(A(F,g))return this.buildQueryFromSourceParams(F.queryChunks,{...X,inlineParams:Q||F.shouldInlineParams});if(A(F,y)){let T=F[y.Symbol.Schema],U=F[y.Symbol.Name];return{sql:T===void 0||F[W6]?J(U):J(T)+"."+J(U),params:[]}}if(A(F,S0)){let T=Y.getColumnCasing(F);if($.invokeSource==="indexes")return{sql:J(T),params:[]};let U=F.table[y.Symbol.Schema];return{sql:F.table[W6]||U===void 0?J(F.table[y.Symbol.Name])+"."+J(T):J(U)+"."+J(F.table[y.Symbol.Name])+"."+J(T),params:[]}}if(A(F,y1)){let T=F[f0].schema,U=F[f0].name;return{sql:T===void 0||F[f0].isAlias?J(U):J(T)+"."+J(U),params:[]}}if(A(F,a1)){if(A(F.value,I2))return{sql:G(z.value++,F),params:[F],typings:["none"]};let T=F.value===null?null:F.encoder.mapToDriverValue(F.value);if(A(T,g))return this.buildQueryFromSourceParams([T],X);if(Q)return{sql:this.mapInlineParam(T,X),params:[]};let U=["none"];if(H)U=[H(F.encoder)];return{sql:G(z.value++,T),params:[T],typings:U}}if(A(F,I2))return{sql:G(z.value++,F),params:[F],typings:["none"]};if(A(F,g.Aliased)&&F.fieldAlias!==void 0)return{sql:J(F.fieldAlias),params:[]};if(A(F,G1)){if(F._.isWith)return{sql:J(F._.alias),params:[]};return this.buildQueryFromSourceParams([new H1("("),F._.sql,new H1(") "),new JY(F._.alias)],X)}if(tH(F)){if(F.schema)return{sql:J(F.schema)+"."+J(F.enumName),params:[]};return{sql:J(F.enumName),params:[]}}if(gJ(F)){if(F.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([F.getSQL()],X);return this.buildQueryFromSourceParams([new H1("("),F.getSQL(),new H1(")")],X)}if(Q)return{sql:this.mapInlineParam(F,X),params:[]};return{sql:G(z.value++,F),params:[F],typings:["none"]}}))}mapInlineParam(W,{escapeString:$}){if(W===null)return"null";if(typeof W==="number"||typeof W==="boolean")return W.toString();if(typeof W==="string")return $(W);if(typeof W==="object"){let X=W.toString();if(X==="[object Object]")return $(JSON.stringify(W));return $(X)}throw new Error("Unexpected param value: "+W)}getSQL(){return this}as(W){if(W===void 0)return this;return new g.Aliased(this,W)}mapWith(W){return this.decoder=typeof W==="function"?{mapFromDriverValue:W}:W,this}inlineParams(){return this.shouldInlineParams=!0,this}if(W){return W?this:void 0}}class JY{constructor(W){this.value=W}static[_]="Name";brand;getSQL(){return new g([this])}}function XQ(W){return typeof W==="object"&&W!==null&&"mapToDriverValue"in W&&typeof W.mapToDriverValue==="function"}var YQ={mapFromDriverValue:(W)=>W},JQ={mapToDriverValue:(W)=>W},Mx={...YQ,...JQ};class a1{constructor(W,$=JQ){this.value=W,this.encoder=$}static[_]="Param";brand;getSQL(){return new g([this])}}function D(W,...$){let X=[];if($.length>0||W.length>0&&W[0]!=="")X.push(new H1(W[0]));for(let[Y,J]of $.entries())X.push(J,new H1(W[Y+1]));return new g(X)}((W)=>{function $(){return new g([])}W.empty=$;function X(z){return new g(z)}W.fromList=X;function Y(z){return new g([new H1(z)])}W.raw=Y;function J(z,F){let T=[];for(let[U,M]of z.entries()){if(U>0&&F!==void 0)T.push(F);T.push(M)}return new g(T)}W.join=J;function G(z){return new JY(z)}W.identifier=G;function H(z){return new I2(z)}W.placeholder=H;function Q(z,F){return new a1(z,F)}W.param=Q})(D||(D={}));((W)=>{class ${constructor(X,Y){this.sql=X,this.fieldAlias=Y}static[_]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new $(this.sql,this.fieldAlias)}}W.Aliased=$})(g||(g={}));class I2{constructor(W){this.name=W}static[_]="Placeholder";getSQL(){return new g([this])}}function mJ(W,$){return W.map((X)=>{if(A(X,I2)){if(!(X.name in $))throw new Error(`No value for placeholder "${X.name}" was provided`);return $[X.name]}if(A(X,a1)&&A(X.value,I2)){if(!(X.value.name in $))throw new Error(`No value for placeholder "${X.value.name}" was provided`);return X.encoder.mapToDriverValue($[X.value.name])}return X})}var tV=Symbol.for("drizzle:IsDrizzleView");class y1{static[_]="View";[f0];[tV]=!0;constructor({name:W,schema:$,selectedFields:X,query:Y}){this[f0]={name:W,originalName:W,schema:$,selectedFields:X,query:Y,isExisting:!Y,isAlias:!1}}getSQL(){return new g([this])}}S0.prototype.getSQL=function(){return new g([this])};y.prototype.getSQL=function(){return new g([this])};G1.prototype.getSQL=function(){return new g([this])};class U${constructor(W){this.table=W}static[_]="ColumnAliasProxyHandler";get(W,$){if($==="table")return this.table;return W[$]}}class $6{constructor(W,$){this.alias=W,this.replaceOriginalName=$}static[_]="TableAliasProxyHandler";get(W,$){if($===y.Symbol.IsAlias)return!0;if($===y.Symbol.Name)return this.alias;if(this.replaceOriginalName&&$===y.Symbol.OriginalName)return this.alias;if($===f0)return{...W[f0],name:this.alias,isAlias:!0};if($===y.Symbol.Columns){let Y=W[y.Symbol.Columns];if(!Y)return Y;let J={};return Object.keys(Y).map((G)=>{J[G]=new Proxy(Y[G],new U$(new Proxy(W,this)))}),J}let X=W[$];if(A(X,S0))return new Proxy(X,new U$(new Proxy(W,this)));return X}}function GY(W,$){return new Proxy(W,new $6($,!1))}function gW(W,$){return new Proxy(W,new U$(new Proxy(W.table,new $6($,!1))))}function pJ(W,$){return new g.Aliased(X6(W.sql,$),W.fieldAlias)}function X6(W,$){return D.join(W.queryChunks.map((X)=>{if(A(X,S0))return gW(X,$);if(A(X,g))return X6(X,$);if(A(X,g.Aliased))return pJ(X,$);return X}))}class HY extends Error{static[_]="DrizzleError";constructor({message:W,cause:$}){super(W);this.name="DrizzleError",this.cause=$}}class uJ extends HY{static[_]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class GQ{static[_]="ConsoleLogWriter";write(W){console.log(W)}}class cJ{static[_]="DefaultLogger";writer;constructor(W){this.writer=W?.writer??new GQ}logQuery(W,$){let X=$.map((J)=>{try{return JSON.stringify(J)}catch{return String(J)}}),Y=X.length?` -- params: [${X.join(", ")}]`:"";this.writer.write(`Query: ${W}${Y}`)}}class dJ{static[_]="NoopLogger";logQuery(){}}class C1{static[_]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(W){return this.then(void 0,W)}finally(W){return this.then(($)=>{return W?.(),$},($)=>{throw W?.(),$})}then(W,$){return this.execute().then(W,$)}}function HQ(W,$,X){let Y={},J=W.reduce((G,{path:H,field:Q},z)=>{let F;if(A(Q,S0))F=Q;else if(A(Q,g))F=Q.decoder;else F=Q.sql.decoder;let T=G;for(let[U,M]of H.entries())if(U<H.length-1){if(!(M in T))T[M]={};T=T[M]}else{let V=$[z],K=T[M]=V===null?null:F.mapFromDriverValue(V);if(X&&A(Q,S0)&&H.length===2){let N=H[0];if(!(N in Y))Y[N]=K===null?U1(Q.table):!1;else if(typeof Y[N]==="string"&&Y[N]!==U1(Q.table))Y[N]=!1}}return G},{});if(X&&Object.keys(Y).length>0){for(let[G,H]of Object.entries(Y))if(typeof H==="string"&&!X[H])J[G]=null}return J}function GW(W,$){return Object.entries(W).reduce((X,[Y,J])=>{if(typeof Y!=="string")return X;let G=$?[...$,Y]:[Y];if(A(J,S0)||A(J,g)||A(J,g.Aliased))X.push({path:G,field:J});else if(A(J,y))X.push(...GW(J[y.Symbol.Columns],G));else X.push(...GW(J,G));return X},[])}function Y6(W,$){let X=Object.keys(W),Y=Object.keys($);if(X.length!==Y.length)return!1;for(let[J,G]of X.entries())if(G!==Y[J])return!1;return!0}function QY(W,$){let X=Object.entries($).filter(([,Y])=>Y!==void 0).map(([Y,J])=>{if(A(J,g)||A(J,S0))return[Y,J];else return[Y,new a1(J,W[y.Symbol.Columns][Y])]});if(X.length===0)throw new Error("No values to set");return Object.fromEntries(X)}function QQ(W,$){for(let X of $)for(let Y of Object.getOwnPropertyNames(X.prototype)){if(Y==="constructor")continue;Object.defineProperty(W.prototype,Y,Object.getOwnPropertyDescriptor(X.prototype,Y)||Object.create(null))}}function zQ(W){return W[y.Symbol.Columns]}function Y2(W){return A(W,G1)?W._.alias:A(W,y1)?W[f0].name:A(W,g)?void 0:W[y.Symbol.IsAlias]?W[y.Symbol.Name]:W[y.Symbol.BaseName]}function D0(W,$){return{name:typeof W==="string"&&W.length>0?W:"",config:typeof W==="object"?W:$}}function FQ(W){if(typeof W!=="object"||W===null)return!1;if(W.constructor.name!=="Object")return!1;if("logger"in W){let $=typeof W.logger;if($!=="boolean"&&($!=="object"||typeof W.logger.logQuery!=="function")&&$!=="undefined")return!1;return!0}if("schema"in W){let $=typeof W.schema;if($!=="object"&&$!=="undefined")return!1;return!0}if("casing"in W){let $=typeof W.casing;if($!=="string"&&$!=="undefined")return!1;return!0}if("mode"in W){if(W.mode!=="default"||W.mode!=="planetscale"||W.mode!==void 0)return!1;return!0}if("connection"in W){let $=typeof W.connection;if($!=="string"&&$!=="object"&&$!=="undefined")return!1;return!0}if("client"in W){let $=typeof W.client;if($!=="object"&&$!=="function"&&$!=="undefined")return!1;return!0}if(Object.keys(W).length===0)return!0;return!1}class j2 extends u{static[_]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(W){if(W){let{name:$,...X}=W;this.config.generatedIdentity={type:"always",sequenceName:$,sequenceOptions:X}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(W){if(W){let{name:$,...X}=W;this.config.generatedIdentity={type:"byDefault",sequenceName:$,sequenceOptions:X}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class TQ extends j2{static[_]="PgBigInt53Builder";constructor(W){super(W,"number","PgBigInt53")}build(W){return new UQ(W,this.config)}}class UQ extends j{static[_]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(W){if(typeof W==="number")return W;return Number(W)}}class wQ extends j2{static[_]="PgBigInt64Builder";constructor(W){super(W,"bigint","PgBigInt64")}build(W){return new MQ(W,this.config)}}class MQ extends j{static[_]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(W){return BigInt(W)}}function _Q(W,$){let{name:X,config:Y}=D0(W,$);if(Y.mode==="number")return new TQ(X);return new wQ(X)}class DQ extends u{static[_]="PgBigSerial53Builder";constructor(W){super(W,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(W){return new VQ(W,this.config)}}class VQ extends j{static[_]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(W){if(typeof W==="number")return W;return Number(W)}}class OQ extends u{static[_]="PgBigSerial64Builder";constructor(W){super(W,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(W){return new KQ(W,this.config)}}class KQ extends j{static[_]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(W){return BigInt(W)}}function LQ(W,$){let{name:X,config:Y}=D0(W,$);if(Y.mode==="number")return new DQ(X);return new OQ(X)}class AQ extends u{static[_]="PgBooleanBuilder";constructor(W){super(W,"boolean","PgBoolean")}build(W){return new EQ(W,this.config)}}class EQ extends j{static[_]="PgBoolean";getSQLType(){return"boolean"}}function J6(W){return new AQ(W??"")}class NQ extends u{static[_]="PgCharBuilder";constructor(W,$){super(W,"string","PgChar");this.config.length=$.length,this.config.enumValues=$.enum}build(W){return new BQ(W,this.config)}}class BQ extends j{static[_]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function RQ(W,$={}){let{name:X,config:Y}=D0(W,$);return new NQ(X,Y)}class ZQ extends u{static[_]="PgCidrBuilder";constructor(W){super(W,"string","PgCidr")}build(W){return new SQ(W,this.config)}}class SQ extends j{static[_]="PgCidr";getSQLType(){return"cidr"}}function qQ(W){return new ZQ(W??"")}class CQ extends u{static[_]="PgCustomColumnBuilder";constructor(W,$,X){super(W,"custom","PgCustomColumn");this.config.fieldConfig=$,this.config.customTypeParams=X}build(W){return new kQ(W,this.config)}}class kQ extends j{static[_]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(W,$){super(W,$);this.sqlName=$.customTypeParams.dataType($.fieldConfig),this.mapTo=$.customTypeParams.toDriver,this.mapFrom=$.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(W){return typeof this.mapFrom==="function"?this.mapFrom(W):W}mapToDriverValue(W){return typeof this.mapTo==="function"?this.mapTo(W):W}}function IQ(W){return($,X)=>{let{name:Y,config:J}=D0($,X);return new CQ(Y,J,W)}}class J2 extends u{static[_]="PgDateColumnBaseBuilder";defaultNow(){return this.default(D`now()`)}}class jQ extends J2{static[_]="PgDateBuilder";constructor(W){super(W,"date","PgDate")}build(W){return new zY(W,this.config)}}class zY extends j{static[_]="PgDate";getSQLType(){return"date"}mapFromDriverValue(W){return new Date(W)}mapToDriverValue(W){return W.toISOString()}}class fQ extends J2{static[_]="PgDateStringBuilder";constructor(W){super(W,"string","PgDateString")}build(W){return new FY(W,this.config)}}class FY extends j{static[_]="PgDateString";getSQLType(){return"date"}}function PQ(W,$){let{name:X,config:Y}=D0(W,$);if(Y?.mode==="date")return new jQ(X);return new fQ(X)}class xQ extends u{static[_]="PgDoublePrecisionBuilder";constructor(W){super(W,"number","PgDoublePrecision")}build(W){return new vQ(W,this.config)}}class vQ extends j{static[_]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(W){if(typeof W==="string")return Number.parseFloat(W);return W}}function bQ(W){return new xQ(W??"")}class yQ extends u{static[_]="PgInetBuilder";constructor(W){super(W,"string","PgInet")}build(W){return new hQ(W,this.config)}}class hQ extends j{static[_]="PgInet";getSQLType(){return"inet"}}function gQ(W){return new yQ(W??"")}class mQ extends j2{static[_]="PgIntegerBuilder";constructor(W){super(W,"number","PgInteger")}build(W){return new pQ(W,this.config)}}class pQ extends j{static[_]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(W){if(typeof W==="string")return Number.parseInt(W);return W}}function G6(W){return new mQ(W??"")}class uQ extends u{static[_]="PgIntervalBuilder";constructor(W,$){super(W,"string","PgInterval");this.config.intervalConfig=$}build(W){return new cQ(W,this.config)}}class cQ extends j{static[_]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let W=this.fields?` ${this.fields}`:"",$=this.precision?`(${this.precision})`:"";return`interval${W}${$}`}}function dQ(W,$={}){let{name:X,config:Y}=D0(W,$);return new uQ(X,Y)}class lQ extends u{static[_]="PgJsonBuilder";constructor(W){super(W,"json","PgJson")}build(W){return new TY(W,this.config)}}class TY extends j{static[_]="PgJson";constructor(W,$){super(W,$)}getSQLType(){return"json"}mapToDriverValue(W){return JSON.stringify(W)}mapFromDriverValue(W){if(typeof W==="string")try{return JSON.parse(W)}catch{return W}return W}}function oQ(W){return new lQ(W??"")}class iQ extends u{static[_]="PgJsonbBuilder";constructor(W){super(W,"json","PgJsonb")}build(W){return new UY(W,this.config)}}class UY extends j{static[_]="PgJsonb";constructor(W,$){super(W,$)}getSQLType(){return"jsonb"}mapToDriverValue(W){return JSON.stringify(W)}mapFromDriverValue(W){if(typeof W==="string")try{return JSON.parse(W)}catch{return W}return W}}function nQ(W){return new iQ(W??"")}class rQ extends u{static[_]="PgLineBuilder";constructor(W){super(W,"array","PgLine")}build(W){return new tQ(W,this.config)}}class tQ extends j{static[_]="PgLine";getSQLType(){return"line"}mapFromDriverValue(W){let[$,X,Y]=W.slice(1,-1).split(",");return[Number.parseFloat($),Number.parseFloat(X),Number.parseFloat(Y)]}mapToDriverValue(W){return`{${W[0]},${W[1]},${W[2]}}`}}class aQ extends u{static[_]="PgLineABCBuilder";constructor(W){super(W,"json","PgLineABC")}build(W){return new sQ(W,this.config)}}class sQ extends j{static[_]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(W){let[$,X,Y]=W.slice(1,-1).split(",");return{a:Number.parseFloat($),b:Number.parseFloat(X),c:Number.parseFloat(Y)}}mapToDriverValue(W){return`{${W.a},${W.b},${W.c}}`}}function eQ(W,$){let{name:X,config:Y}=D0(W,$);if(!Y?.mode||Y.mode==="tuple")return new rQ(X);return new aQ(X)}class Wz extends u{static[_]="PgMacaddrBuilder";constructor(W){super(W,"string","PgMacaddr")}build(W){return new $z(W,this.config)}}class $z extends j{static[_]="PgMacaddr";getSQLType(){return"macaddr"}}function Xz(W){return new Wz(W??"")}class Yz extends u{static[_]="PgMacaddr8Builder";constructor(W){super(W,"string","PgMacaddr8")}build(W){return new Jz(W,this.config)}}class Jz extends j{static[_]="PgMacaddr8";getSQLType(){return"macaddr8"}}function Gz(W){return new Yz(W??"")}class Hz extends u{static[_]="PgNumericBuilder";constructor(W,$,X){super(W,"string","PgNumeric");this.config.precision=$,this.config.scale=X}build(W){return new wY(W,this.config)}}class wY extends j{static[_]="PgNumeric";precision;scale;constructor(W,$){super(W,$);this.precision=$.precision,this.scale=$.scale}mapFromDriverValue(W){if(typeof W==="string")return W;return String(W)}getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}class Qz extends u{static[_]="PgNumericNumberBuilder";constructor(W,$,X){super(W,"number","PgNumericNumber");this.config.precision=$,this.config.scale=X}build(W){return new zz(W,this.config)}}class zz extends j{static[_]="PgNumericNumber";precision;scale;constructor(W,$){super(W,$);this.precision=$.precision,this.scale=$.scale}mapFromDriverValue(W){if(typeof W==="number")return W;return Number(W)}mapToDriverValue=String;getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}class Fz extends u{static[_]="PgNumericBigIntBuilder";constructor(W,$,X){super(W,"bigint","PgNumericBigInt");this.config.precision=$,this.config.scale=X}build(W){return new Tz(W,this.config)}}class Tz extends j{static[_]="PgNumericBigInt";precision;scale;constructor(W,$){super(W,$);this.precision=$.precision,this.scale=$.scale}mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}function Uz(W,$){let{name:X,config:Y}=D0(W,$),J=Y?.mode;return J==="number"?new Qz(X,Y?.precision,Y?.scale):J==="bigint"?new Fz(X,Y?.precision,Y?.scale):new Hz(X,Y?.precision,Y?.scale)}class wz extends u{static[_]="PgPointTupleBuilder";constructor(W){super(W,"array","PgPointTuple")}build(W){return new Mz(W,this.config)}}class Mz extends j{static[_]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(W){if(typeof W==="string"){let[$,X]=W.slice(1,-1).split(",");return[Number.parseFloat($),Number.parseFloat(X)]}return[W.x,W.y]}mapToDriverValue(W){return`(${W[0]},${W[1]})`}}class _z extends u{static[_]="PgPointObjectBuilder";constructor(W){super(W,"json","PgPointObject")}build(W){return new Dz(W,this.config)}}class Dz extends j{static[_]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(W){if(typeof W==="string"){let[$,X]=W.slice(1,-1).split(",");return{x:Number.parseFloat($),y:Number.parseFloat(X)}}return W}mapToDriverValue(W){return`(${W.x},${W.y})`}}function Vz(W,$){let{name:X,config:Y}=D0(W,$);if(!Y?.mode||Y.mode==="tuple")return new wz(X);return new _z(X)}function aV(W){let $=[];for(let X=0;X<W.length;X+=2)$.push(Number.parseInt(W.slice(X,X+2),16));return new Uint8Array($)}function Oz(W,$){let X=new ArrayBuffer(8),Y=new DataView(X);for(let J=0;J<8;J++)Y.setUint8(J,W[$+J]);return Y.getFloat64(0,!0)}function lJ(W){let $=aV(W),X=0,Y=$[X];X+=1;let J=new DataView($.buffer),G=J.getUint32(X,Y===1);X+=4;let H;if(G&536870912)H=J.getUint32(X,Y===1),X+=4;if((G&65535)===1){let Q=Oz($,X);X+=8;let z=Oz($,X);return X+=8,[Q,z]}throw new Error("Unsupported geometry type")}class Kz extends u{static[_]="PgGeometryBuilder";constructor(W){super(W,"array","PgGeometry")}build(W){return new Lz(W,this.config)}}class Lz extends j{static[_]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(W){return lJ(W)}mapToDriverValue(W){return`point(${W[0]} ${W[1]})`}}class Az extends u{static[_]="PgGeometryObjectBuilder";constructor(W){super(W,"json","PgGeometryObject")}build(W){return new Ez(W,this.config)}}class Ez extends j{static[_]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(W){let $=lJ(W);return{x:$[0],y:$[1]}}mapToDriverValue(W){return`point(${W.x} ${W.y})`}}function Nz(W,$){let{name:X,config:Y}=D0(W,$);if(!Y?.mode||Y.mode==="tuple")return new Kz(X);return new Az(X)}class Bz extends u{static[_]="PgRealBuilder";constructor(W,$){super(W,"number","PgReal");this.config.length=$}build(W){return new Rz(W,this.config)}}class Rz extends j{static[_]="PgReal";constructor(W,$){super(W,$)}getSQLType(){return"real"}mapFromDriverValue=(W)=>{if(typeof W==="string")return Number.parseFloat(W);return W}}function Zz(W){return new Bz(W??"")}class Sz extends u{static[_]="PgSerialBuilder";constructor(W){super(W,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(W){return new qz(W,this.config)}}class qz extends j{static[_]="PgSerial";getSQLType(){return"serial"}}function Cz(W){return new Sz(W??"")}class kz extends j2{static[_]="PgSmallIntBuilder";constructor(W){super(W,"number","PgSmallInt")}build(W){return new Iz(W,this.config)}}class Iz extends j{static[_]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(W)=>{if(typeof W==="string")return Number(W);return W}}function jz(W){return new kz(W??"")}class fz extends u{static[_]="PgSmallSerialBuilder";constructor(W){super(W,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(W){return new Pz(W,this.config)}}class Pz extends j{static[_]="PgSmallSerial";getSQLType(){return"smallserial"}}function xz(W){return new fz(W??"")}class vz extends u{static[_]="PgTextBuilder";constructor(W,$){super(W,"string","PgText");this.config.enumValues=$.enum}build(W){return new bz(W,this.config)}}class bz extends j{static[_]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function yz(W,$={}){let{name:X,config:Y}=D0(W,$);return new vz(X,Y)}class hz extends J2{constructor(W,$,X){super(W,"string","PgTime");this.withTimezone=$,this.precision=X,this.config.withTimezone=$,this.config.precision=X}static[_]="PgTimeBuilder";build(W){return new MY(W,this.config)}}class MY extends j{static[_]="PgTime";withTimezone;precision;constructor(W,$){super(W,$);this.withTimezone=$.withTimezone,this.precision=$.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function gz(W,$={}){let{name:X,config:Y}=D0(W,$);return new hz(X,Y.withTimezone??!1,Y.precision)}class mz extends J2{static[_]="PgTimestampBuilder";constructor(W,$,X){super(W,"date","PgTimestamp");this.config.withTimezone=$,this.config.precision=X}build(W){return new _Y(W,this.config)}}class _Y extends j{static[_]="PgTimestamp";withTimezone;precision;constructor(W,$){super(W,$);this.withTimezone=$.withTimezone,this.precision=$.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(W)=>{return new Date(this.withTimezone?W:W+"+0000")};mapToDriverValue=(W)=>{return W.toISOString()}}class pz extends J2{static[_]="PgTimestampStringBuilder";constructor(W,$,X){super(W,"string","PgTimestampString");this.config.withTimezone=$,this.config.precision=X}build(W){return new DY(W,this.config)}}class DY extends j{static[_]="PgTimestampString";withTimezone;precision;constructor(W,$){super(W,$);this.withTimezone=$.withTimezone,this.precision=$.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function NW(W,$={}){let{name:X,config:Y}=D0(W,$);if(Y?.mode==="string")return new pz(X,Y.withTimezone??!1,Y.precision);return new mz(X,Y?.withTimezone??!1,Y?.precision)}class uz extends u{static[_]="PgUUIDBuilder";constructor(W){super(W,"string","PgUUID")}defaultRandom(){return this.default(D`gen_random_uuid()`)}build(W){return new VY(W,this.config)}}class VY extends j{static[_]="PgUUID";getSQLType(){return"uuid"}}function HW(W){return new uz(W??"")}class cz extends u{static[_]="PgVarcharBuilder";constructor(W,$){super(W,"string","PgVarchar");this.config.length=$.length,this.config.enumValues=$.enum}build(W){return new dz(W,this.config)}}class dz extends j{static[_]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function k1(W,$={}){let{name:X,config:Y}=D0(W,$);return new cz(X,Y)}class lz extends u{static[_]="PgBinaryVectorBuilder";constructor(W,$){super(W,"string","PgBinaryVector");this.config.dimensions=$.dimensions}build(W){return new oz(W,this.config)}}class oz extends j{static[_]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function iz(W,$){let{name:X,config:Y}=D0(W,$);return new lz(X,Y)}class nz extends u{static[_]="PgHalfVectorBuilder";constructor(W,$){super(W,"array","PgHalfVector");this.config.dimensions=$.dimensions}build(W){return new rz(W,this.config)}}class rz extends j{static[_]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(W){return JSON.stringify(W)}mapFromDriverValue(W){return W.slice(1,-1).split(",").map(($)=>Number.parseFloat($))}}function tz(W,$){let{name:X,config:Y}=D0(W,$);return new nz(X,Y)}class az extends u{static[_]="PgSparseVectorBuilder";constructor(W,$){super(W,"string","PgSparseVector");this.config.dimensions=$.dimensions}build(W){return new sz(W,this.config)}}class sz extends j{static[_]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function ez(W,$){let{name:X,config:Y}=D0(W,$);return new az(X,Y)}class WF extends u{static[_]="PgVectorBuilder";constructor(W,$){super(W,"array","PgVector");this.config.dimensions=$.dimensions}build(W){return new $F(W,this.config)}}class $F extends j{static[_]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(W){return JSON.stringify(W)}mapFromDriverValue(W){return W.slice(1,-1).split(",").map(($)=>Number.parseFloat($))}}function XF(W,$){let{name:X,config:Y}=D0(W,$);return new WF(X,Y)}function YF(){return{bigint:_Q,bigserial:LQ,boolean:J6,char:RQ,cidr:qQ,customType:IQ,date:PQ,doublePrecision:bQ,inet:gQ,integer:G6,interval:dQ,json:oQ,jsonb:nQ,line:eQ,macaddr:Xz,macaddr8:Gz,numeric:Uz,point:Vz,geometry:Nz,real:Zz,serial:Cz,smallint:jz,smallserial:xz,text:yz,time:gz,timestamp:NW,uuid:HW,varchar:k1,bit:iz,halfvec:tz,sparsevec:ez,vector:XF}}var oJ=Symbol.for("drizzle:PgInlineForeignKeys"),JF=Symbol.for("drizzle:EnableRLS");class _1 extends y{static[_]="PgTable";static Symbol=Object.assign({},y.Symbol,{InlineForeignKeys:oJ,EnableRLS:JF});[oJ]=[];[JF]=!1;[y.Symbol.ExtraConfigBuilder]=void 0;[y.Symbol.ExtraConfigColumns]={}}function sV(W,$,X,Y,J=W){let G=new _1(W,Y,J),H=typeof $==="function"?$(YF()):$,Q=Object.fromEntries(Object.entries(H).map(([T,U])=>{let M=U;M.setName(T);let V=M.build(G);return G[oJ].push(...M.buildForeignKeys(V,G)),[T,V]})),z=Object.fromEntries(Object.entries(H).map(([T,U])=>{let M=U;M.setName(T);let V=M.buildExtraConfigColumn(G);return[T,V]})),F=Object.assign(G,Q);if(F[y.Symbol.Columns]=Q,F[y.Symbol.ExtraConfigColumns]=z,X)F[_1.Symbol.ExtraConfigBuilder]=X;return Object.assign(F,{enableRLS:()=>{return F[_1.Symbol.EnableRLS]=!0,F}})}var f2=(W,$,X)=>{return sV(W,$,X,void 0)};function GF(...W){if(W[0].columns)return new H6(W[0].columns,W[0].name);return new H6(W)}class H6{static[_]="PgPrimaryKeyBuilder";columns;name;constructor(W,$){this.columns=W,this.name=$}build(W){return new HF(W,this.columns,this.name)}}class HF{constructor(W,$,X){this.table=W,this.columns=$,this.name=X}static[_]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[_1.Symbol.Name]}_${this.columns.map((W)=>W.name).join("_")}_pk`}}function h1(W,$){if(XQ($)&&!gJ(W)&&!A(W,a1)&&!A(W,I2)&&!A(W,S0)&&!A(W,y)&&!A(W,y1))return new a1(W,$);return W}var OY=(W,$)=>{return D`${W} = ${h1($,W)}`},QF=(W,$)=>{return D`${W} <> ${h1($,W)}`};function Q6(...W){let $=W.filter((X)=>X!==void 0);if($.length===0)return;if($.length===1)return new g($);return new g([new H1("("),D.join($,new H1(" and ")),new H1(")")])}function zF(...W){let $=W.filter((X)=>X!==void 0);if($.length===0)return;if($.length===1)return new g($);return new g([new H1("("),D.join($,new H1(" or ")),new H1(")")])}function FF(W){return D`not ${W}`}var KY=(W,$)=>{return D`${W} > ${h1($,W)}`},TF=(W,$)=>{return D`${W} >= ${h1($,W)}`},UF=(W,$)=>{return D`${W} < ${h1($,W)}`},wF=(W,$)=>{return D`${W} <= ${h1($,W)}`};function MF(W,$){if(Array.isArray($)){if($.length===0)return D`false`;return D`${W} in ${$.map((X)=>h1(X,W))}`}return D`${W} in ${h1($,W)}`}function _F(W,$){if(Array.isArray($)){if($.length===0)return D`true`;return D`${W} not in ${$.map((X)=>h1(X,W))}`}return D`${W} not in ${h1($,W)}`}function DF(W){return D`${W} is null`}function VF(W){return D`${W} is not null`}function OF(W){return D`exists ${W}`}function KF(W){return D`not exists ${W}`}function LF(W,$,X){return D`${W} between ${h1($,W)} and ${h1(X,W)}`}function AF(W,$,X){return D`${W} not between ${h1($,W)} and ${h1(X,W)}`}function EF(W,$){return D`${W} like ${$}`}function NF(W,$){return D`${W} not like ${$}`}function BF(W,$){return D`${W} ilike ${$}`}function RF(W,$){return D`${W} not ilike ${$}`}function ZF(W){return D`${W} asc`}function SF(W){return D`${W} desc`}class iJ{constructor(W,$,X){this.sourceTable=W,this.referencedTable=$,this.relationName=X,this.referencedTableName=$[y.Symbol.Name]}static[_]="Relation";referencedTableName;fieldName}class qF{constructor(W,$){this.table=W,this.config=$}static[_]="Relations"}class P2 extends iJ{constructor(W,$,X,Y){super(W,$,X?.relationName);this.config=X,this.isNullable=Y}static[_]="One";withFieldName(W){let $=new P2(this.sourceTable,this.referencedTable,this.config,this.isNullable);return $.fieldName=W,$}}class z6 extends iJ{constructor(W,$,X){super(W,$,X?.relationName);this.config=X}static[_]="Many";withFieldName(W){let $=new z6(this.sourceTable,this.referencedTable,this.config);return $.fieldName=W,$}}function CF(){return{and:Q6,between:LF,eq:OY,exists:OF,gt:KY,gte:TF,ilike:BF,inArray:MF,isNull:DF,isNotNull:VF,like:EF,lt:UF,lte:wF,ne:QF,not:FF,notBetween:AF,notExists:KF,notLike:NF,notIlike:RF,notInArray:_F,or:zF,sql:D}}function kF(){return{sql:D,asc:ZF,desc:SF}}function IF(W,$){if(Object.keys(W).length===1&&"default"in W&&!A(W.default,y))W=W.default;let X={},Y={},J={};for(let[G,H]of Object.entries(W))if(A(H,y)){let Q=_8(H),z=Y[Q];X[Q]=G,J[G]={tsName:G,dbName:H[y.Symbol.Name],schema:H[y.Symbol.Schema],columns:H[y.Symbol.Columns],relations:z?.relations??{},primaryKey:z?.primaryKey??[]};for(let T of Object.values(H[y.Symbol.Columns]))if(T.primary)J[G].primaryKey.push(T);let F=H[y.Symbol.ExtraConfigBuilder]?.(H[y.Symbol.ExtraConfigColumns]);if(F){for(let T of Object.values(F))if(A(T,H6))J[G].primaryKey.push(...T.columns)}}else if(A(H,qF)){let Q=_8(H.table),z=X[Q],F=H.config($(H.table)),T;for(let[U,M]of Object.entries(F))if(z){let V=J[z];if(V.relations[U]=M,T)V.primaryKey.push(...T)}else{if(!(Q in Y))Y[Q]={relations:{},primaryKey:T};Y[Q].relations[U]=M}}return{tables:J,tableNamesMap:X}}function eV(W){return function $(X,Y){return new P2(W,X,Y,Y?.fields.reduce((J,G)=>J&&G.notNull,!0)??!1)}}function WO(W){return function $(X,Y){return new z6(W,X,Y)}}function jF(W,$,X){if(A(X,P2)&&X.config)return{fields:X.config.fields,references:X.config.references};let Y=$[_8(X.referencedTable)];if(!Y)throw new Error(`Table "${X.referencedTable[y.Symbol.Name]}" not found in schema`);let J=W[Y];if(!J)throw new Error(`Table "${Y}" not found in schema`);let G=X.sourceTable,H=$[_8(G)];if(!H)throw new Error(`Table "${G[y.Symbol.Name]}" not found in schema`);let Q=[];for(let z of Object.values(J.relations))if(X.relationName&&X!==z&&z.relationName===X.relationName||!X.relationName&&z.referencedTable===X.sourceTable)Q.push(z);if(Q.length>1)throw X.relationName?new Error(`There are multiple relations with name "${X.relationName}" in table "${Y}"`):new Error(`There are multiple relations between "${Y}" and "${X.sourceTable[y.Symbol.Name]}". Please specify relation name`);if(Q[0]&&A(Q[0],P2)&&Q[0].config)return{fields:Q[0].config.references,references:Q[0].config.fields};throw new Error(`There is not enough information to infer relation "${H}.${X.fieldName}"`)}function fF(W){return{one:eV(W),many:WO(W)}}function LY(W,$,X,Y,J=(G)=>G){let G={};for(let[H,Q]of Y.entries())if(Q.isJson){let z=$.relations[Q.tsKey],F=X[H],T=typeof F==="string"?JSON.parse(F):F;G[Q.tsKey]=A(z,P2)?T&&LY(W,W[Q.relationTableTsKey],T,Q.selection,J):T.map((U)=>LY(W,W[Q.relationTableTsKey],U,Q.selection,J))}else{let z=J(X[H]),F=Q.field,T;if(A(F,S0))T=F;else if(A(F,g))T=F.decoder;else T=F.sql.decoder;G[Q.tsKey]=z===null?null:T.mapFromDriverValue(z)}return G}import cE from"path";import RO from"os";import ZO from"fs";var AY=new Map,nJ=new Map,rJ=Symbol("OriginError"),w$={};class QW extends Promise{constructor(W,$,X,Y,J={}){let G,H;super((Q,z)=>{G=Q,H=z});this.tagged=Array.isArray(W.raw),this.strings=W,this.args=$,this.handler=X,this.canceller=Y,this.options=J,this.state=null,this.statement=null,this.resolve=(Q)=>(this.active=!1,G(Q)),this.reject=(Q)=>(this.active=!1,H(Q)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[rJ]=this.handler.debug?new Error:this.tagged&&$O(this.strings)}get origin(){return(this.handler.debug?this[rJ].stack:this.tagged&&nJ.has(this.strings)?nJ.get(this.strings):nJ.set(this.strings,this[rJ].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(W=1,$){if(this.options.simple=!1,typeof W==="function")$=W,W=1;if(this.cursorRows=W,typeof $==="function")return this.cursorFn=$,this;let X;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};X&&X();let Y=new Promise((J,G)=>{this.cursorFn=(H)=>{return J({value:H,done:!1}),new Promise((Q)=>X=Q)},this.resolve=()=>(this.active=!1,J({done:!0})),this.reject=(H)=>(this.active=!1,G(H))});return this.execute(),Y},return(){return X&&X(w$),{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(W){return this.forEachFn=W,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 $O(W){if(AY.has(W))return AY.get(W);let $=Error.stackTraceLimit;return Error.stackTraceLimit=4,AY.set(W,new Error),Error.stackTraceLimit=$,AY.get(W)}class M$ extends Error{constructor(W){super(W.message);this.name=this.constructor.name,Object.assign(this,W)}}var t0={connection:PF,postgres:xF,generic:vF,notSupported:bF};function PF(W,$,X){let{host:Y,port:J}=X||$,G=Object.assign(new Error("write "+W+" "+($.path||Y+":"+J)),{code:W,errno:W,address:$.path||Y},$.path?{}:{port:J});return Error.captureStackTrace(G,PF),G}function xF(W){let $=new M$(W);return Error.captureStackTrace($,xF),$}function vF(W,$){let X=Object.assign(new Error(W+": "+$),{code:W});return Error.captureStackTrace(X,vF),X}function bF(W){let $=Object.assign(new Error(W+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:W});return Error.captureStackTrace($,bF),$}var XO={string:{to:25,from:null,serialize:(W)=>""+W},number:{to:0,from:[21,23,26,700,701],serialize:(W)=>""+W,parse:(W)=>+W},json:{to:114,from:[114,3802],serialize:(W)=>JSON.stringify(W),parse:(W)=>JSON.parse(W)},boolean:{to:16,from:16,serialize:(W)=>W===!0?"t":"f",parse:(W)=>W==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(W)=>(W instanceof Date?W:new Date(W)).toISOString(),parse:(W)=>new Date(W)},bytea:{to:17,from:17,serialize:(W)=>"\\x"+Buffer.from(W).toString("hex"),parse:(W)=>Buffer.from(W.slice(2),"hex")}};class BY{then(){tJ()}catch(){tJ()}finally(){tJ()}}class w6 extends BY{constructor(W){super();this.value=SY(W)}}class mW extends BY{constructor(W,$,X){super();this.value=W,this.type=$,this.array=X}}class RY extends BY{constructor(W,$){super();this.first=W,this.rest=$}build(W,$,X,Y){let J=YO.map(([G,H])=>({fn:H,i:W.search(G)})).sort((G,H)=>G.i-H.i).pop();return J.i===-1?$5(this.first,Y):J.fn(this.first,this.rest,$,X,Y)}}function ZY(W,$,X,Y){let J=W instanceof mW?W.value:W;if(J===void 0){if(W instanceof mW?W.value=Y.transform.undefined:J=W=Y.transform.undefined,J===void 0)throw t0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+X.push(W instanceof mW?($.push(W.value),W.array?W.array[W.type||NY(W.value)]||W.type||mF(W.value):W.type):($.push(W),NY(W)))}var hF=uF(XO);function eJ(W,$,X,Y,J,G){for(let H=1;H<W.strings.length;H++)$+=W5($,X,Y,J,G)+W.strings[H],X=W.args[H];return $}function W5(W,$,X,Y,J){return $ instanceof RY?$.build(W,X,Y,J):$ instanceof QW?sJ($,X,Y,J):$ instanceof w6?$.value:$&&$[0]instanceof QW?$.reduce((G,H)=>G+" "+sJ(H,X,Y,J),""):ZY($,X,Y,J)}function sJ(W,$,X,Y){return W.fragment=!0,eJ(W,W.strings[0],W.args[0],$,X,Y)}function gF(W,$,X,Y,J){return W.map((G)=>"("+Y.map((H)=>W5("values",G[H],$,X,J)).join(",")+")").join(",")}function yF(W,$,X,Y,J){let G=Array.isArray(W[0]),H=$.length?$.flat():Object.keys(G?W[0]:W);return gF(G?W:[W],X,Y,H,J)}function EY(W,$,X,Y,J){if(typeof W==="string"&&(W=[W].concat($)),Array.isArray(W))return $5(W,J);let G;return($.length?$.flat():Object.keys(W)).map((Q)=>{return G=W[Q],(G instanceof QW?sJ(G,X,Y,J):G instanceof w6?G.value:ZY(G,X,Y,J))+" as "+SY(J.transform.column.to?J.transform.column.to(Q):Q)}).join(",")}var YO=Object.entries({values:yF,in:(...W)=>{let $=yF(...W);return $==="()"?"(null)":$},select:EY,as:EY,returning:EY,"\\(":EY,update(W,$,X,Y,J){return($.length?$.flat():Object.keys(W)).map((G)=>SY(J.transform.column.to?J.transform.column.to(G):G)+"="+W5("values",W[G],X,Y,J))},insert(W,$,X,Y,J){let G=$.length?$.flat():Object.keys(Array.isArray(W)?W[0]:W);return"("+$5(G,J)+")values"+gF(Array.isArray(W)?W:[W],X,Y,G,J)}}).map(([W,$])=>[new RegExp("((?:^|[\\s(])"+W+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),$]);function tJ(){throw t0.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:JO,parsers:GO}=hF;function mF(W){if(Array.isArray(W))return mF(W[0]);return typeof W==="string"?1009:0}var pF=function(W){let $=uF(W||{});return{serializers:Object.assign({},JO,$.serializers),parsers:Object.assign({},GO,$.parsers)}};function uF(W){return Object.keys(W).reduce(($,X)=>{if(W[X].from&&[].concat(W[X].from).forEach((Y)=>$.parsers[Y]=W[X].parse),W[X].serialize)$.serializers[W[X].to]=W[X].serialize,W[X].from&&[].concat(W[X].from).forEach((Y)=>$.serializers[Y]=W[X].serialize);return $},{parsers:{},serializers:{}})}function $5(W,{transform:{column:$}}){return W.map((X)=>SY($.to?$.to(X):X)).join(",")}var SY=function W($){return'"'+$.replace(/"/g,'""').replace(/\./g,'"."')+'"'},NY=function W($){return $ instanceof mW?$.type:$ instanceof Date?1184:$ instanceof Uint8Array?17:$===!0||$===!1?16:typeof $==="bigint"?20:Array.isArray($)?W($[0]):0},HO=/\\/g,QO=/"/g;function zO(W){return W.replace(HO,"\\\\").replace(QO,"\\\"")}var cF=function W($,X,Y,J){if(Array.isArray($)===!1)return $;if(!$.length)return"{}";let G=$[0],H=J===1020?";":",";if(Array.isArray(G)&&!G.type)return"{"+$.map((Q)=>W(Q,X,Y,J)).join(H)+"}";return"{"+$.map((Q)=>{if(Q===void 0){if(Q=Y.transform.undefined,Q===void 0)throw t0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return Q===null?"null":'"'+zO(X?X(Q.type?Q.value:Q):""+Q)+'"'}).join(H)+"}"},aJ={i:0,char:null,str:"",quoted:!1,last:0},dF=function W($,X,Y){return aJ.i=aJ.last=0,lF(aJ,$,X,Y)};function lF(W,$,X,Y){let J=[],G=Y===1020?";":",";for(;W.i<$.length;W.i++){if(W.char=$[W.i],W.quoted)if(W.char==="\\")W.str+=$[++W.i];else if(W.char==='"')J.push(X?X(W.str):W.str),W.str="",W.quoted=$[W.i+1]==='"',W.last=W.i+2;else W.str+=W.char;else if(W.char==='"')W.quoted=!0;else if(W.char==="{")W.last=++W.i,J.push(lF(W,$,X,Y));else if(W.char==="}"){W.quoted=!1,W.last<W.i&&J.push(X?X($.slice(W.last,W.i)):$.slice(W.last,W.i)),W.last=W.i+1;break}else if(W.char===G&&W.p!=="}"&&W.p!=='"')J.push(X?X($.slice(W.last,W.i)):$.slice(W.last,W.i)),W.last=W.i+1;W.p=W.char}return W.last<W.i&&J.push(X?X($.slice(W.last,W.i+1)):$.slice(W.last,W.i+1)),J}var D8=(W)=>{let $=W[0];for(let X=1;X<W.length;X++)$+=W[X]==="_"?W[++X].toUpperCase():W[X];return $},V8=(W)=>{let $=W[0].toUpperCase();for(let X=1;X<W.length;X++)$+=W[X]==="_"?W[++X].toUpperCase():W[X];return $},O8=(W)=>W.replace(/_/g,"-"),F6=(W)=>W.replace(/([A-Z])/g,"_$1").toLowerCase(),T6=(W)=>(W.slice(0,1)+W.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),U6=(W)=>W.replace(/-/g,"_");function X5(W){return function $(X,Y){return typeof X==="object"&&X!==null&&(Y.type===114||Y.type===3802)?Array.isArray(X)?X.map((J)=>$(J,Y)):Object.entries(X).reduce((J,[G,H])=>Object.assign(J,{[W(G)]:$(H,Y)}),{}):X}}D8.column={from:D8};D8.value={from:X5(D8)};F6.column={to:F6};var Y5={...D8};Y5.column.to=F6;V8.column={from:V8};V8.value={from:X5(V8)};T6.column={to:T6};var J5={...V8};J5.column.to=T6;O8.column={from:O8};O8.value={from:X5(O8)};U6.column={to:U6};var G5={...O8};G5.column.to=U6;import oF from"net";import wO from"tls";import M6 from"crypto";import H5 from"stream";import{performance as iF}from"perf_hooks";class K8 extends Array{constructor(){super();Object.defineProperties(this,{count:{value:null,writable:!0},state:{value:null,writable:!0},command:{value:null,writable:!0},columns:{value:null,writable:!0},statement:{value:null,writable:!0}})}static get[Symbol.species](){return Array}}var s1=FO;function FO(W=[]){let $=W.slice(),X=0;return{get length(){return $.length-X},remove:(Y)=>{let J=$.indexOf(Y);return J===-1?null:($.splice(J,1),Y)},push:(Y)=>($.push(Y),Y),shift:()=>{let Y=$[X++];if(X===$.length)X=0,$=[];else $[X-1]=void 0;return Y}}}var E1=Buffer.allocUnsafe(256),TO="BCcDdEFfHPpQSX".split("").reduce((W,$)=>{let X=$.charCodeAt(0);return W[$]=()=>{return E1[0]=X,R0.i=5,R0},W},{}),R0=Object.assign(UO,TO,{N:String.fromCharCode(0),i:0,inc(W){return R0.i+=W,R0},str(W){let $=Buffer.byteLength(W);return qY($),R0.i+=E1.write(W,R0.i,$,"utf8"),R0},i16(W){return qY(2),E1.writeUInt16BE(W,R0.i),R0.i+=2,R0},i32(W,$){if($||$===0)return E1.writeUInt32BE(W,$),R0;return qY(4),E1.writeUInt32BE(W,R0.i),R0.i+=4,R0},z(W){return qY(W),E1.fill(0,R0.i,R0.i+W),R0.i+=W,R0},raw(W){return E1=Buffer.concat([E1.subarray(0,R0.i),W]),R0.i=E1.length,R0},end(W=1){E1.writeUInt32BE(R0.i-W,W);let $=E1.subarray(0,R0.i);return R0.i=0,E1=Buffer.allocUnsafe(256),$}}),n=R0;function qY(W){if(E1.length-R0.i<W){let $=E1,X=$.length;E1=Buffer.allocUnsafe(X+(X>>1)+W),$.copy(E1)}}function UO(){return R0.i=0,R0}var F5=tF,MO=1,x2=n().S().end(),nF=n().H().end(),_O=n().i32(8).i32(80877103).end(8),DO=Buffer.concat([n().E().str(n.N).i32(0).end(),x2]),VO=n().D().str("S").str(n.N).end(),_$=()=>{},OO=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),KO={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 tF(W,$={},{onopen:X=_$,onend:Y=_$,onclose:J=_$}={}){let{ssl:G,max:H,user:Q,host:z,port:F,database:T,parsers:U,transform:M,onnotice:V,onnotify:K,onparameter:N,max_pipeline:I,keep_alive:C,backoff:B,target_session_attrs:q}=W,m=s1(),c=MO++,v={pid:null,secret:null},h=z5(V9,W.idle_timeout),U0=z5(V9,W.max_lifetime),m0=z5(vM,W.connect_timeout),E=null,_0,e=new K8,w0=Buffer.alloc(0),s0=W.fetch_types,D1={},wW={},q8=Math.random().toString(36).slice(2),k=1,a=0,N0=0,g0=0,e0=0,F0=0,k0=0,n0=0,p0=null,v0=null,V1=!1,I0=null,MW=null,O1=null,V2=null,W1=null,b0=null,_W=null,CW=null,x=null,y$=null,K1={queue:$.closed,idleTimer:h,connect(w){O1=w||!0,WG()},terminate:g$,execute:h$,cancel:jM,end:V9,count:0,id:c};return $.closed&&$.closed.push(K1),K1;async function IM(){let w;try{w=W.socket?await Promise.resolve(W.socket(W)):new oF.Socket}catch(O){k8(O);return}return w.on("error",k8),w.on("close",$G),w.on("drain",s7),w}async function jM({pid:w,secret:O},t,A0){try{_0=n().i32(16).i32(80877102).i32(w).i32(O).end(16),await e7(),E.once("error",A0),E.once("close",t)}catch(d0){A0(d0)}}function h$(w){if(V1)return r6(w,t0.connection("CONNECTION_DESTROYED",W));if(w.cancelled)return;try{return w.state=v,x?m.push(w):(x=w,x.active=!0),xM(w),w1(fM(w))&&!w.describeFirst&&!w.cursorFn&&m.length<I&&(!w.options.onexecute||w.options.onexecute(K1))}catch(O){return m.length===0&&w1(x2),kW(O),!0}}function fM(w){if(w.parameters.length>=65534)throw t0.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return w.options.simple?n().Q().str(w.statement.string+n.N).end():w.describeFirst?Buffer.concat([r7(w),nF]):w.prepare?w.prepared?n6(w):Buffer.concat([r7(w),n6(w)]):PM(w)}function r7(w){return Buffer.concat([YG(w.statement.string,w.parameters,w.statement.types,w.statement.name),L_("S",w.statement.name)])}function n6(w){return Buffer.concat([K_(w.parameters,w.statement.types,w.statement.name,w.cursorName),w.cursorFn?JG("",w.cursorRows):DO])}function PM(w){return Buffer.concat([YG(w.statement.string,w.parameters,w.statement.types),VO,n6(w)])}function xM(w){let O=[],t=[],A0=eJ(w,w.strings[0],w.args[0],O,t,W);!w.tagged&&w.args.forEach((d0)=>ZY(d0,O,t,W)),w.prepare=W.prepare&&("prepare"in w.options?w.options.prepare:!0),w.string=A0,w.signature=w.prepare&&t+A0,w.onlyDescribe&&delete wW[w.signature],w.parameters=w.parameters||O,w.prepared=w.prepare&&w.signature in wW,w.describeFirst=w.onlyDescribe||O.length&&!w.prepared,w.statement=w.prepared?wW[w.signature]:{string:A0,types:t,name:w.prepare?q8+k++:""},typeof W.debug==="function"&&W.debug(c,A0,O,t)}function w1(w,O){if(b0=b0?Buffer.concat([b0,w]):Buffer.from(w),O||b0.length>=1024)return t7(O);return v0===null&&(v0=setImmediate(t7)),!0}function t7(w){let O=E.write(b0,w);return v0!==null&&clearImmediate(v0),b0=v0=null,O}function vM(){kW(t0.connection("CONNECT_TIMEOUT",W,E)),E.destroy()}async function a7(){if(w1(_O),!await new Promise((O)=>E.once("data",(t)=>O(t[0]===83)))&&G==="prefer")return C8();E.removeAllListeners(),E=wO.connect({socket:E,servername:oF.isIP(E.host)?void 0:E.host,...G==="require"||G==="allow"||G==="prefer"?{rejectUnauthorized:!1}:G==="verify-full"?{}:typeof G==="object"?G:{}}),E.on("secureConnect",C8),E.on("error",k8),E.on("close",$G),E.on("drain",s7)}function s7(){!x&&X(K1)}function D9(w){if(I0){if(I0.push(w),N0-=w.length,N0>=0)return}w0=I0?Buffer.concat(I0,F0-N0):w0.length===0?w:Buffer.concat([w0,w],w0.length+w.length);while(w0.length>4){if(F0=w0.readUInt32BE(1),F0>=w0.length){N0=F0-w0.length,I0=[w0];break}try{bM(w0.subarray(0,F0+1))}catch(O){x&&(x.cursorFn||x.describeFirst)&&w1(x2),kW(O)}w0=w0.subarray(F0+1),N0=0,I0=null}}async function e7(){if(V1=!1,D1={},E||(E=await IM()),!E)return;if(m0.start(),W.socket)return G?a7():C8();if(E.on("connect",G?a7:C8),W.path)return E.connect(W.path);E.ssl=G,E.connect(F[g0],z[g0]),E.host=z[g0],E.port=F[g0],g0=(g0+1)%F.length}function WG(){setTimeout(e7,a?a+k0-iF.now():0)}function C8(){try{wW={},s0=W.fetch_types,q8=Math.random().toString(36).slice(2),k=1,U0.start(),E.on("data",D9),C&&E.setKeepAlive&&E.setKeepAlive(!0,1000*C);let w=E_();w1(w)}catch(w){k8(w)}}function k8(w){if(K1.queue===$.connecting&&W.host[e0+1])return;kW(w);while(m.length)r6(m.shift(),w)}function kW(w){W1&&(W1.destroy(w),W1=null),x&&r6(x,w),O1&&(r6(O1,w),O1=null)}function r6(w,O){"query"in O||"parameters"in O||Object.defineProperties(O,{stack:{value:O.stack+w.origin.replace(/.*\n/,`
57
+ `),enumerable:W.debug},query:{value:w.string,enumerable:W.debug},parameters:{value:w.parameters,enumerable:W.debug},args:{value:w.args,enumerable:W.debug},types:{value:w.statement&&w.statement.types,enumerable:W.debug}}),w.reject(O)}function V9(){return V2||(!K1.reserved&&Y(K1),!K1.reserved&&!O1&&!x&&m.length===0?(g$(),new Promise((w)=>E&&E.readyState!=="closed"?E.once("close",w):w())):V2=new Promise((w)=>_W=w))}function g$(){if(V1=!0,W1||x||O1||m.length)k8(t0.connection("CONNECTION_DESTROYED",W));if(clearImmediate(v0),E)E.removeListener("data",D9),E.removeListener("connect",C8),E.readyState==="open"&&E.end(n().X().end());_W&&(_W(),V2=_W=null)}async function $G(w){if(w0=Buffer.alloc(0),N0=0,I0=null,clearImmediate(v0),E.removeListener("data",D9),E.removeListener("connect",C8),h.cancel(),U0.cancel(),m0.cancel(),E.removeAllListeners(),E=null,O1)return WG();!w&&(x||m.length)&&k8(t0.connection("CONNECTION_CLOSED",W,E)),a=iF.now(),w&&W.shared.retries++,k0=(typeof B==="function"?B(W.shared.retries):B)*1000,J(K1,t0.connection("CONNECTION_CLOSED",W,E))}function bM(w,O=w[0]){(O===68?yM:O===100?T_:O===65?J_:O===83?hM:O===90?gM:O===67?mM:O===50?XG:O===49?pM:O===116?uM:O===84?cM:O===82?dM:O===110?tM:O===75?aM:O===69?X_:O===115?G_:O===51?H_:O===71?Q_:O===78?w_:O===72?z_:O===99?U_:O===73?M_:O===86?__:O===118?D_:O===87?F_:V_)(w)}function yM(w){let O=7,t,A0,d0,L1=x.isRaw?new Array(x.statement.columns.length):{};for(let R1=0;R1<x.statement.columns.length;R1++)A0=x.statement.columns[R1],t=w.readInt32BE(O),O+=4,d0=t===-1?null:x.isRaw===!0?w.subarray(O,O+=t):A0.parser===void 0?w.toString("utf8",O,O+=t):A0.parser.array===!0?A0.parser(w.toString("utf8",O+1,O+=t)):A0.parser(w.toString("utf8",O,O+=t)),x.isRaw?L1[R1]=x.isRaw===!0?d0:M.value.from?M.value.from(d0,A0):d0:L1[A0.name]=M.value.from?M.value.from(d0,A0):d0;x.forEachFn?x.forEachFn(M.row.from?M.row.from(L1):L1,e):e[n0++]=M.row.from?M.row.from(L1):L1}function hM(w){let[O,t]=w.toString("utf8",5,w.length-1).split(n.N);if(D1[O]=t,W.parameters[O]!==t)W.parameters[O]=t,N&&N(O,t)}function gM(w){if(x&&x.options.simple&&x.resolve(MW||e),x=MW=null,e=new K8,m0.cancel(),O1){if(q){if(!D1.in_hot_standby||!D1.default_transaction_read_only)return $_();else if(W_(q,D1))return g$()}if(s0)return O1===!0&&(O1=null),sM();O1!==!0&&h$(O1),W.shared.retries=e0=0,O1=null;return}while(m.length&&(x=m.shift())&&(x.active=!0,x.cancelled))tF(W).cancel(x.state,x.cancelled.resolve,x.cancelled.reject);if(x)return;K1.reserved?!K1.reserved.release&&w[5]===73?V2?g$():(K1.reserved=null,X(K1)):K1.reserved():V2?g$():X(K1)}function mM(w){n0=0;for(let O=w.length-1;O>0;O--){if(w[O]===32&&w[O+1]<58&&e.count===null)e.count=+w.toString("utf8",O+1,w.length-1);if(w[O-1]>=65){e.command=w.toString("utf8",5,O),e.state=v;break}}if(y$&&(y$(),y$=null),e.command==="BEGIN"&&H!==1&&!K1.reserved)return kW(t0.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(x.options.simple)return XG();if(x.cursorFn)e.count&&x.cursorFn(e),w1(x2);x.resolve(e)}function pM(){x.parsing=!1}function XG(){!e.statement&&(e.statement=x.statement),e.columns=x.statement.columns}function uM(w){let O=w.readUInt16BE(5);for(let t=0;t<O;++t)!x.statement.types[t]&&(x.statement.types[t]=w.readUInt32BE(7+t*4));x.prepare&&(wW[x.signature]=x.statement),x.describeFirst&&!x.onlyDescribe&&(w1(n6(x)),x.describeFirst=!1)}function cM(w){if(e.command)MW=MW||[e],MW.push(e=new K8),e.count=null,x.statement.columns=null;let O=w.readUInt16BE(5),t=7,A0;x.statement.columns=Array(O);for(let d0=0;d0<O;++d0){A0=t;while(w[t++]!==0);let L1=w.readUInt32BE(t),R1=w.readUInt16BE(t+4),O2=w.readUInt32BE(t+6);x.statement.columns[d0]={name:M.column.from?M.column.from(w.toString("utf8",A0,t-1)):w.toString("utf8",A0,t-1),parser:U[O2],table:L1,number:R1,type:O2},t+=18}if(e.statement=x.statement,x.onlyDescribe)return x.resolve(x.statement),w1(x2)}async function dM(w,O=w.readUInt32BE(5)){(O===3?lM:O===5?oM:O===10?iM:O===11?nM:O===12?rM:O!==0?O_:_$)(w,O)}async function lM(){let w=await O9();w1(n().p().str(w).z(1).end())}async function oM(w){let O="md5"+await rF(Buffer.concat([Buffer.from(await rF(await O9()+Q)),w.subarray(9)]));w1(n().p().str(O).z(1).end())}async function iM(){CW=(await M6.randomBytes(18)).toString("base64"),n().p().str("SCRAM-SHA-256"+n.N);let w=n.i;w1(n.inc(4).str("n,,n=*,r="+CW).i32(n.i-w-4,w).end())}async function nM(w){let O=w.toString("utf8",9).split(",").reduce((R1,O2)=>(R1[O2[0]]=O2.slice(2),R1),{}),t=await M6.pbkdf2Sync(await O9(),Buffer.from(O.s,"base64"),parseInt(O.i),32,"sha256"),A0=await CY(t,"Client Key"),d0="n=*,r="+CW+",r="+O.r+",s="+O.s+",i="+O.i+",c=biws,r="+O.r;p0=(await CY(await CY(t,"Server Key"),d0)).toString("base64");let L1="c=biws,r="+O.r+",p="+AO(A0,Buffer.from(await CY(await LO(A0),d0))).toString("base64");w1(n().p().str(L1).end())}function rM(w){if(w.toString("utf8",9).split(n.N,1)[0].slice(2)===p0)return;kW(t0.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),E.destroy()}function O9(){return Promise.resolve(typeof W.pass==="function"?W.pass():W.pass)}function tM(){if(e.statement=x.statement,e.statement.columns=[],x.onlyDescribe)return x.resolve(x.statement),w1(x2)}function aM(w){v.pid=w.readUInt32BE(5),v.secret=w.readUInt32BE(9)}async function sM(){s0=!1,(await new QW([`
69
58
  select b.oid, b.typarray
70
59
  from pg_catalog.pg_type a
71
60
  left join pg_catalog.pg_type b on b.oid = a.typelem
72
61
  where a.typcategory = 'A'
73
62
  group by b.oid, b.typarray
74
63
  order by b.oid
75
- `],[],wX)).forEach(({oid:K,typarray:TT})=>CU(K,TT))}function CU(Q,K){if(!!T.parsers[K]&&!!T.serializers[K])return;let TT=T.parsers[Q];T.shared.typeArrayMap[Q]=K,T.parsers[K]=(CT)=>DA(CT,TT,K),T.parsers[K].array=!0,T.serializers[K]=(CT)=>_A(CT,T.serializers[Q],T,K)}function ZU(Q,K){return Q==="read-write"&&K.default_transaction_read_only==="on"||Q==="read-only"&&K.default_transaction_read_only==="off"||Q==="primary"&&K.in_hot_standby==="on"||Q==="standby"&&K.in_hot_standby==="off"||Q==="prefer-standby"&&K.in_hot_standby==="off"&&T.host[M$]}function qU(){let Q=new RJ([`
64
+ `],[],h$)).forEach(({oid:O,typarray:t})=>eM(O,t))}function eM(w,O){if(!!W.parsers[O]&&!!W.serializers[O])return;let t=W.parsers[w];W.shared.typeArrayMap[w]=O,W.parsers[O]=(A0)=>dF(A0,t,O),W.parsers[O].array=!0,W.serializers[O]=(A0)=>cF(A0,W.serializers[w],W,O)}function W_(w,O){return w==="read-write"&&O.default_transaction_read_only==="on"||w==="read-only"&&O.default_transaction_read_only==="off"||w==="primary"&&O.in_hot_standby==="on"||w==="standby"&&O.in_hot_standby==="off"||w==="prefer-standby"&&O.in_hot_standby==="off"&&W.host[e0]}function $_(){let w=new QW([`
76
65
  show transaction_read_only;
77
66
  select pg_catalog.pg_is_in_recovery()
78
- `],[],wX,null,{simple:!0});Q.resolve=([[K],[TT]])=>{eT.default_transaction_read_only=K.transaction_read_only,eT.in_hot_standby=TT.pg_is_in_recovery?"on":"off"},Q.execute()}function kU(Q){h&&(h.cursorFn||h.describeFirst)&&f$(s1);let K=G$.postgres(M9(Q));h&&h.retried?uJ(h.retried):h&&h.prepared&&tK.has(K.routine)?yU(h,K):uJ(K)}function yU(Q,K){delete l$[Q.signature],Q.retried=K,wX(Q)}function IU(Q){if(!D)return;let K=9;while(Q[K++]!==0);D(Q.toString("utf8",9,K-1),Q.toString("utf8",K,Q.length-1))}async function jU(){try{let Q=await Promise.resolve(h.cursorFn(n));X$=0,Q===gW?f$(iU(h.portal)):(n=new u0,f$(F7("",h.cursorRows)))}catch(Q){f$(s1),h.reject(Q)}}function xU(){n.count&&h.cursorFn(n),h.resolve(n)}function PU(){z$=new H9.Writable({autoDestroy:!0,write(Q,K,TT){E.write(s().d().raw(Q).end(),TT)},destroy(Q,K){K(Q),E.write(s().f().str(Q+s.N).end()),z$=null},final(Q){E.write(s().c().end()),AX=Q}}),h.resolve(z$)}function bU(){z$=new H9.Readable({read(){E.resume()}}),h.resolve(z$)}function vU(){z$=new H9.Duplex({autoDestroy:!0,read(){E.resume()},write(Q,K,TT){E.write(s().d().raw(Q).end(),TT)},destroy(Q,K){K(Q),E.write(s().f().str(Q+s.N).end()),z$=null},final(Q){E.write(s().c().end()),AX=Q}}),h.resolve(z$)}function hU(Q){z$&&(z$.push(Q.subarray(5))||E.pause())}function mU(){z$&&z$.push(null),z$=null}function gU(Q){_?_(M9(Q)):console.log(M9(Q))}function pU(){}function uU(){uJ(G$.notSupported("FunctionCallResponse"))}function cU(){uJ(G$.notSupported("NegotiateProtocolVersion"))}function oU(Q){console.error("Postgres.js : Unknown Message:",Q[0])}function dU(Q,K){console.error("Postgres.js : Unknown Auth:",K)}function lU(Q,K,TT="",CT=""){let T$,I$;return s().B().str(CT+s.N).str(TT+s.N).i16(0).i16(Q.length),Q.forEach((m$,P1)=>{if(m$===null)return s.i32(4294967295);I$=K[P1],Q[P1]=m$=I$ in T.serializers?T.serializers[I$](m$):""+m$,T$=s.i,s.inc(4).str(m$).i32(s.i-T$-4,T$)}),s.i16(0),s.end()}function X7(Q,K,TT,CT=""){return s().P().str(CT+s.N).str(Q+s.N).i16(K.length),K.forEach((T$,I$)=>s.i32(TT[I$]||0)),s.end()}function nU(Q,K=""){return s().D().str(Q).str(K+s.N).end()}function F7(Q="",K=0){return Buffer.concat([s().E().str(Q+s.N).i32(K).end(),EA])}function iU(Q=""){return Buffer.concat([s().C().str("P").str(Q+s.N).end(),s().S().end()])}function tU(){return XT||s().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:G,database:z,client_encoding:"UTF8"},T.connection)).filter(([,Q])=>Q).map(([Q,K])=>Q+s.N+K).join(s.N)).z(2).end(0)}}function M9(T){let $={},J=5;for(let W=5;W<T.length-1;W++)if(T[W]===0)$[rK[T[J]]]=T.toString("utf8",J+1,W),J=W+1;return $}function RA(T){return p2.createHash("md5").update(T).digest("hex")}function A6(T,$){return p2.createHmac("sha256",T).update($).digest()}function aK(T){return p2.createHash("sha256").update(T).digest()}function sK(T,$){let J=Math.max(T.length,$.length),W=Buffer.allocUnsafe(J);for(let X=0;X<J;X++)W[X]=T[X]^$[X];return W}function z9(T,$){if($=typeof $==="function"?$():$,!$)return{cancel:uW,start:uW};let J;return{cancel(){J&&(clearTimeout(J),J=null)},start(){J&&clearTimeout(J),J=setTimeout(W,$*1000,arguments)}};function W(X){T.apply(null,X),J=null}}var BA=()=>{};function w9(T,$){let J=new Map,W="postgresjs_"+Math.random().toString(36).slice(2),X={},F,Y,G=!1,H=A.sql=T({...$,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...$.connection,replication:"database"},onclose:async function(){if(G)return;Y=null,X.pid=X.secret=void 0,w(await _(H,W,$.publications)),J.forEach((S)=>S.forEach(({onsubscribe:Z})=>Z()))},no_subscribe:!0}),M=H.end,z=H.close;return H.end=async()=>{return G=!0,Y&&await new Promise((S)=>(Y.once("close",S),Y.end())),M()},H.close=async()=>{return Y&&await new Promise((S)=>(Y.once("close",S),Y.end())),z()},A;async function A(S,Z,q=BA,N=BA){if(S=$S(S),!F)F=_(H,W,$.publications);let y={fn:Z,onsubscribe:q},V=J.has(S)?J.get(S).add(y):J.set(S,new Set([y])).get(S),f=()=>{V.delete(y),V.size===0&&J.delete(S)};return F.then((C)=>{return w(C),q(),Y&&Y.on("error",N),{unsubscribe:f,state:X,sql:H}})}function w(S){Y=S.stream,X.pid=S.state.pid,X.secret=S.state.secret}async function _(S,Z,q){if(!q)throw new Error("Missing publication names");let N=await S.unsafe(`CREATE_REPLICATION_SLOT ${Z} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[y]=N,V=await S.unsafe(`START_REPLICATION SLOT ${Z} LOGICAL ${y.consistent_point} (proto_version '1', publication_names '${q}')`).writable(),f={lsn:Buffer.concat(y.consistent_point.split("/").map((E)=>Buffer.from(("00000000"+E).slice(-8),"hex")))};return V.on("data",B),V.on("error",C),V.on("close",S.close),{stream:V,state:N.state};function C(E){console.error("Unexpected error during logical streaming - reconnecting",E)}function B(E){if(E[0]===119)TS(E.subarray(25),f,S.options.parsers,m,$.transform);else if(E[0]===107&&E[17])f.lsn=E.subarray(1,9),$T()}function m(E,XT){let n=XT.relation.schema+"."+XT.relation.table;D("*",E,XT),D("*:"+n,E,XT),XT.relation.keys.length&&D("*:"+n+"="+XT.relation.keys.map((MT)=>E[MT.name]),E,XT),D(XT.command,E,XT),D(XT.command+":"+n,E,XT),XT.relation.keys.length&&D(XT.command+":"+n+"="+XT.relation.keys.map((MT)=>E[MT.name]),E,XT)}function $T(){let E=Buffer.alloc(34);E[0]=114,E.fill(f.lsn,1),E.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),V.write(E)}}function D(S,Z,q){J.has(S)&&J.get(S).forEach(({fn:N})=>N(Z,q,S))}}function eK(T){return new Date(Date.UTC(2000,0,1)+Number(T/BigInt(1000)))}function TS(T,$,J,W,X){let F=(Y,[G,H])=>(Y[G.charCodeAt(0)]=H,Y);Object.entries({R:(Y)=>{let G=1,H=$[Y.readUInt32BE(G)]={schema:Y.toString("utf8",G+=4,G=Y.indexOf(0,G))||"pg_catalog",table:Y.toString("utf8",G+1,G=Y.indexOf(0,G+1)),columns:Array(Y.readUInt16BE(G+=2)),keys:[]};G+=2;let M=0,z;while(G<Y.length)z=H.columns[M++]={key:Y[G++],name:X.column.from?X.column.from(Y.toString("utf8",G,G=Y.indexOf(0,G))):Y.toString("utf8",G,G=Y.indexOf(0,G)),type:Y.readUInt32BE(G+=1),parser:J[Y.readUInt32BE(G)],atttypmod:Y.readUInt32BE(G+=4)},z.key&&H.keys.push(z),G+=4},Y:()=>{},O:()=>{},B:(Y)=>{$.date=eK(Y.readBigInt64BE(9)),$.lsn=Y.subarray(1,9)},I:(Y)=>{let G=1,H=$[Y.readUInt32BE(G)],{row:M}=w6(Y,H.columns,G+=7,X);W(M,{command:"insert",relation:H})},D:(Y)=>{let G=1,H=$[Y.readUInt32BE(G)];G+=4;let M=Y[G]===75;W(M||Y[G]===79?w6(Y,H.columns,G+=3,X).row:null,{command:"delete",relation:H,key:M})},U:(Y)=>{let G=1,H=$[Y.readUInt32BE(G)];G+=4;let M=Y[G]===75,z=M||Y[G]===79?w6(Y,H.columns,G+=3,X):null;z&&(G=z.i);let{row:A}=w6(Y,H.columns,G+3,X);W(A,{command:"update",relation:H,key:M,old:z&&z.row})},T:()=>{},C:()=>{}}).reduce(F,{})[T[0]](T)}function w6(T,$,J,W){let X,F,Y,G=W.raw?new Array($.length):{};for(let H=0;H<$.length;H++)X=T[J++],F=$[H],Y=X===110?null:X===117?void 0:F.parser===void 0?T.toString("utf8",J+4,J+=4+T.readUInt32BE(J)):F.parser.array===!0?F.parser(T.toString("utf8",J+5,J+=4+T.readUInt32BE(J))):F.parser(T.toString("utf8",J+4,J+=4+T.readUInt32BE(J))),W.raw?G[H]=W.raw===!0?Y:W.value.from?W.value.from(Y,F):Y:G[F.name]=W.value.from?W.value.from(Y,F):Y;return{i:J,row:W.row.from?W.row.from(G):G}}function $S(T){let $=T.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!$)throw new Error("Malformed subscribe pattern: "+T);let[,J,W,X]=$;return(J||"*")+(W?":"+(W.indexOf(".")===-1?"public."+W:W):"")+(X?"="+X:"")}import fA from"stream";function Q9(T,$,J=393216){return new Promise(async(W,X)=>{await T.begin(async(F)=>{let Y;!$&&([{oid:$}]=await F`select lo_creat(-1) as oid`);let[{fd:G}]=await F`select lo_open(${$}, ${J}) as fd`,H={writable:z,readable:M,close:()=>F`select lo_close(${G})`.then(Y),tell:()=>F`select lo_tell64(${G})`,read:(A)=>F`select loread(${G}, ${A}) as data`,write:(A)=>F`select lowrite(${G}, ${A})`,truncate:(A)=>F`select lo_truncate64(${G}, ${A})`,seek:(A,w=0)=>F`select lo_lseek64(${G}, ${A}, ${w})`,size:()=>F`
67
+ `],[],h$,null,{simple:!0});w.resolve=([[O],[t]])=>{D1.default_transaction_read_only=O.transaction_read_only,D1.in_hot_standby=t.pg_is_in_recovery?"on":"off"},w.execute()}function X_(w){x&&(x.cursorFn||x.describeFirst)&&w1(x2);let O=t0.postgres(Q5(w));x&&x.retried?kW(x.retried):x&&x.prepared&&OO.has(O.routine)?Y_(x,O):kW(O)}function Y_(w,O){delete wW[w.signature],w.retried=O,h$(w)}function J_(w){if(!K)return;let O=9;while(w[O++]!==0);K(w.toString("utf8",9,O-1),w.toString("utf8",O,w.length-1))}async function G_(){try{let w=await Promise.resolve(x.cursorFn(e));n0=0,w===w$?w1(A_(x.portal)):(e=new K8,w1(JG("",x.cursorRows)))}catch(w){w1(x2),x.reject(w)}}function H_(){e.count&&x.cursorFn(e),x.resolve(e)}function Q_(){W1=new H5.Writable({autoDestroy:!0,write(w,O,t){E.write(n().d().raw(w).end(),t)},destroy(w,O){O(w),E.write(n().f().str(w+n.N).end()),W1=null},final(w){E.write(n().c().end()),y$=w}}),x.resolve(W1)}function z_(){W1=new H5.Readable({read(){E.resume()}}),x.resolve(W1)}function F_(){W1=new H5.Duplex({autoDestroy:!0,read(){E.resume()},write(w,O,t){E.write(n().d().raw(w).end(),t)},destroy(w,O){O(w),E.write(n().f().str(w+n.N).end()),W1=null},final(w){E.write(n().c().end()),y$=w}}),x.resolve(W1)}function T_(w){W1&&(W1.push(w.subarray(5))||E.pause())}function U_(){W1&&W1.push(null),W1=null}function w_(w){V?V(Q5(w)):console.log(Q5(w))}function M_(){}function __(){kW(t0.notSupported("FunctionCallResponse"))}function D_(){kW(t0.notSupported("NegotiateProtocolVersion"))}function V_(w){console.error("Postgres.js : Unknown Message:",w[0])}function O_(w,O){console.error("Postgres.js : Unknown Auth:",O)}function K_(w,O,t="",A0=""){let d0,L1;return n().B().str(A0+n.N).str(t+n.N).i16(0).i16(w.length),w.forEach((R1,O2)=>{if(R1===null)return n.i32(4294967295);L1=O[O2],w[O2]=R1=L1 in W.serializers?W.serializers[L1](R1):""+R1,d0=n.i,n.inc(4).str(R1).i32(n.i-d0-4,d0)}),n.i16(0),n.end()}function YG(w,O,t,A0=""){return n().P().str(A0+n.N).str(w+n.N).i16(O.length),O.forEach((d0,L1)=>n.i32(t[L1]||0)),n.end()}function L_(w,O=""){return n().D().str(w).str(O+n.N).end()}function JG(w="",O=0){return Buffer.concat([n().E().str(w+n.N).i32(O).end(),nF])}function A_(w=""){return Buffer.concat([n().C().str("P").str(w+n.N).end(),n().S().end()])}function E_(){return _0||n().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:Q,database:T,client_encoding:"UTF8"},W.connection)).filter(([,w])=>w).map(([w,O])=>w+n.N+O).join(n.N)).z(2).end(0)}}function Q5(W){let $={},X=5;for(let Y=5;Y<W.length-1;Y++)if(W[Y]===0)$[KO[W[X]]]=W.toString("utf8",X+1,Y),X=Y+1;return $}function rF(W){return M6.createHash("md5").update(W).digest("hex")}function CY(W,$){return M6.createHmac("sha256",W).update($).digest()}function LO(W){return M6.createHash("sha256").update(W).digest()}function AO(W,$){let X=Math.max(W.length,$.length),Y=Buffer.allocUnsafe(X);for(let J=0;J<X;J++)Y[J]=W[J]^$[J];return Y}function z5(W,$){if($=typeof $==="function"?$():$,!$)return{cancel:_$,start:_$};let X;return{cancel(){X&&(clearTimeout(X),X=null)},start(){X&&clearTimeout(X),X=setTimeout(Y,$*1000,arguments)}};function Y(J){W.apply(null,J),X=null}}var aF=()=>{};function T5(W,$){let X=new Map,Y="postgresjs_"+Math.random().toString(36).slice(2),J={},G,H,Q=!1,z=U.sql=W({...$,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...$.connection,replication:"database"},onclose:async function(){if(Q)return;H=null,J.pid=J.secret=void 0,M(await V(z,Y,$.publications)),X.forEach((N)=>N.forEach(({onsubscribe:I})=>I()))},no_subscribe:!0}),F=z.end,T=z.close;return z.end=async()=>{return Q=!0,H&&await new Promise((N)=>(H.once("close",N),H.end())),F()},z.close=async()=>{return H&&await new Promise((N)=>(H.once("close",N),H.end())),T()},U;async function U(N,I,C=aF,B=aF){if(N=BO(N),!G)G=V(z,Y,$.publications);let q={fn:I,onsubscribe:C},m=X.has(N)?X.get(N).add(q):X.set(N,new Set([q])).get(N),c=()=>{m.delete(q),m.size===0&&X.delete(N)};return G.then((v)=>{return M(v),C(),H&&H.on("error",B),{unsubscribe:c,state:J,sql:z}})}function M(N){H=N.stream,J.pid=N.state.pid,J.secret=N.state.secret}async function V(N,I,C){if(!C)throw new Error("Missing publication names");let B=await N.unsafe(`CREATE_REPLICATION_SLOT ${I} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[q]=B,m=await N.unsafe(`START_REPLICATION SLOT ${I} LOGICAL ${q.consistent_point} (proto_version '1', publication_names '${C}')`).writable(),c={lsn:Buffer.concat(q.consistent_point.split("/").map((E)=>Buffer.from(("00000000"+E).slice(-8),"hex")))};return m.on("data",h),m.on("error",v),m.on("close",N.close),{stream:m,state:B.state};function v(E){console.error("Unexpected error during logical streaming - reconnecting",E)}function h(E){if(E[0]===119)NO(E.subarray(25),c,N.options.parsers,U0,$.transform);else if(E[0]===107&&E[17])c.lsn=E.subarray(1,9),m0()}function U0(E,_0){let e=_0.relation.schema+"."+_0.relation.table;K("*",E,_0),K("*:"+e,E,_0),_0.relation.keys.length&&K("*:"+e+"="+_0.relation.keys.map((w0)=>E[w0.name]),E,_0),K(_0.command,E,_0),K(_0.command+":"+e,E,_0),_0.relation.keys.length&&K(_0.command+":"+e+"="+_0.relation.keys.map((w0)=>E[w0.name]),E,_0)}function m0(){let E=Buffer.alloc(34);E[0]=114,E.fill(c.lsn,1),E.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),m.write(E)}}function K(N,I,C){X.has(N)&&X.get(N).forEach(({fn:B})=>B(I,C,N))}}function EO(W){return new Date(Date.UTC(2000,0,1)+Number(W/BigInt(1000)))}function NO(W,$,X,Y,J){let G=(H,[Q,z])=>(H[Q.charCodeAt(0)]=z,H);Object.entries({R:(H)=>{let Q=1,z=$[H.readUInt32BE(Q)]={schema:H.toString("utf8",Q+=4,Q=H.indexOf(0,Q))||"pg_catalog",table:H.toString("utf8",Q+1,Q=H.indexOf(0,Q+1)),columns:Array(H.readUInt16BE(Q+=2)),keys:[]};Q+=2;let F=0,T;while(Q<H.length)T=z.columns[F++]={key:H[Q++],name:J.column.from?J.column.from(H.toString("utf8",Q,Q=H.indexOf(0,Q))):H.toString("utf8",Q,Q=H.indexOf(0,Q)),type:H.readUInt32BE(Q+=1),parser:X[H.readUInt32BE(Q)],atttypmod:H.readUInt32BE(Q+=4)},T.key&&z.keys.push(T),Q+=4},Y:()=>{},O:()=>{},B:(H)=>{$.date=EO(H.readBigInt64BE(9)),$.lsn=H.subarray(1,9)},I:(H)=>{let Q=1,z=$[H.readUInt32BE(Q)],{row:F}=kY(H,z.columns,Q+=7,J);Y(F,{command:"insert",relation:z})},D:(H)=>{let Q=1,z=$[H.readUInt32BE(Q)];Q+=4;let F=H[Q]===75;Y(F||H[Q]===79?kY(H,z.columns,Q+=3,J).row:null,{command:"delete",relation:z,key:F})},U:(H)=>{let Q=1,z=$[H.readUInt32BE(Q)];Q+=4;let F=H[Q]===75,T=F||H[Q]===79?kY(H,z.columns,Q+=3,J):null;T&&(Q=T.i);let{row:U}=kY(H,z.columns,Q+3,J);Y(U,{command:"update",relation:z,key:F,old:T&&T.row})},T:()=>{},C:()=>{}}).reduce(G,{})[W[0]](W)}function kY(W,$,X,Y){let J,G,H,Q=Y.raw?new Array($.length):{};for(let z=0;z<$.length;z++)J=W[X++],G=$[z],H=J===110?null:J===117?void 0:G.parser===void 0?W.toString("utf8",X+4,X+=4+W.readUInt32BE(X)):G.parser.array===!0?G.parser(W.toString("utf8",X+5,X+=4+W.readUInt32BE(X))):G.parser(W.toString("utf8",X+4,X+=4+W.readUInt32BE(X))),Y.raw?Q[z]=Y.raw===!0?H:Y.value.from?Y.value.from(H,G):H:Q[G.name]=Y.value.from?Y.value.from(H,G):H;return{i:X,row:Y.row.from?Y.row.from(Q):Q}}function BO(W){let $=W.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!$)throw new Error("Malformed subscribe pattern: "+W);let[,X,Y,J]=$;return(X||"*")+(Y?":"+(Y.indexOf(".")===-1?"public."+Y:Y):"")+(J?"="+J:"")}import sF from"stream";function U5(W,$,X=393216){return new Promise(async(Y,J)=>{await W.begin(async(G)=>{let H;!$&&([{oid:$}]=await G`select lo_creat(-1) as oid`);let[{fd:Q}]=await G`select lo_open(${$}, ${X}) as fd`,z={writable:T,readable:F,close:()=>G`select lo_close(${Q})`.then(H),tell:()=>G`select lo_tell64(${Q})`,read:(U)=>G`select loread(${Q}, ${U}) as data`,write:(U)=>G`select lowrite(${Q}, ${U})`,truncate:(U)=>G`select lo_truncate64(${Q}, ${U})`,seek:(U,M=0)=>G`select lo_lseek64(${Q}, ${U}, ${M})`,size:()=>G`
79
68
  select
80
- lo_lseek64(${G}, location, 0) as position,
69
+ lo_lseek64(${Q}, location, 0) as position,
81
70
  seek.size
82
71
  from (
83
72
  select
@@ -85,62 +74,62 @@ ${Y}`)}let H=xJ.join(this.baseDir,`${T}/${$}.output.json`);return JSON.parse(lT.
85
74
  tell.location
86
75
  from (select lo_tell64($1) as location) tell
87
76
  ) seek
88
- `};return W(H),new Promise(async(A)=>Y=A);async function M({highWaterMark:A=16384,start:w=0,end:_=1/0}={}){let D=_-w;return w&&await H.seek(w),new fA.Readable({highWaterMark:A,async read(S){let Z=S>D?S-D:S;D-=S;let[{data:q}]=await H.read(Z);if(this.push(q),q.length<S)this.push(null)}})}async function z({highWaterMark:A=16384,start:w=0}={}){return w&&await H.seek(w),new fA.Writable({highWaterMark:A,write(_,D,S){H.write(_).then(()=>S(),S)}})}}).catch(X)})}Object.assign(Q6,{PostgresError:pW,toPascal:g0,pascal:Y9,toCamel:m0,camel:F9,toKebab:p0,kebab:G9,fromPascal:h2,fromCamel:v2,fromKebab:m2,BigInt:{to:20,from:[20],parse:(T)=>BigInt(T),serialize:(T)=>T.toString()}});var cW=Q6;function Q6(T,$){let J=XS(T,$),W=J.no_subscribe||w9(Q6,{...J}),X=!1,F=wJ(),Y=wJ(),G=wJ(),H=wJ(),M=wJ(),z=wJ(),A=wJ(),w=wJ(),_={connecting:Y,reserved:G,closed:H,ended:M,open:z,busy:A,full:w},D=[...Array(J.max)].map(()=>A9(J,_,{onopen:l$,onend:eT,onclose:J1})),S=Z(m);return Object.assign(S,{get parameters(){return J.parameters},largeObject:Q9.bind(null,S),subscribe:W,CLOSE:gW,END:gW,PostgresError:pW,options:J,reserve:y,listen:q,begin:V,close:n,end:XT}),S;function Z(I){return I.debug=J.debug,Object.entries(J.types).reduce((UT,[mT,X$])=>{return UT[mT]=(rT)=>new sJ(rT,X$.to),UT},a),Object.assign(NT,{types:a,typed:a,unsafe:tT,notify:N,array:B,json:C,file:M$}),NT;function a(UT,mT){return new sJ(UT,mT)}function NT(UT,...mT){return UT&&Array.isArray(UT.raw)?new RJ(UT,mT,I,E):typeof UT==="string"&&!mT.length?new g2(J.transform.column.to?J.transform.column.to(UT):UT):new G6(UT,mT)}function tT(UT,mT=[],X$={}){return arguments.length===2&&!Array.isArray(mT)&&(X$=mT,mT=[]),new RJ([UT],mT,I,E,{prepare:!1,...X$,simple:"simple"in X$?X$.simple:mT.length===0})}function M$(UT,mT=[],X$={}){return arguments.length===2&&!Array.isArray(mT)&&(X$=mT,mT=[]),new RJ([],mT,(oT)=>{WS.readFile(UT,"utf8",(q$,gT)=>{if(q$)return oT.reject(q$);oT.strings=[gT],I(oT)})},E,{...X$,simple:"simple"in X$?X$.simple:mT.length===0})}}async function q(I,a,NT){let tT={fn:a,onlisten:NT},M$=q.sql||(q.sql=Q6({...J,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(q.channels).forEach(([oT,{listeners:q$}])=>{delete q.channels[oT],Promise.all(q$.map((gT)=>q(oT,gT.fn,gT.onlisten).catch(()=>{})))})},onnotify(oT,q$){oT in q.channels&&q.channels[oT].listeners.forEach((gT)=>gT.fn(q$))}})),UT=q.channels||(q.channels={});if(I in UT){UT[I].listeners.push(tT);let oT=await UT[I].result;return tT.onlisten&&tT.onlisten(),{state:oT.state,unlisten:rT}}UT[I]={result:M$`listen ${M$.unsafe('"'+I.replace(/"/g,'""')+'"')}`,listeners:[tT]};let X$=await UT[I].result;return tT.onlisten&&tT.onlisten(),{state:X$.state,unlisten:rT};async function rT(){if(I in UT===!1)return;if(UT[I].listeners=UT[I].listeners.filter((oT)=>oT!==tT),UT[I].listeners.length)return;return delete UT[I],M$`unlisten ${M$.unsafe('"'+I.replace(/"/g,'""')+'"')}`}}async function N(I,a){return await S`select pg_notify(${I}, ${""+a})`}async function y(){let I=wJ(),a=z.length?z.shift():await new Promise((M$)=>{F.push({reserve:M$}),H.length&&kT(H.shift())});f(a,G),a.reserved=()=>I.length?a.execute(I.shift()):f(a,G),a.reserved.release=!0;let NT=Z(tT);return NT.release=()=>{a.reserved=null,l$(a)},NT;function tT(M$){a.queue===w?I.push(M$):a.execute(M$)||f(a,w)}}async function V(I,a){!a&&(a=I,I="");let NT=wJ(),tT=0,M$,UT=null;try{return await S.unsafe("begin "+I.replace(/[^a-z ]/ig,""),[],{onexecute:X$}).execute(),await Promise.race([mT(M$,a),new Promise((rT,oT)=>M$.onclose=oT)])}catch(rT){throw rT}async function mT(rT,oT,q$){let gT=Z(z$);gT.savepoint=x1,gT.prepare=(dT)=>UT=dT.replace(/[^a-z0-9$-_. ]/gi);let CJ,k$;q$&&await gT`savepoint ${gT(q$)}`;try{if(k$=await new Promise((dT,ZJ)=>{let pJ=oT(gT);Promise.resolve(Array.isArray(pJ)?Promise.all(pJ):pJ).then(dT,ZJ)}),CJ)throw CJ}catch(dT){throw await(q$?gT`rollback to ${gT(q$)}`:gT`rollback`),dT instanceof pW&&dT.code==="25P02"&&CJ||dT}if(!q$)UT?await gT`prepare transaction '${gT.unsafe(UT)}'`:await gT`commit`;return k$;function x1(dT,ZJ){if(dT&&Array.isArray(dT.raw))return x1((pJ)=>pJ.apply(pJ,arguments));return arguments.length===1&&(ZJ=dT,dT=null),mT(rT,ZJ,"s"+tT+++(dT?"_"+dT:""))}function z$(dT){dT.catch((ZJ)=>CJ||(CJ=ZJ)),rT.queue===w?NT.push(dT):rT.execute(dT)||f(rT,w)}}function X$(rT){M$=rT,f(rT,G),rT.reserved=()=>NT.length?rT.execute(NT.shift()):f(rT,G)}}function f(I,a){return I.queue.remove(I),a.push(I),I.queue=a,a===z?I.idleTimer.start():I.idleTimer.cancel(),I}function C(I){return new sJ(I,3802)}function B(I,a){if(!Array.isArray(I))return B(Array.from(arguments));return new sJ(I,a||(I.length?F6(I)||25:0),J.shared.typeArrayMap)}function m(I){if(X)return I.reject(G$.connection("CONNECTION_ENDED",J,J));if(z.length)return $T(z.shift(),I);if(H.length)return kT(H.shift(),I);A.length?$T(A.shift(),I):F.push(I)}function $T(I,a){return I.execute(a)?f(I,A):f(I,w)}function E(I){return new Promise((a,NT)=>{I.state?I.active?A9(J).cancel(I.state,a,NT):I.cancelled={resolve:a,reject:NT}:(F.remove(I),I.cancelled=!0,I.reject(G$.generic("57014","canceling statement due to user request")),a())})}async function XT({timeout:I=null}={}){if(X)return X;await 1;let a;return X=Promise.race([new Promise((NT)=>I!==null&&(a=setTimeout(MT,I*1000,NT))),Promise.all(D.map((NT)=>NT.end()).concat(q.sql?q.sql.end({timeout:0}):[],W.sql?W.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(a))}async function n(){await Promise.all(D.map((I)=>I.end()))}async function MT(I){await Promise.all(D.map((a)=>a.terminate()));while(F.length)F.shift().reject(G$.connection("CONNECTION_DESTROYED",J));I()}function kT(I,a){return f(I,Y),I.connect(a),I}function eT(I){f(I,M)}function l$(I){if(F.length===0)return f(I,z);let a=Math.ceil(F.length/(Y.length+1)),NT=!0;while(NT&&F.length&&a-- >0){let tT=F.shift();if(tT.reserve)return tT.reserve(I);NT=I.execute(tT)}NT?f(I,A):f(I,w)}function J1(I,a){f(I,H),I.reserved=null,I.onclose&&(I.onclose(a),I.onclose=null),J.onclose&&J.onclose(I.id),F.length&&kT(I,F.shift())}}function XS(T,$){if(T&&T.shared)return T;let J=process.env,W=(!T||typeof T==="string"?$:T)||{},{url:X,multihost:F}=MS(T),Y=[...X.searchParams].reduce((w,[_,D])=>(w[_]=D,w),{}),G=W.hostname||W.host||F||X.hostname||J.PGHOST||"localhost",H=W.port||X.port||J.PGPORT||5432,M=W.user||W.username||X.username||J.PGUSERNAME||J.PGUSER||zS();W.no_prepare&&(W.prepare=!1),Y.sslmode&&(Y.ssl=Y.sslmode,delete Y.sslmode),"timeout"in W&&(console.log("The timeout option is deprecated, use idle_timeout instead"),W.idle_timeout=W.timeout),Y.sslrootcert==="system"&&(Y.ssl="verify-full");let z=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],A={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:GS,max_pipeline:100,backoff:YS,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(G)?G:G.split(",").map((w)=>w.split(":")[0]),port:Array.isArray(H)?H:G.split(",").map((w)=>parseInt(w.split(":")[1]||H)),path:W.path||G.indexOf("/")>-1&&G+"/.s.PGSQL."+H,database:W.database||W.db||(X.pathname||"").slice(1)||J.PGDATABASE||M,user:M,pass:W.pass||W.password||X.password||J.PGPASSWORD||"",...Object.entries(A).reduce((w,[_,D])=>{let S=_ in W?W[_]:(_ in Y)?Y[_]==="disable"||Y[_]==="false"?!1:Y[_]:J["PG"+_.toUpperCase()]||D;return w[_]=typeof S==="string"&&z.includes(_)?+S:S,w},{}),connection:{application_name:"postgres.js",...W.connection,...Object.entries(Y).reduce((w,[_,D])=>((_ in A)||(w[_]=D),w),{})},types:W.types||{},target_session_attrs:FS(W,X,J),onnotice:W.onnotice,onnotify:W.onnotify,onclose:W.onclose,onparameter:W.onparameter,socket:W.socket,transform:HS(W.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...OA(W.types)}}function FS(T,$,J){let W=T.target_session_attrs||$.searchParams.get("target_session_attrs")||J.PGTARGETSESSIONATTRS;if(!W||["read-write","read-only","primary","standby","prefer-standby"].includes(W))return W;throw new Error("target_session_attrs "+W+" is not supported")}function YS(T){return(0.5+Math.random()/2)*Math.min(3**T/100,20)}function GS(){return 60*(30+Math.random()*30)}function HS(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 MS(T){if(!T||typeof T!=="string")return{url:{searchParams:new Map}};let $=T;$=$.slice($.indexOf("://")+3).split(/[?/]/)[0],$=decodeURIComponent($.slice($.indexOf("@")+1));let J=new URL(T.replace($,$.split(",")[0]));return{url:{username:decodeURIComponent(J.username),password:decodeURIComponent(J.password),host:J.host,hostname:J.hostname,port:J.port,pathname:J.pathname,searchParams:J.searchParams},multihost:$.indexOf(",")>-1&&$}}function zS(){try{return JS.userInfo().username}catch(T){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class J${static[O]="SelectionProxyHandler";config;constructor(T){this.config={...T}}get(T,$){if($==="_")return{...T._,selectedFields:new Proxy(T._.selectedFields,this)};if($===pT)return{...T[pT],selectedFields:new Proxy(T[pT].selectedFields,this)};if(typeof $==="symbol")return T[$];let W=(L(T,D$)?T._.selectedFields:L(T,a$)?T[pT].selectedFields:T)[$];if(L(W,c.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!W.isSelectionField)return W.sql;let X=W.clone();return X.isSelectionField=!0,X}if(L(W,c)){if(this.config.sqlBehavior==="sql")return W;throw new Error(`You tried to reference "${$}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(L(W,bT)){if(this.config.alias)return new Proxy(W,new mW(new Proxy(W.table,new k2(this.config.alias,this.config.replaceOriginalName??!1))));return W}if(typeof W!=="object"||W===null)return W;return new Proxy(W,new J$(this.config))}}class O6 extends u${constructor(T,$,J,W){super();this.session=$,this.dialect=J,this.config={table:T,withList:W}}static[O]="PgDelete";config;where(T){return this.config.where=T,this}returning(T=this.config.table[u.Symbol.Columns]){return this.config.returningFields=T,this.config.returning=EJ(T),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:T,...$}=this.dialect.sqlToQuery(this.getSQL());return $}_prepare(T){return vT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return vT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new J$({alias:B$(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}function AS(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((J)=>J.toLowerCase()).join("_")}function wS(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((J,W,X)=>{let F=X===0?W.toLowerCase():`${W[0].toUpperCase()}${W.slice(1)}`;return J+F},"")}function QS(T){return T}class O9{static[O]="CasingCache";cache={};cachedTables={};convert;constructor(T){this.convert=T==="snake_case"?AS:T==="camelCase"?wS:QS}getColumnCasing(T){if(!T.keyAsName)return T.name;let $=T.table[u.Symbol.Schema]??"public",J=T.table[u.Symbol.OriginalName],W=`${$}.${J}.${T.name}`;if(!this.cache[W])this.cacheTable(T.table);return this.cache[W]}cacheTable(T){let $=T[u.Symbol.Schema]??"public",J=T[u.Symbol.OriginalName],W=`${$}.${J}`;if(!this.cachedTables[W]){for(let X of Object.values(T[u.Symbol.Columns])){let F=`${W}.${X.name}`;this.cache[F]=this.convert(X.name)}this.cachedTables[W]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class u2 extends a${static[O]="PgViewBase"}class c0{static[O]="PgDialect";casing;constructor(T){this.casing=new O9(T?.casing)}async migrate(T,$,J){let W=typeof J==="string"?"__drizzle_migrations":J.migrationsTable??"__drizzle_migrations",X=typeof J==="string"?"drizzle":J.migrationsSchema??"drizzle",F=U`
89
- CREATE TABLE IF NOT EXISTS ${U.identifier(X)}.${U.identifier(W)} (
77
+ `};return Y(z),new Promise(async(U)=>H=U);async function F({highWaterMark:U=16384,start:M=0,end:V=1/0}={}){let K=V-M;return M&&await z.seek(M),new sF.Readable({highWaterMark:U,async read(N){let I=N>K?N-K:N;K-=N;let[{data:C}]=await z.read(I);if(this.push(C),C.length<N)this.push(null)}})}async function T({highWaterMark:U=16384,start:M=0}={}){return M&&await z.seek(M),new sF.Writable({highWaterMark:U,write(V,K,N){z.write(V).then(()=>N(),N)}})}}).catch(J)})}Object.assign(IY,{PostgresError:M$,toPascal:V8,pascal:J5,toCamel:D8,camel:Y5,toKebab:O8,kebab:G5,fromPascal:T6,fromCamel:F6,fromKebab:U6,BigInt:{to:20,from:[20],parse:(W)=>BigInt(W),serialize:(W)=>W.toString()}});var D$=IY;function IY(W,$){let X=SO(W,$),Y=X.no_subscribe||T5(IY,{...X}),J=!1,G=s1(),H=s1(),Q=s1(),z=s1(),F=s1(),T=s1(),U=s1(),M=s1(),V={connecting:H,reserved:Q,closed:z,ended:F,open:T,busy:U,full:M},K=[...Array(X.max)].map(()=>F5(X,V,{onopen:wW,onend:D1,onclose:q8})),N=I(U0);return Object.assign(N,{get parameters(){return X.parameters},largeObject:U5.bind(null,N),subscribe:Y,CLOSE:w$,END:w$,PostgresError:M$,options:X,reserve:q,listen:C,begin:m,close:e,end:_0}),N;function I(k){return k.debug=X.debug,Object.entries(X.types).reduce((F0,[k0,n0])=>{return F0[k0]=(p0)=>new mW(p0,n0.to),F0},a),Object.assign(N0,{types:a,typed:a,unsafe:g0,notify:B,array:h,json:v,file:e0}),N0;function a(F0,k0){return new mW(F0,k0)}function N0(F0,...k0){return F0&&Array.isArray(F0.raw)?new QW(F0,k0,k,E):typeof F0==="string"&&!k0.length?new w6(X.transform.column.to?X.transform.column.to(F0):F0):new RY(F0,k0)}function g0(F0,k0=[],n0={}){return arguments.length===2&&!Array.isArray(k0)&&(n0=k0,k0=[]),new QW([F0],k0,k,E,{prepare:!1,...n0,simple:"simple"in n0?n0.simple:k0.length===0})}function e0(F0,k0=[],n0={}){return arguments.length===2&&!Array.isArray(k0)&&(n0=k0,k0=[]),new QW([],k0,(v0)=>{ZO.readFile(F0,"utf8",(V1,I0)=>{if(V1)return v0.reject(V1);v0.strings=[I0],k(v0)})},E,{...n0,simple:"simple"in n0?n0.simple:k0.length===0})}}async function C(k,a,N0){let g0={fn:a,onlisten:N0},e0=C.sql||(C.sql=IY({...X,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(C.channels).forEach(([v0,{listeners:V1}])=>{delete C.channels[v0],Promise.all(V1.map((I0)=>C(v0,I0.fn,I0.onlisten).catch(()=>{})))})},onnotify(v0,V1){v0 in C.channels&&C.channels[v0].listeners.forEach((I0)=>I0.fn(V1))}})),F0=C.channels||(C.channels={});if(k in F0){F0[k].listeners.push(g0);let v0=await F0[k].result;return g0.onlisten&&g0.onlisten(),{state:v0.state,unlisten:p0}}F0[k]={result:e0`listen ${e0.unsafe('"'+k.replace(/"/g,'""')+'"')}`,listeners:[g0]};let n0=await F0[k].result;return g0.onlisten&&g0.onlisten(),{state:n0.state,unlisten:p0};async function p0(){if(k in F0===!1)return;if(F0[k].listeners=F0[k].listeners.filter((v0)=>v0!==g0),F0[k].listeners.length)return;return delete F0[k],e0`unlisten ${e0.unsafe('"'+k.replace(/"/g,'""')+'"')}`}}async function B(k,a){return await N`select pg_notify(${k}, ${""+a})`}async function q(){let k=s1(),a=T.length?T.shift():await new Promise((e0)=>{G.push({reserve:e0}),z.length&&s0(z.shift())});c(a,Q),a.reserved=()=>k.length?a.execute(k.shift()):c(a,Q),a.reserved.release=!0;let N0=I(g0);return N0.release=()=>{a.reserved=null,wW(a)},N0;function g0(e0){a.queue===M?k.push(e0):a.execute(e0)||c(a,M)}}async function m(k,a){!a&&(a=k,k="");let N0=s1(),g0=0,e0,F0=null;try{return await N.unsafe("begin "+k.replace(/[^a-z ]/ig,""),[],{onexecute:n0}).execute(),await Promise.race([k0(e0,a),new Promise((p0,v0)=>e0.onclose=v0)])}catch(p0){throw p0}async function k0(p0,v0,V1){let I0=I(W1);I0.savepoint=V2,I0.prepare=(b0)=>F0=b0.replace(/[^a-z0-9$-_. ]/gi);let MW,O1;V1&&await I0`savepoint ${I0(V1)}`;try{if(O1=await new Promise((b0,_W)=>{let CW=v0(I0);Promise.resolve(Array.isArray(CW)?Promise.all(CW):CW).then(b0,_W)}),MW)throw MW}catch(b0){throw await(V1?I0`rollback to ${I0(V1)}`:I0`rollback`),b0 instanceof M$&&b0.code==="25P02"&&MW||b0}if(!V1)F0?await I0`prepare transaction '${I0.unsafe(F0)}'`:await I0`commit`;return O1;function V2(b0,_W){if(b0&&Array.isArray(b0.raw))return V2((CW)=>CW.apply(CW,arguments));return arguments.length===1&&(_W=b0,b0=null),k0(p0,_W,"s"+g0+++(b0?"_"+b0:""))}function W1(b0){b0.catch((_W)=>MW||(MW=_W)),p0.queue===M?N0.push(b0):p0.execute(b0)||c(p0,M)}}function n0(p0){e0=p0,c(p0,Q),p0.reserved=()=>N0.length?p0.execute(N0.shift()):c(p0,Q)}}function c(k,a){return k.queue.remove(k),a.push(k),k.queue=a,a===T?k.idleTimer.start():k.idleTimer.cancel(),k}function v(k){return new mW(k,3802)}function h(k,a){if(!Array.isArray(k))return h(Array.from(arguments));return new mW(k,a||(k.length?NY(k)||25:0),X.shared.typeArrayMap)}function U0(k){if(J)return k.reject(t0.connection("CONNECTION_ENDED",X,X));if(T.length)return m0(T.shift(),k);if(z.length)return s0(z.shift(),k);U.length?m0(U.shift(),k):G.push(k)}function m0(k,a){return k.execute(a)?c(k,U):c(k,M)}function E(k){return new Promise((a,N0)=>{k.state?k.active?F5(X).cancel(k.state,a,N0):k.cancelled={resolve:a,reject:N0}:(G.remove(k),k.cancelled=!0,k.reject(t0.generic("57014","canceling statement due to user request")),a())})}async function _0({timeout:k=null}={}){if(J)return J;await 1;let a;return J=Promise.race([new Promise((N0)=>k!==null&&(a=setTimeout(w0,k*1000,N0))),Promise.all(K.map((N0)=>N0.end()).concat(C.sql?C.sql.end({timeout:0}):[],Y.sql?Y.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(a))}async function e(){await Promise.all(K.map((k)=>k.end()))}async function w0(k){await Promise.all(K.map((a)=>a.terminate()));while(G.length)G.shift().reject(t0.connection("CONNECTION_DESTROYED",X));k()}function s0(k,a){return c(k,H),k.connect(a),k}function D1(k){c(k,F)}function wW(k){if(G.length===0)return c(k,T);let a=Math.ceil(G.length/(H.length+1)),N0=!0;while(N0&&G.length&&a-- >0){let g0=G.shift();if(g0.reserve)return g0.reserve(k);N0=k.execute(g0)}N0?c(k,U):c(k,M)}function q8(k,a){c(k,z),k.reserved=null,k.onclose&&(k.onclose(a),k.onclose=null),X.onclose&&X.onclose(k.id),G.length&&s0(k,G.shift())}}function SO(W,$){if(W&&W.shared)return W;let X=process.env,Y=(!W||typeof W==="string"?$:W)||{},{url:J,multihost:G}=jO(W),H=[...J.searchParams].reduce((M,[V,K])=>(M[V]=K,M),{}),Q=Y.hostname||Y.host||G||J.hostname||X.PGHOST||"localhost",z=Y.port||J.port||X.PGPORT||5432,F=Y.user||Y.username||J.username||X.PGUSERNAME||X.PGUSER||fO();Y.no_prepare&&(Y.prepare=!1),H.sslmode&&(H.ssl=H.sslmode,delete H.sslmode),"timeout"in Y&&(console.log("The timeout option is deprecated, use idle_timeout instead"),Y.idle_timeout=Y.timeout),H.sslrootcert==="system"&&(H.ssl="verify-full");let T=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],U={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:kO,max_pipeline:100,backoff:CO,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(Q)?Q:Q.split(",").map((M)=>M.split(":")[0]),port:Array.isArray(z)?z:Q.split(",").map((M)=>parseInt(M.split(":")[1]||z)),path:Y.path||Q.indexOf("/")>-1&&Q+"/.s.PGSQL."+z,database:Y.database||Y.db||(J.pathname||"").slice(1)||X.PGDATABASE||F,user:F,pass:Y.pass||Y.password||J.password||X.PGPASSWORD||"",...Object.entries(U).reduce((M,[V,K])=>{let N=V in Y?Y[V]:(V in H)?H[V]==="disable"||H[V]==="false"?!1:H[V]:X["PG"+V.toUpperCase()]||K;return M[V]=typeof N==="string"&&T.includes(V)?+N:N,M},{}),connection:{application_name:"postgres.js",...Y.connection,...Object.entries(H).reduce((M,[V,K])=>((V in U)||(M[V]=K),M),{})},types:Y.types||{},target_session_attrs:qO(Y,J,X),onnotice:Y.onnotice,onnotify:Y.onnotify,onclose:Y.onclose,onparameter:Y.onparameter,socket:Y.socket,transform:IO(Y.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...pF(Y.types)}}function qO(W,$,X){let Y=W.target_session_attrs||$.searchParams.get("target_session_attrs")||X.PGTARGETSESSIONATTRS;if(!Y||["read-write","read-only","primary","standby","prefer-standby"].includes(Y))return Y;throw new Error("target_session_attrs "+Y+" is not supported")}function CO(W){return(0.5+Math.random()/2)*Math.min(3**W/100,20)}function kO(){return 60*(30+Math.random()*30)}function IO(W){return{undefined:W.undefined,column:{from:typeof W.column==="function"?W.column:W.column&&W.column.from,to:W.column&&W.column.to},value:{from:typeof W.value==="function"?W.value:W.value&&W.value.from,to:W.value&&W.value.to},row:{from:typeof W.row==="function"?W.row:W.row&&W.row.from,to:W.row&&W.row.to}}}function jO(W){if(!W||typeof W!=="string")return{url:{searchParams:new Map}};let $=W;$=$.slice($.indexOf("://")+3).split(/[?/]/)[0],$=decodeURIComponent($.slice($.indexOf("@")+1));let X=new URL(W.replace($,$.split(",")[0]));return{url:{username:decodeURIComponent(X.username),password:decodeURIComponent(X.password),host:X.host,hostname:X.hostname,port:X.port,pathname:X.pathname,searchParams:X.searchParams},multihost:$.indexOf(",")>-1&&$}}function fO(){try{return RO.userInfo().username}catch(W){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class i0{static[_]="SelectionProxyHandler";config;constructor(W){this.config={...W}}get(W,$){if($==="_")return{...W._,selectedFields:new Proxy(W._.selectedFields,this)};if($===f0)return{...W[f0],selectedFields:new Proxy(W[f0].selectedFields,this)};if(typeof $==="symbol")return W[$];let Y=(A(W,G1)?W._.selectedFields:A(W,y1)?W[f0].selectedFields:W)[$];if(A(Y,g.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!Y.isSelectionField)return Y.sql;let J=Y.clone();return J.isSelectionField=!0,J}if(A(Y,g)){if(this.config.sqlBehavior==="sql")return Y;throw new Error(`You tried to reference "${$}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(A(Y,S0)){if(this.config.alias)return new Proxy(Y,new U$(new Proxy(Y.table,new $6(this.config.alias,this.config.replaceOriginalName??!1))));return Y}if(typeof Y!=="object"||Y===null)return Y;return new Proxy(Y,new i0(this.config))}}class jY extends C1{constructor(W,$,X,Y){super();this.session=$,this.dialect=X,this.config={table:W,withList:Y}}static[_]="PgDelete";config;where(W){return this.config.where=W,this}returning(W=this.config.table[y.Symbol.Columns]){return this.config.returningFields=W,this.config.returning=GW(W),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:W,...$}=this.dialect.sqlToQuery(this.getSQL());return $}_prepare(W){return q0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,W,!0)})}prepare(W){return this._prepare(W)}authToken;setToken(W){return this.authToken=W,this}execute=(W)=>{return q0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(W,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new i0({alias:U1(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}function PO(W){return(W.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((X)=>X.toLowerCase()).join("_")}function xO(W){return(W.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((X,Y,J)=>{let G=J===0?Y.toLowerCase():`${Y[0].toUpperCase()}${Y.slice(1)}`;return X+G},"")}function vO(W){return W}class w5{static[_]="CasingCache";cache={};cachedTables={};convert;constructor(W){this.convert=W==="snake_case"?PO:W==="camelCase"?xO:vO}getColumnCasing(W){if(!W.keyAsName)return W.name;let $=W.table[y.Symbol.Schema]??"public",X=W.table[y.Symbol.OriginalName],Y=`${$}.${X}.${W.name}`;if(!this.cache[Y])this.cacheTable(W.table);return this.cache[Y]}cacheTable(W){let $=W[y.Symbol.Schema]??"public",X=W[y.Symbol.OriginalName],Y=`${$}.${X}`;if(!this.cachedTables[Y]){for(let J of Object.values(W[y.Symbol.Columns])){let G=`${Y}.${J.name}`;this.cache[G]=this.convert(J.name)}this.cachedTables[Y]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class _6 extends y1{static[_]="PgViewBase"}class L8{static[_]="PgDialect";casing;constructor(W){this.casing=new w5(W?.casing)}async migrate(W,$,X){let Y=typeof X==="string"?"__drizzle_migrations":X.migrationsTable??"__drizzle_migrations",J=typeof X==="string"?"drizzle":X.migrationsSchema??"drizzle",G=D`
78
+ CREATE TABLE IF NOT EXISTS ${D.identifier(J)}.${D.identifier(Y)} (
90
79
  id SERIAL PRIMARY KEY,
91
80
  hash text NOT NULL,
92
81
  created_at bigint
93
82
  )
94
- `;await $.execute(U`CREATE SCHEMA IF NOT EXISTS ${U.identifier(X)}`),await $.execute(F);let G=(await $.all(U`select id, hash, created_at from ${U.identifier(X)}.${U.identifier(W)} order by created_at desc limit 1`))[0];await $.transaction(async(H)=>{for await(let M of T)if(!G||Number(G.created_at)<M.folderMillis){for(let z of M.sql)await H.execute(U.raw(z));await H.execute(U`insert into ${U.identifier(X)}.${U.identifier(W)} ("hash", "created_at") values(${M.hash}, ${M.folderMillis})`)}})}escapeName(T){return`"${T}"`}escapeParam(T){return`$${T+1}`}escapeString(T){return`'${T.replace(/'/g,"''")}'`}buildWithCTE(T){if(!T?.length)return;let $=[U`with `];for(let[J,W]of T.entries())if($.push(U`${U.identifier(W._.alias)} as (${W._.sql})`),J<T.length-1)$.push(U`, `);return $.push(U` `),U.join($)}buildDeleteQuery({table:T,where:$,returning:J,withList:W}){let X=this.buildWithCTE(W),F=J?U` returning ${this.buildSelection(J,{isSingleTable:!0})}`:void 0,Y=$?U` where ${$}`:void 0;return U`${X}delete from ${T}${Y}${F}`}buildUpdateSet(T,$){let J=T[u.Symbol.Columns],W=Object.keys(J).filter((F)=>$[F]!==void 0||J[F]?.onUpdateFn!==void 0),X=W.length;return U.join(W.flatMap((F,Y)=>{let G=J[F],H=$[F]??U.param(G.onUpdateFn(),G),M=U`${U.identifier(this.casing.getColumnCasing(G))} = ${H}`;if(Y<X-1)return[M,U.raw(", ")];return[M]}))}buildUpdateQuery({table:T,set:$,where:J,returning:W,withList:X,from:F,joins:Y}){let G=this.buildWithCTE(X),H=T[Z$.Symbol.Name],M=T[Z$.Symbol.Schema],z=T[Z$.Symbol.OriginalName],A=H===z?void 0:H,w=U`${M?U`${U.identifier(M)}.`:void 0}${U.identifier(z)}${A&&U` ${U.identifier(A)}`}`,_=this.buildUpdateSet(T,$),D=F&&U.join([U.raw(" from "),this.buildFromTable(F)]),S=this.buildJoins(Y),Z=W?U` returning ${this.buildSelection(W,{isSingleTable:!F})}`:void 0,q=J?U` where ${J}`:void 0;return U`${G}update ${w} set ${_}${D}${S}${q}${Z}`}buildSelection(T,{isSingleTable:$=!1}={}){let J=T.length,W=T.flatMap(({field:X},F)=>{let Y=[];if(L(X,c.Aliased)&&X.isSelectionField)Y.push(U.identifier(X.fieldAlias));else if(L(X,c.Aliased)||L(X,c)){let G=L(X,c.Aliased)?X.sql:X;if($)Y.push(new c(G.queryChunks.map((H)=>{if(L(H,P))return U.identifier(this.casing.getColumnCasing(H));return H})));else Y.push(G);if(L(X,c.Aliased))Y.push(U` as ${U.identifier(X.fieldAlias)}`)}else if(L(X,bT))if($)Y.push(U.identifier(this.casing.getColumnCasing(X)));else Y.push(X);if(F<J-1)Y.push(U`, `);return Y});return U.join(W)}buildJoins(T){if(!T||T.length===0)return;let $=[];for(let[J,W]of T.entries()){if(J===0)$.push(U` `);let X=W.table,F=W.lateral?U` lateral`:void 0;if(L(X,Z$)){let Y=X[Z$.Symbol.Name],G=X[Z$.Symbol.Schema],H=X[Z$.Symbol.OriginalName],M=Y===H?void 0:W.alias;$.push(U`${U.raw(W.joinType)} join${F} ${G?U`${U.identifier(G)}.`:void 0}${U.identifier(H)}${M&&U` ${U.identifier(M)}`} on ${W.on}`)}else if(L(X,a$)){let Y=X[pT].name,G=X[pT].schema,H=X[pT].originalName,M=Y===H?void 0:W.alias;$.push(U`${U.raw(W.joinType)} join${F} ${G?U`${U.identifier(G)}.`:void 0}${U.identifier(H)}${M&&U` ${U.identifier(M)}`} on ${W.on}`)}else $.push(U`${U.raw(W.joinType)} join${F} ${X} on ${W.on}`);if(J<T.length-1)$.push(U` `)}return U.join($)}buildFromTable(T){if(L(T,u)&&T[u.Symbol.IsAlias]){let $=U`${U.identifier(T[u.Symbol.OriginalName])}`;if(T[u.Symbol.Schema])$=U`${U.identifier(T[u.Symbol.Schema])}.${$}`;return U`${$} ${U.identifier(T[u.Symbol.Name])}`}return T}buildSelectQuery({withList:T,fields:$,fieldsFlat:J,where:W,having:X,table:F,joins:Y,orderBy:G,groupBy:H,limit:M,offset:z,lockingClause:A,distinct:w,setOperators:_}){let D=J??EJ($);for(let MT of D)if(L(MT.field,bT)&&B$(MT.field.table)!==(L(F,D$)?F._.alias:L(F,u2)?F[pT].name:L(F,c)?void 0:B$(F))&&!((kT)=>Y?.some(({alias:eT})=>eT===(kT[u.Symbol.IsAlias]?B$(kT):kT[u.Symbol.BaseName])))(MT.field.table)){let kT=B$(MT.field.table);throw new Error(`Your "${MT.path.join("->")}" field references a column "${kT}"."${MT.field.name}", but the table "${kT}" is not part of the query! Did you forget to join it?`)}let S=!Y||Y.length===0,Z=this.buildWithCTE(T),q;if(w)q=w===!0?U` distinct`:U` distinct on (${U.join(w.on,U`, `)})`;let N=this.buildSelection(D,{isSingleTable:S}),y=this.buildFromTable(F),V=this.buildJoins(Y),f=W?U` where ${W}`:void 0,C=X?U` having ${X}`:void 0,B;if(G&&G.length>0)B=U` order by ${U.join(G,U`, `)}`;let m;if(H&&H.length>0)m=U` group by ${U.join(H,U`, `)}`;let $T=typeof M==="object"||typeof M==="number"&&M>=0?U` limit ${M}`:void 0,E=z?U` offset ${z}`:void 0,XT=U.empty();if(A){let MT=U` for ${U.raw(A.strength)}`;if(A.config.of)MT.append(U` of ${U.join(Array.isArray(A.config.of)?A.config.of:[A.config.of],U`, `)}`);if(A.config.noWait)MT.append(U` no wait`);else if(A.config.skipLocked)MT.append(U` skip locked`);XT.append(MT)}let n=U`${Z}select${q} ${N} from ${y}${V}${f}${m}${C}${B}${$T}${E}${XT}`;if(_.length>0)return this.buildSetOperations(n,_);return n}buildSetOperations(T,$){let[J,...W]=$;if(!J)throw new Error("Cannot pass undefined values to any set operator");if(W.length===0)return this.buildSetOperationQuery({leftSelect:T,setOperator:J});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:T,setOperator:J}),W)}buildSetOperationQuery({leftSelect:T,setOperator:{type:$,isAll:J,rightSelect:W,limit:X,orderBy:F,offset:Y}}){let G=U`(${T.getSQL()}) `,H=U`(${W.getSQL()})`,M;if(F&&F.length>0){let _=[];for(let D of F)if(L(D,P))_.push(U.identifier(D.name));else if(L(D,c)){for(let S=0;S<D.queryChunks.length;S++){let Z=D.queryChunks[S];if(L(Z,P))D.queryChunks[S]=U.identifier(Z.name)}_.push(U`${D}`)}else _.push(U`${D}`);M=U` order by ${U.join(_,U`, `)} `}let z=typeof X==="object"||typeof X==="number"&&X>=0?U` limit ${X}`:void 0,A=U.raw(`${$} ${J?"all ":""}`),w=Y?U` offset ${Y}`:void 0;return U`${G}${A}${H}${M}${z}${w}`}buildInsertQuery({table:T,values:$,onConflict:J,returning:W,withList:X,select:F,overridingSystemValue_:Y}){let G=[],H=T[u.Symbol.Columns],M=Object.entries(H).filter(([Z,q])=>!q.shouldDisableInsert()),z=M.map(([,Z])=>U.identifier(this.casing.getColumnCasing(Z)));if(F){let Z=$;if(L(Z,c))G.push(Z);else G.push(Z.getSQL())}else{let Z=$;G.push(U.raw("values "));for(let[q,N]of Z.entries()){let y=[];for(let[V,f]of M){let C=N[V];if(C===void 0||L(C,zJ)&&C.value===void 0)if(f.defaultFn!==void 0){let B=f.defaultFn(),m=L(B,c)?B:U.param(B,f);y.push(m)}else if(!f.default&&f.onUpdateFn!==void 0){let B=f.onUpdateFn(),m=L(B,c)?B:U.param(B,f);y.push(m)}else y.push(U`default`);else y.push(C)}if(G.push(y),q<Z.length-1)G.push(U`, `)}}let A=this.buildWithCTE(X),w=U.join(G),_=W?U` returning ${this.buildSelection(W,{isSingleTable:!0})}`:void 0,D=J?U` on conflict ${J}`:void 0,S=Y===!0?U`overriding system value `:void 0;return U`${A}insert into ${T} ${z} ${S}${w}${D}${_}`}buildRefreshMaterializedViewQuery({view:T,concurrently:$,withNoData:J}){let W=$?U` concurrently`:void 0,X=J?U` with no data`:void 0;return U`refresh materialized view${W} ${T}${X}`}prepareTyping(T){if(L(T,i4)||L(T,n4))return"json";else if(L(T,t4))return"decimal";else if(L(T,r4))return"time";else if(L(T,a4)||L(T,s4))return"timestamp";else if(L(T,o4)||L(T,d4))return"date";else if(L(T,e4))return"uuid";else return"none"}sqlToQuery(T,$){return T.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:$})}buildRelationalQueryWithoutPK({fullSchema:T,schema:$,tableNamesMap:J,table:W,tableConfig:X,queryConfig:F,tableAlias:Y,nestedQueryRelation:G,joinOn:H}){let M=[],z,A,w=[],_,D=[];if(F===!0)M=Object.entries(X.columns).map(([q,N])=>({dbKey:N.name,tsKey:q,field:aJ(N,Y),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let Z=Object.fromEntries(Object.entries(X.columns).map(([C,B])=>[C,aJ(B,Y)]));if(F.where){let C=typeof F.where==="function"?F.where(Z,$A()):F.where;_=C&&y2(C,Y)}let q=[],N=[];if(F.columns){let C=!1;for(let[B,m]of Object.entries(F.columns)){if(m===void 0)continue;if(B in X.columns){if(!C&&m===!0)C=!0;N.push(B)}}if(N.length>0)N=C?N.filter((B)=>F.columns?.[B]===!0):Object.keys(X.columns).filter((B)=>!N.includes(B))}else N=Object.keys(X.columns);for(let C of N){let B=X.columns[C];q.push({tsKey:C,value:B})}let y=[];if(F.with)y=Object.entries(F.with).filter((C)=>!!C[1]).map(([C,B])=>({tsKey:C,queryConfig:B,relation:X.relations[C]}));let V;if(F.extras){V=typeof F.extras==="function"?F.extras(Z,{sql:U}):F.extras;for(let[C,B]of Object.entries(V))q.push({tsKey:C,value:cY(B,Y)})}for(let{tsKey:C,value:B}of q)M.push({dbKey:L(B,c.Aliased)?B.fieldAlias:X.columns[C].name,tsKey:C,field:L(B,bT)?aJ(B,Y):B,relationTableTsKey:void 0,isJson:!1,selection:[]});let f=typeof F.orderBy==="function"?F.orderBy(Z,JA()):F.orderBy??[];if(!Array.isArray(f))f=[f];w=f.map((C)=>{if(L(C,bT))return aJ(C,Y);return y2(C,Y)}),z=F.limit,A=F.offset;for(let{tsKey:C,queryConfig:B,relation:m}of y){let $T=XA($,J,m),E=h0(m.referencedTable),XT=J[E],n=`${Y}_${C}`,MT=P2(...$T.fields.map((l$,J1)=>T6(aJ($T.references[J1],n),aJ(l$,Y)))),kT=this.buildRelationalQueryWithoutPK({fullSchema:T,schema:$,tableNamesMap:J,table:T[XT],tableConfig:$[XT],queryConfig:L(m,a1)?B===!0?{limit:1}:{...B,limit:1}:B,tableAlias:n,joinOn:MT,nestedQueryRelation:m}),eT=U`${U.identifier(n)}.${U.identifier("data")}`.as(C);D.push({on:U`true`,table:new D$(kT.sql,{},n),alias:n,joinType:"left",lateral:!0}),M.push({dbKey:C,tsKey:C,field:eT,relationTableTsKey:XT,isJson:!0,selection:kT.selection})}}if(M.length===0)throw new u4({message:`No fields selected for table "${X.tsName}" ("${Y}")`});let S;if(_=P2(H,_),G){let Z=U`json_build_array(${U.join(M.map(({field:y,tsKey:V,isJson:f})=>f?U`${U.identifier(`${Y}_${V}`)}.${U.identifier("data")}`:L(y,c.Aliased)?y.sql:y),U`, `)})`;if(L(G,b2))Z=U`coalesce(json_agg(${Z}${w.length>0?U` order by ${U.join(w,U`, `)}`:void 0}), '[]'::json)`;let q=[{dbKey:"data",tsKey:"data",field:Z.as("data"),isJson:!0,relationTableTsKey:X.tsName,selection:M}];if(z!==void 0||A!==void 0||w.length>0)S=this.buildSelectQuery({table:p4(W,Y),fields:{},fieldsFlat:[{path:[],field:U.raw("*")}],where:_,limit:z,offset:A,orderBy:w,setOperators:[]}),_=void 0,z=void 0,A=void 0,w=[];else S=p4(W,Y);S=this.buildSelectQuery({table:L(S,Z$)?S:new D$(S,{},Y),fields:{},fieldsFlat:q.map(({field:y})=>({path:[],field:L(y,bT)?aJ(y,Y):y})),joins:D,where:_,limit:z,offset:A,orderBy:w,setOperators:[]})}else S=this.buildSelectQuery({table:p4(W,Y),fields:{},fieldsFlat:M.map(({field:Z})=>({path:[],field:L(Z,bT)?aJ(Z,Y):Z})),joins:D,where:_,limit:z,offset:A,orderBy:w,setOperators:[]});return{tableTsKey:X.tsName,sql:S,selection:M}}}class U9{static[O]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class c${static[O]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(T){if(this.fields=T.fields,this.session=T.session,this.dialect=T.dialect,T.withList)this.withList=T.withList;this.distinct=T.distinct}authToken;setToken(T){return this.authToken=T,this}from(T){let $=!!this.fields,J=T,W;if(this.fields)W=this.fields;else if(L(J,D$))W=Object.fromEntries(Object.keys(J._.selectedFields).map((X)=>[X,J[X]]));else if(L(J,u2))W=J[pT].selectedFields;else if(L(J,c))W={};else W=PH(J);return new _9({table:J,fields:W,isPartialSelect:$,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class NA extends U9{static[O]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:T,fields:$,isPartialSelect:J,session:W,dialect:X,withList:F,distinct:Y}){super();this.config={withList:F,table:T,fields:{...$},distinct:Y,setOperators:[]},this.isPartialSelect=J,this.session=W,this.dialect=X,this._={selectedFields:$},this.tableName=V1(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(T){return($,J)=>{let W=this.tableName,X=V1($);if(typeof X==="string"&&this.config.joins?.some((F)=>F.alias===X))throw new Error(`Alias "${X}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof W==="string")this.config.fields={[W]:this.config.fields};if(typeof X==="string"&&!L($,c)){let F=L($,D$)?$._.selectedFields:L($,a$)?$[pT].selectedFields:$[u.Symbol.Columns];this.config.fields[X]=F}}if(typeof J==="function")J=J(new Proxy(this.config.fields,new J$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:J,table:$,joinType:T,alias:X}),typeof X==="string")switch(T){case"left":{this.joinsNotNullableMap[X]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([F])=>[F,!1])),this.joinsNotNullableMap[X]=!0;break}case"inner":{this.joinsNotNullableMap[X]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([F])=>[F,!1])),this.joinsNotNullableMap[X]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");createSetOperator(T,$){return(J)=>{let W=typeof J==="function"?J(OS()):J;if(!I2(this.getSelectedFields(),W.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:T,isAll:$,rightSelect:W}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);intersectAll=this.createSetOperator("intersect",!0);except=this.createSetOperator("except",!1);exceptAll=this.createSetOperator("except",!0);addSetOperators(T){return this.config.setOperators.push(...T),this}where(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new J$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=T,this}having(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new J$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=T,this}groupBy(...T){if(typeof T[0]==="function"){let $=T[0](new Proxy(this.config.fields,new J$({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray($)?$:[$]}else this.config.groupBy=T;return this}orderBy(...T){if(typeof T[0]==="function"){let $=T[0](new Proxy(this.config.fields,new J$({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),J=Array.isArray($)?$:[$];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=J;else this.config.orderBy=J}else{let $=T;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=$;else this.config.orderBy=$}return this}limit(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=T;else this.config.limit=T;return this}offset(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=T;else this.config.offset=T;return this}for(T,$={}){return this.config.lockingClause={strength:T,config:$},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:T,...$}=this.dialect.sqlToQuery(this.getSQL());return $}as(T){return new Proxy(new D$(this.getSQL(),this.config.fields,T),new J$({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new J$({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class _9 extends NA{static[O]="PgSelect";_prepare(T){let{session:$,config:J,dialect:W,joinsNotNullableMap:X,authToken:F}=this;if(!$)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return vT.startActiveSpan("drizzle.prepareQuery",()=>{let Y=EJ(J.fields),G=$.prepareQuery(W.sqlToQuery(this.getSQL()),Y,T,!0);return G.joinsNotNullableMap=X,G.setToken(F)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return vT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})}}xH(_9,[u$]);function oW(T,$){return(J,W,...X)=>{let F=[W,...X].map((Y)=>({type:T,isAll:$,rightSelect:Y}));for(let Y of F)if(!I2(J.getSelectedFields(),Y.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return J.addSetOperators(F)}}var OS=()=>({union:US,unionAll:_S,intersect:DS,intersectAll:KS,except:SS,exceptAll:VS}),US=oW("union",!1),_S=oW("union",!0),DS=oW("intersect",!1),KS=oW("intersect",!0),SS=oW("except",!1),VS=oW("except",!0);class c2{static[O]="PgQueryBuilder";dialect;dialectConfig;constructor(T){this.dialect=L(T,c0)?T:void 0,this.dialectConfig=L(T,c0)?void 0:T}$with=(T,$)=>{let J=this;return{as:(X)=>{if(typeof X==="function")X=X(J);return new Proxy(new Z2(X.getSQL(),$??("getSelectedFields"in X?X.getSelectedFields()??{}:{}),T,!0),new J$({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...T){let $=this;function J(F){return new c$({fields:F??void 0,session:void 0,dialect:$.getDialect(),withList:T})}function W(F){return new c$({fields:F??void 0,session:void 0,dialect:$.getDialect(),distinct:!0})}function X(F,Y){return new c$({fields:Y??void 0,session:void 0,dialect:$.getDialect(),distinct:{on:F}})}return{select:J,selectDistinct:W,selectDistinctOn:X}}select(T){return new c$({fields:T??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(T){return new c$({fields:T??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(T,$){return new c$({fields:$??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:T}})}getDialect(){if(!this.dialect)this.dialect=new c0(this.dialectConfig);return this.dialect}}class U6{constructor(T,$,J,W,X){this.table=T,this.session=$,this.dialect=J,this.withList=W,this.overridingSystemValue_=X}static[O]="PgInsertBuilder";authToken;setToken(T){return this.authToken=T,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(T){if(T=Array.isArray(T)?T:[T],T.length===0)throw new Error("values() must be called with at least one value");let $=T.map((J)=>{let W={},X=this.table[u.Symbol.Columns];for(let F of Object.keys(J)){let Y=J[F];W[F]=L(Y,c)?Y:new zJ(Y,X[F])}return W});return new D9(this.table,$,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(T){let $=typeof T==="function"?T(new c2):T;if(!L($,c)&&!I2(this.table[m4],$._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new D9(this.table,$,this.session,this.dialect,this.withList,!0)}}class D9 extends u${constructor(T,$,J,W,X,F,Y){super();this.session=J,this.dialect=W,this.config={table:T,values:$,withList:X,select:F,overridingSystemValue_:Y}}static[O]="PgInsert";config;returning(T=this.config.table[u.Symbol.Columns]){return this.config.returningFields=T,this.config.returning=EJ(T),this}onConflictDoNothing(T={}){if(T.target===void 0)this.config.onConflict=U`do nothing`;else{let $="";$=Array.isArray(T.target)?T.target.map((W)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(W))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target));let J=T.where?U` where ${T.where}`:void 0;this.config.onConflict=U`(${U.raw($)})${J} do nothing`}return this}onConflictDoUpdate(T){if(T.where&&(T.targetWhere||T.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');let $=T.where?U` where ${T.where}`:void 0,J=T.targetWhere?U` where ${T.targetWhere}`:void 0,W=T.setWhere?U` where ${T.setWhere}`:void 0,X=this.dialect.buildUpdateSet(this.config.table,c4(this.config.table,T.set)),F="";return F=Array.isArray(T.target)?T.target.map((Y)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(Y))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target)),this.config.onConflict=U`(${U.raw(F)})${J} do update set ${X}${$}${W}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:T,...$}=this.dialect.sqlToQuery(this.getSQL());return $}_prepare(T){return vT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return vT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new J$({alias:B$(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class K9 extends u${constructor(T,$,J){super();this.session=$,this.dialect=J,this.config={view:T}}static[O]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:T,...$}=this.dialect.sqlToQuery(this.getSQL());return $}_prepare(T){return vT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,T,!0)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return vT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})}}class _6{constructor(T,$,J,W){this.table=T,this.session=$,this.dialect=J,this.withList=W}static[O]="PgUpdateBuilder";authToken;setToken(T){return this.authToken=T,this}set(T){return new CA(this.table,c4(this.table,T),this.session,this.dialect,this.withList).setToken(this.authToken)}}class CA extends u${constructor(T,$,J,W,X){super();this.session=J,this.dialect=W,this.config={set:$,table:T,withList:X,joins:[]},this.tableName=V1(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[O]="PgUpdate";config;tableName;joinsNotNullableMap;from(T){let $=T,J=V1($);if(typeof J==="string")this.joinsNotNullableMap[J]=!0;return this.config.from=$,this}getTableLikeFields(T){if(L(T,Z$))return T[u.Symbol.Columns];else if(L(T,D$))return T._.selectedFields;return T[pT].selectedFields}createJoin(T){return($,J)=>{let W=V1($);if(typeof W==="string"&&this.config.joins.some((X)=>X.alias===W))throw new Error(`Alias "${W}" is already used in this query`);if(typeof J==="function"){let X=this.config.from&&!L(this.config.from,c)?this.getTableLikeFields(this.config.from):void 0;J=J(new Proxy(this.config.table[u.Symbol.Columns],new J$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),X&&new Proxy(X,new J$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:J,table:$,joinType:T,alias:W}),typeof W==="string")switch(T){case"left":{this.joinsNotNullableMap[W]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([X])=>[X,!1])),this.joinsNotNullableMap[W]=!0;break}case"inner":{this.joinsNotNullableMap[W]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([X])=>[X,!1])),this.joinsNotNullableMap[W]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(T){return this.config.where=T,this}returning(T){if(!T){if(T=Object.assign({},this.config.table[u.Symbol.Columns]),this.config.from){let $=V1(this.config.from);if(typeof $==="string"&&this.config.from&&!L(this.config.from,c)){let J=this.getTableLikeFields(this.config.from);T[$]=J}for(let J of this.config.joins){let W=V1(J.table);if(typeof W==="string"&&!L(J.table,c)){let X=this.getTableLikeFields(J.table);T[W]=X}}}}return this.config.returningFields=T,this.config.returning=EJ(T),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:T,...$}=this.dialect.sqlToQuery(this.getSQL());return $}_prepare(T){let $=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0);return $.joinsNotNullableMap=this.joinsNotNullableMap,$}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return this._prepare().execute(T,this.authToken)};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new J$({alias:B$(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class o2 extends c{constructor(T){super(o2.buildEmbeddedCount(T.source,T.filters).queryChunks);this.params=T,this.mapWith(Number),this.session=T.session,this.sql=o2.buildCount(T.source,T.filters)}sql;token;static[O]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(T,$){return U`(select count(*) from ${T}${U.raw(" where ").if($)}${$})`}static buildCount(T,$){return U`select count(*) as count from ${T}${U.raw(" where ").if($)}${$};`}setToken(T){return this.token=T,this}then(T,$){return Promise.resolve(this.session.count(this.sql,this.token)).then(T,$)}catch(T){return this.then(void 0,T)}finally(T){return this.then(($)=>{return T?.(),$},($)=>{throw T?.(),$})}}class V9{constructor(T,$,J,W,X,F,Y){this.fullSchema=T,this.schema=$,this.tableNamesMap=J,this.table=W,this.tableConfig=X,this.dialect=F,this.session=Y}static[O]="PgRelationalQueryBuilder";findMany(T){return new S9(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?T:{},"many")}findFirst(T){return new S9(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?{...T,limit:1}:{limit:1},"first")}}class S9 extends u${constructor(T,$,J,W,X,F,Y,G,H){super();this.fullSchema=T,this.schema=$,this.tableNamesMap=J,this.table=W,this.tableConfig=X,this.dialect=F,this.session=Y,this.config=G,this.mode=H}static[O]="PgRelationalQuery";_prepare(T){return vT.startActiveSpan("drizzle.prepareQuery",()=>{let{query:$,builtQuery:J}=this._toSQL();return this.session.prepareQuery(J,void 0,T,!0,(W,X)=>{let F=W.map((Y)=>J6(this.schema,this.tableConfig,Y,$.selection,X));if(this.mode==="first")return F[0];return F})})}prepare(T){return this._prepare(T)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let T=this._getQuery(),$=this.dialect.sqlToQuery(T.sql);return{query:T,builtQuery:$}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(T){return this.authToken=T,this}execute(){return vT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class E9 extends u${constructor(T,$,J,W){super();this.execute=T,this.sql=$,this.query=J,this.mapBatchResult=W}static[O]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(T,$){return $?this.mapBatchResult(T):T}_prepare(){return this}isResponseInArrayMode(){return!1}}class d2{constructor(T,$,J){if(this.dialect=T,this.session=$,this._=J?{schema:J.schema,fullSchema:J.fullSchema,tableNamesMap:J.tableNamesMap,session:$}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:$},this.query={},this._.schema)for(let[W,X]of Object.entries(this._.schema))this.query[W]=new V9(J.fullSchema,this._.schema,this._.tableNamesMap,J.fullSchema[W],X,T,$)}static[O]="PgDatabase";query;$with=(T,$)=>{let J=this;return{as:(X)=>{if(typeof X==="function")X=X(new c2(J.dialect));return new Proxy(new Z2(X.getSQL(),$??("getSelectedFields"in X?X.getSelectedFields()??{}:{}),T,!0),new J$({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(T,$){return new o2({source:T,filters:$,session:this.session})}with(...T){let $=this;function J(H){return new c$({fields:H??void 0,session:$.session,dialect:$.dialect,withList:T})}function W(H){return new c$({fields:H??void 0,session:$.session,dialect:$.dialect,withList:T,distinct:!0})}function X(H,M){return new c$({fields:M??void 0,session:$.session,dialect:$.dialect,withList:T,distinct:{on:H}})}function F(H){return new _6(H,$.session,$.dialect,T)}function Y(H){return new U6(H,$.session,$.dialect,T)}function G(H){return new O6(H,$.session,$.dialect,T)}return{select:J,selectDistinct:W,selectDistinctOn:X,update:F,insert:Y,delete:G}}select(T){return new c$({fields:T??void 0,session:this.session,dialect:this.dialect})}selectDistinct(T){return new c$({fields:T??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(T,$){return new c$({fields:$??void 0,session:this.session,dialect:this.dialect,distinct:{on:T}})}update(T){return new _6(T,this.session,this.dialect)}insert(T){return new U6(T,this.session,this.dialect)}delete(T){return new O6(T,this.session,this.dialect)}refreshMaterializedView(T){return new K9(T,this.session,this.dialect)}authToken;execute(T){let $=typeof T==="string"?U.raw(T):T.getSQL(),J=this.dialect.sqlToQuery($),W=this.session.prepareQuery(J,void 0,void 0,!1);return new E9(()=>W.execute(void 0,this.authToken),$,J,(X)=>W.mapResult(X,!0))}transaction(T,$){return this.session.transaction(T,$)}}class ZA{constructor(T,$){this.unique=T,this.name=$}static[O]="PgIndexBuilderOn";on(...T){return new D6(T.map(($)=>{if(L($,c))return $;$=$;let J=new C2($.name,!!$.keyAsName,$.columnType,$.indexConfig);return $.indexConfig=JSON.parse(JSON.stringify($.defaultConfig)),J}),this.unique,!1,this.name)}onOnly(...T){return new D6(T.map(($)=>{if(L($,c))return $;$=$;let J=new C2($.name,!!$.keyAsName,$.columnType,$.indexConfig);return $.indexConfig=$.defaultConfig,J}),this.unique,!0,this.name)}using(T,...$){return new D6($.map((J)=>{if(L(J,c))return J;J=J;let W=new C2(J.name,!!J.keyAsName,J.columnType,J.indexConfig);return J.indexConfig=JSON.parse(JSON.stringify(J.defaultConfig)),W}),this.unique,!0,this.name,T)}}class D6{static[O]="PgIndexBuilder";config;constructor(T,$,J,W,X="btree"){this.config={name:W,columns:T,unique:$,only:J,method:X}}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 qA(this.config,T)}}class qA{static[O]="PgIndex";config;constructor(T,$){this.config={...T,table:$}}}function R9(T){return new ZA(!0,T)}class L9{constructor(T){this.query=T}authToken;getQuery(){return this.query}mapResult(T,$){return T}setToken(T){return this.authToken=T,this}static[O]="PgPreparedQuery";joinsNotNullableMap}class B9{constructor(T){this.dialect=T}static[O]="PgSession";execute(T,$){return vT.startActiveSpan("drizzle.operation",()=>{return vT.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1)}).setToken($).execute(void 0,$)})}all(T){return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1).all()}async count(T,$){let J=await this.execute(T,$);return Number(J[0].count)}}class f9 extends d2{constructor(T,$,J,W=0){super(T,$,J);this.schema=J,this.nestedIndex=W}static[O]="PgTransaction";rollback(){throw new oY}getTransactionConfigSQL(T){let $=[];if(T.isolationLevel)$.push(`isolation level ${T.isolationLevel}`);if(T.accessMode)$.push(T.accessMode);if(typeof T.deferrable==="boolean")$.push(T.deferrable?"deferrable":"not deferrable");return U.raw($.join(" "))}setTransaction(T){return this.session.execute(U`set transaction ${this.getTransactionConfigSQL(T)}`)}}class kA extends L9{constructor(T,$,J,W,X,F,Y){super({sql:$,params:J});this.client=T,this.queryString=$,this.params=J,this.logger=W,this.fields=X,this._isResponseInArrayMode=F,this.customResultMapper=Y}static[O]="PostgresJsPreparedQuery";async execute(T={}){return vT.startActiveSpan("drizzle.execute",async($)=>{let J=uY(this.params,T);$?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(J)}),this.logger.logQuery(this.queryString,J);let{fields:W,queryString:X,client:F,joinsNotNullableMap:Y,customResultMapper:G}=this;if(!W&&!G)return vT.startActiveSpan("drizzle.driver.execute",()=>{return F.unsafe(X,J)});let H=await vT.startActiveSpan("drizzle.driver.execute",()=>{return $?.setAttributes({"drizzle.query.text":X,"drizzle.query.params":JSON.stringify(J)}),F.unsafe(X,J).values()});return vT.startActiveSpan("drizzle.mapResponse",()=>{return G?G(H):H.map((M)=>jH(W,M,Y))})})}all(T={}){return vT.startActiveSpan("drizzle.execute",async($)=>{let J=uY(this.params,T);return $?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(J)}),this.logger.logQuery(this.queryString,J),vT.startActiveSpan("drizzle.driver.execute",()=>{return $?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(J)}),this.client.unsafe(this.queryString,J)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class l2 extends B9{constructor(T,$,J,W={}){super($);this.client=T,this.schema=J,this.options=W,this.logger=W.logger??new lY}static[O]="PostgresJsSession";logger;prepareQuery(T,$,J,W,X){return new kA(this.client,T.sql,T.params,this.logger,$,W,X)}query(T,$){return this.logger.logQuery(T,$),this.client.unsafe(T,$).values()}queryObjects(T,$){return this.client.unsafe(T,$)}transaction(T,$){return this.client.begin(async(J)=>{let W=new l2(J,this.dialect,this.schema,this.options),X=new N9(this.dialect,W,this.schema);if($)await X.setTransaction($);return T(X)})}}class N9 extends f9{constructor(T,$,J,W=0){super(T,$,J,W);this.session=$}static[O]="PostgresJsTransaction";transaction(T){return this.session.client.savepoint(($)=>{let J=new l2($,this.dialect,this.schema,this.session.options),W=new N9(this.dialect,J,this.schema);return T(W)})}}class yA extends d2{static[O]="PostgresJsDatabase"}function dW(T,$={}){let J=(H)=>H;for(let H of["1184","1082","1083","1114","1182","1185","1115","1231"])T.options.parsers[H]=J,T.options.serializers[H]=J;T.options.serializers["114"]=J,T.options.serializers["3802"]=J;let W=new c0({casing:$.casing}),X;if($.logger===!0)X=new dY;else if($.logger!==!1)X=$.logger;let F;if($.schema){let H=WA($.schema,FA);F={fullSchema:$.schema,schema:H.tables,tableNamesMap:H.tableNamesMap}}let Y=new l2(T,W,F,{logger:X}),G=new yA(W,Y,F);return G.$client=T,G}function K6(...T){if(typeof T[0]==="string"){let $=cW(T[0]);return dW($,T[1])}if(bH(T[0])){let{connection:$,client:J,...W}=T[0];if(J)return dW(J,W);if(typeof $==="object"&&$.url!==void 0){let{url:F,...Y}=$,G=cW(F,Y);return dW(G,W)}let X=cW($);return dW(X,W)}return dW(T[0],T[1])}((T)=>{function $(J){return dW({options:{parsers:{},serializers:{}}},J)}T.mock=$})(K6||(K6={}));function IA(T,$){if(T instanceof Promise)throw new Error($)}function ES(T,$){let J={},W=[];for(let X in T){let F=T[X]["~standard"].validate($[X]);if(IA(F,`Validation must be synchronous, but ${X} returned a Promise.`),F.issues){W.push(...F.issues.map((Y)=>({...Y,path:[X,...Y.path??[]]})));continue}J[X]=F.value}if(W.length)return{issues:W};return{value:J}}function jA(T){let $=T.runtimeEnvStrict??T.runtimeEnv??process.env;if(T.emptyStringAsUndefined??!1){for(let[N,y]of Object.entries($))if(y==="")delete $[N]}if(!!T.skipValidation)return $;let X=typeof T.client==="object"?T.client:{},F=typeof T.server==="object"?T.server:{},Y=typeof T.shared==="object"?T.shared:{},G=T.isServer??(typeof window==="undefined"||("Deno"in window)),H=G?{...F,...Y,...X}:{...X,...Y},M=T.createFinalSchema?.(H,G)["~standard"].validate($)??ES(H,$);IA(M,"Validation must be synchronous");let z=T.onValidationError??((N)=>{throw console.error("\u274C Invalid environment variables:",N),new Error("Invalid environment variables")}),A=T.onInvalidAccess??(()=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(M.issues)return z(M.issues);let w=(N)=>{if(!T.clientPrefix)return!0;return!N.startsWith(T.clientPrefix)&&!(N in Y)},_=(N)=>{return G||!w(N)},D=(N)=>{return N==="__esModule"||N==="$$typeof"},S=(T.extends??[]).reduce((N,y)=>{return Object.assign(N,y)},{}),Z=Object.assign(S,M.value);return new Proxy(Z,{get(N,y){if(typeof y!=="string")return;if(D(y))return;if(!_(y))return A(y);return Reflect.get(N,y)}})}var e1=(T)=>Array.isArray(T)?T:[T],xA=(T,$)=>{let J=[[],[]];for(let W of T)if($(W))J[0].push(W);else J[1].push(W);return J},S6=Array,R1=(T,$)=>T.includes($),PA=(T,$=0)=>[...new Array(T)].map((J,W)=>W+$),ST=(T,$,J)=>{if(T===void 0)return $===void 0?[]:Array.isArray($)?$:[$];if(J?.prepend)if(Array.isArray($))T.unshift(...$);else T.unshift($);else if(Array.isArray($))T.push(...$);else T.push($);return T},L1=(T,$)=>{if($===void 0||$===null)return T??[];if(T===void 0||T===null)return e1($);return T.concat($)},bA=(...T)=>T.reduce(L1,[]),eJ=(T,$,J)=>{if(T===void 0)return Array.isArray($)?$:[$];let W=J?.isEqual??((X,F)=>X===F);for(let X of e1($))if(!T.some((F)=>W(F,X)))T.push(X);return T},vA=(T,$)=>T.reduce((J,W)=>{let X=W[$];return J[X]=ST(J[X],W),J},{}),B1=(T,$,J)=>T.length===$.length&&T.every(J?.isEqual?(W,X)=>J.isEqual(W,$[X]):(W,X)=>W===$[X]);var e$=(T,$)=>S$(T)===$,S$=(T)=>{let $=typeof T;return $==="object"?T===null?"null":"object":$==="function"?"object":$},TJ={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},hA={...TJ,function:"a function"};class mA extends Error{}var RT=(T)=>o0(T,mA),o0=(T,$=Error)=>{throw new $(T)};class n2 extends Error{name="ParseError"}var R=(T)=>o0(T,n2),vJ=(T)=>` ${T}`;var YT=(T,$)=>{let J={},W=Array.isArray(T),X=!1;for(let[F,Y]of Object.entries(T).entries()){let G=W?$(F,Y[1]):$(...Y,F);X||=typeof G[0]==="number";let H=Array.isArray(G[0])||G.length===0?G:[G];for(let[M,z]of H)if(typeof M==="object")J[M.group]=ST(J[M.group],z);else J[M]=z}return X?Object.values(J):J};var C9=Object.entries;var V$=(T,$)=>(T in $),lW=(T,$)=>($ in T);class Z9{constructor(T){Object.assign(this,T)}}var gA=class{};class i2 extends gA{}var RS=(T,$)=>{let J={},W={},X;for(X in T)if(X in $)J[X]=T[X];else W[X]=T[X];return[J,W]};var pA=(T,$)=>RS(T,$)[1],T1=(T)=>Object.keys(T).length===0,d0=(T)=>[...Object.entries(T),...Object.getOwnPropertySymbols(T).map(($)=>[$,T[$]])],uA=(T,$)=>Object.defineProperties(T,Object.getOwnPropertyDescriptors($)),cA=(T)=>{let $=Object.keys(T).sort(),J={};for(let W=0;W<$.length;W++)J[$[W]]=T[$[W]];return J};var QJ=vJ("represents an uninitialized value"),oA=(T)=>Object.values(T).filter(($)=>{if(typeof $==="number")return!0;return typeof T[$]!=="number"});var q9={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},k9=globalThis.File??Blob,y9={ArrayBuffer,Blob,File:k9,FormData,Headers,Request,Response,URL},LS={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},l0={...q9,...y9,...LS,String,Number,Boolean},t2=(T)=>{let $=Object.getPrototypeOf(T);while($?.constructor&&(!V$($.constructor.name,l0)||!(T instanceof l0[$.constructor.name])))$=Object.getPrototypeOf($);let J=$?.constructor?.name;if(J===void 0||J==="Object")return;return J},r2=(T)=>typeof T==="object"&&T!==null?t2(T)??"object":S$(T);var hT=Array.isArray,BS={Array:"an array",Function:"a function",Date:"a Date",RegExp:"a RegExp",Error:"an Error",Map:"a Map",Set:"a Set",String:"a String object",Number:"a Number object",Boolean:"a Boolean object",Promise:"a Promise",WeakMap:"a WeakMap",WeakSet:"a WeakSet"},fS={ArrayBuffer:"an ArrayBuffer instance",Blob:"a Blob instance",File:"a File instance",FormData:"a FormData instance",Headers:"a Headers instance",Request:"a Request instance",Response:"a Response instance",URL:"a URL instance"},NS={Int8Array:"an Int8Array",Uint8Array:"a Uint8Array",Uint8ClampedArray:"a Uint8ClampedArray",Int16Array:"an Int16Array",Uint16Array:"a Uint16Array",Int32Array:"an Int32Array",Uint32Array:"a Uint32Array",Float32Array:"a Float32Array",Float64Array:"a Float64Array",BigInt64Array:"a BigInt64Array",BigUint64Array:"a BigUint64Array"},dA={...BS,...fS,...NS},a2=(T)=>{let $=Object(T).name??null;return $&&V$($,l0)&&l0[$]===T?$:null};var I9=(T,$)=>{let J=T.prototype;while(J!==null){if(J===$.prototype)return!0;J=Object.getPrototypeOf(J)}return!1};var lA=(T)=>nA(T,new Map),nA=(T,$)=>{if(typeof T!=="object"||T===null)return T;if($?.has(T))return $.get(T);let J=a2(T.constructor);if(J==="Date")return new Date(T.getTime());if(J&&J!=="Array")return T;let W=Array.isArray(T)?T.slice():Object.create(Object.getPrototypeOf(T)),X=Object.getOwnPropertyDescriptors(T);if($){$.set(T,W);for(let F in X){let Y=X[F];if("get"in Y||"set"in Y)continue;Y.value=nA(Y.value,$)}}return Object.defineProperties(W,X),W};var CS=(T)=>{let $=QJ;return()=>$===QJ?$=T():$},T0=(T)=>typeof T==="function"&&T.length===0;var iA=class extends Function{constructor(...T){let $=T.slice(0,-1),J=T.at(-1);try{super(...$,J)}catch(W){return RT(`Encountered an unexpected error while compiling your definition:
95
- Message: ${W}
96
- Source: (${T.slice(0,-1)}) => {
97
- ${T.at(-1)}
98
- }`)}}};class hJ{constructor(T,...[$]){return Object.assign(Object.setPrototypeOf(T.bind($?.bind??this),this.constructor.prototype),$?.attach)}}var tA=CS(()=>{try{return new Function("return false")()}catch{return!0}});var Zr=vJ("brand");var rA=vJ("arkInferred");var yr=vJ("args");class v${constructor(){}}var ZS=()=>{try{return((new Error().stack?.split(`
99
- `)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},qS=globalThis.process?.env??{},aA={fileName:ZS,env:qS};var sA=(T)=>T[0].toUpperCase()+T.slice(1);var j9=(T)=>new RegExp(kS(T),typeof T==="string"?"":T.flags);var kS=(T)=>{return`^(?:${typeof T==="string"?T:T.source})$`};var f1={negativeLookahead:(T)=>`(?!${T})`,nonCapturingGroup:(T)=>`(?:${T})`},s2="\\",$0={" ":1,"\n":1,"\t":1};var yS=/^-0\.?0*$/.source,Tw=/[1-9]\d*/.source,IS=/\.\d+/.source,jS=/\.\d*[1-9]/.source,$w=(T)=>j9(f1.negativeLookahead(yS)+f1.nonCapturingGroup("-?"+f1.nonCapturingGroup(f1.nonCapturingGroup("0|"+Tw)+f1.nonCapturingGroup(T.decimalPattern)+"?")+(T.allowDecimalOnly?"|"+T.decimalPattern:"")+"?")),eA=$w({decimalPattern:jS,allowDecimalOnly:!1}),xS=eA.test.bind(eA),V6=$w({decimalPattern:IS,allowDecimalOnly:!0}),hr=V6.test.bind(V6),PS=/^-?\d*\.?\d*$/,bS=(T)=>T.length!==0&&PS.test(T),e2=j9(f1.negativeLookahead("^-0$")+"-?"+f1.nonCapturingGroup(f1.nonCapturingGroup("0|"+Tw))),vS=e2.test.bind(e2),x9=/^-?\d+$/,hS=x9.test.bind(x9),Jw={number:"a number",bigint:"a bigint",integer:"an integer"},Ww=(T,$)=>`'${T}' was parsed as ${Jw[$]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,mS=(T,$)=>$==="number"?xS(T):vS(T),gS=(T,$)=>$==="number"?Number(T):Number.parseInt(T),pS=(T,$)=>$==="number"?bS(T):hS(T),Xw=(T,$)=>P9(T,"number",$),Fw=(T,$)=>P9(T,"number",{...$,strict:!0}),Yw=(T,$)=>P9(T,"integer",$),P9=(T,$,J)=>{let W=gS(T,$);if(!Number.isNaN(W)){if(pS(T,$)){if(J?.strict)return mS(T,$)?W:R(Ww(T,$));return W}}return J?.errorOnFail?R(J?.errorOnFail===!0?`Failed to parse ${Jw[$]} from '${T}'`:J?.errorOnFail):void 0},Gw=(T)=>{if(T[T.length-1]!=="n")return;let $=T.slice(0,-1),J;try{J=BigInt($)}catch{return}if(e2.test($))return J;if(x9.test($))return R(Ww(T,"bigint"))};var uS="0.46.0",cS={version:uS,filename:aA.fileName(),FileConstructor:k9},n0=cS,Hw=new Map,b9=Object.create(null),T8=(T)=>{let $=Hw.get(T);if($)return $;let J=oS(T);if(b9[J])J=`${J}${b9[J]++}`;else b9[J]=1;return n0[J]=T,Hw.set(T,J),J},J0=(T)=>/^[$A-Z_a-z][\w$]*$/.test(T),oS=(T)=>{switch(typeof T){case"object":{if(T===null)break;let $=t2(T)??"object";return $[0].toLowerCase()+$.slice(1)}case"function":return J0(T.name)?T.name:"fn";case"symbol":return T.description&&J0(T.description)?T.description:"symbol"}return RT(`Unexpected attempt to register serializable value of type ${S$(T)}`)};var $8=(T)=>typeof T==="string"?JSON.stringify(T):typeof T==="bigint"?`${T}n`:`${T}`;var Mw=(T,$={})=>J8(T,{onUndefined:"$ark.undefined",onBigInt:(J)=>`$ark.bigint-${J}`,...$},[]);var GT=(T,$)=>{switch(S$(T)){case"object":let J=T,W=J.constructor.name;return W==="Object"||W==="Array"?$?.quoteKeys===!1?E6(J,$?.indent??0,""):JSON.stringify(J8(J,nW,[]),null,$?.indent):E6(J,$?.indent??0,"");case"symbol":return nW.onSymbol(T);default:return $8(T)}},E6=(T,$,J)=>{if(typeof T==="function")return nW.onFunction(T);if(typeof T!=="object"||T===null)return $8(T);let W=J+" ".repeat($);if(Array.isArray(T)){if(T.length===0)return"[]";let F=T.map((Y)=>E6(Y,$,W)).join(`,
100
- `+W);return $?`[
101
- ${W}${F}
102
- ${J}]`:`[${F}]`}let X=T.constructor.name;if(X==="Object"){let F=d0(T).map(([Y,G])=>{let H=typeof Y==="symbol"?nW.onSymbol(Y):J0(Y)?Y:JSON.stringify(Y),M=E6(G,$,W);return`${W}${H}: ${M}`});if(F.length===0)return"{}";return $?`{
103
- ${F.join(`,
83
+ `;await $.execute(D`CREATE SCHEMA IF NOT EXISTS ${D.identifier(J)}`),await $.execute(G);let Q=(await $.all(D`select id, hash, created_at from ${D.identifier(J)}.${D.identifier(Y)} order by created_at desc limit 1`))[0];await $.transaction(async(z)=>{for await(let F of W)if(!Q||Number(Q.created_at)<F.folderMillis){for(let T of F.sql)await z.execute(D.raw(T));await z.execute(D`insert into ${D.identifier(J)}.${D.identifier(Y)} ("hash", "created_at") values(${F.hash}, ${F.folderMillis})`)}})}escapeName(W){return`"${W}"`}escapeParam(W){return`$${W+1}`}escapeString(W){return`'${W.replace(/'/g,"''")}'`}buildWithCTE(W){if(!W?.length)return;let $=[D`with `];for(let[X,Y]of W.entries())if($.push(D`${D.identifier(Y._.alias)} as (${Y._.sql})`),X<W.length-1)$.push(D`, `);return $.push(D` `),D.join($)}buildDeleteQuery({table:W,where:$,returning:X,withList:Y}){let J=this.buildWithCTE(Y),G=X?D` returning ${this.buildSelection(X,{isSingleTable:!0})}`:void 0,H=$?D` where ${$}`:void 0;return D`${J}delete from ${W}${H}${G}`}buildUpdateSet(W,$){let X=W[y.Symbol.Columns],Y=Object.keys(X).filter((G)=>$[G]!==void 0||X[G]?.onUpdateFn!==void 0),J=Y.length;return D.join(Y.flatMap((G,H)=>{let Q=X[G],z=$[G]??D.param(Q.onUpdateFn(),Q),F=D`${D.identifier(this.casing.getColumnCasing(Q))} = ${z}`;if(H<J-1)return[F,D.raw(", ")];return[F]}))}buildUpdateQuery({table:W,set:$,where:X,returning:Y,withList:J,from:G,joins:H}){let Q=this.buildWithCTE(J),z=W[_1.Symbol.Name],F=W[_1.Symbol.Schema],T=W[_1.Symbol.OriginalName],U=z===T?void 0:z,M=D`${F?D`${D.identifier(F)}.`:void 0}${D.identifier(T)}${U&&D` ${D.identifier(U)}`}`,V=this.buildUpdateSet(W,$),K=G&&D.join([D.raw(" from "),this.buildFromTable(G)]),N=this.buildJoins(H),I=Y?D` returning ${this.buildSelection(Y,{isSingleTable:!G})}`:void 0,C=X?D` where ${X}`:void 0;return D`${Q}update ${M} set ${V}${K}${N}${C}${I}`}buildSelection(W,{isSingleTable:$=!1}={}){let X=W.length,Y=W.flatMap(({field:J},G)=>{let H=[];if(A(J,g.Aliased)&&J.isSelectionField)H.push(D.identifier(J.fieldAlias));else if(A(J,g.Aliased)||A(J,g)){let Q=A(J,g.Aliased)?J.sql:J;if($)H.push(new g(Q.queryChunks.map((z)=>{if(A(z,j))return D.identifier(this.casing.getColumnCasing(z));return z})));else H.push(Q);if(A(J,g.Aliased))H.push(D` as ${D.identifier(J.fieldAlias)}`)}else if(A(J,S0))if($)H.push(D.identifier(this.casing.getColumnCasing(J)));else H.push(J);if(G<X-1)H.push(D`, `);return H});return D.join(Y)}buildJoins(W){if(!W||W.length===0)return;let $=[];for(let[X,Y]of W.entries()){if(X===0)$.push(D` `);let J=Y.table,G=Y.lateral?D` lateral`:void 0,H=Y.on?D` on ${Y.on}`:void 0;if(A(J,_1)){let Q=J[_1.Symbol.Name],z=J[_1.Symbol.Schema],F=J[_1.Symbol.OriginalName],T=Q===F?void 0:Y.alias;$.push(D`${D.raw(Y.joinType)} join${G} ${z?D`${D.identifier(z)}.`:void 0}${D.identifier(F)}${T&&D` ${D.identifier(T)}`}${H}`)}else if(A(J,y1)){let Q=J[f0].name,z=J[f0].schema,F=J[f0].originalName,T=Q===F?void 0:Y.alias;$.push(D`${D.raw(Y.joinType)} join${G} ${z?D`${D.identifier(z)}.`:void 0}${D.identifier(F)}${T&&D` ${D.identifier(T)}`}${H}`)}else $.push(D`${D.raw(Y.joinType)} join${G} ${J}${H}`);if(X<W.length-1)$.push(D` `)}return D.join($)}buildFromTable(W){if(A(W,y)&&W[y.Symbol.IsAlias]){let $=D`${D.identifier(W[y.Symbol.OriginalName])}`;if(W[y.Symbol.Schema])$=D`${D.identifier(W[y.Symbol.Schema])}.${$}`;return D`${$} ${D.identifier(W[y.Symbol.Name])}`}return W}buildSelectQuery({withList:W,fields:$,fieldsFlat:X,where:Y,having:J,table:G,joins:H,orderBy:Q,groupBy:z,limit:F,offset:T,lockingClause:U,distinct:M,setOperators:V}){let K=X??GW($);for(let w0 of K)if(A(w0.field,S0)&&U1(w0.field.table)!==(A(G,G1)?G._.alias:A(G,_6)?G[f0].name:A(G,g)?void 0:U1(G))&&!((s0)=>H?.some(({alias:D1})=>D1===(s0[y.Symbol.IsAlias]?U1(s0):s0[y.Symbol.BaseName])))(w0.field.table)){let s0=U1(w0.field.table);throw new Error(`Your "${w0.path.join("->")}" field references a column "${s0}"."${w0.field.name}", but the table "${s0}" is not part of the query! Did you forget to join it?`)}let N=!H||H.length===0,I=this.buildWithCTE(W),C;if(M)C=M===!0?D` distinct`:D` distinct on (${D.join(M.on,D`, `)})`;let B=this.buildSelection(K,{isSingleTable:N}),q=this.buildFromTable(G),m=this.buildJoins(H),c=Y?D` where ${Y}`:void 0,v=J?D` having ${J}`:void 0,h;if(Q&&Q.length>0)h=D` order by ${D.join(Q,D`, `)}`;let U0;if(z&&z.length>0)U0=D` group by ${D.join(z,D`, `)}`;let m0=typeof F==="object"||typeof F==="number"&&F>=0?D` limit ${F}`:void 0,E=T?D` offset ${T}`:void 0,_0=D.empty();if(U){let w0=D` for ${D.raw(U.strength)}`;if(U.config.of)w0.append(D` of ${D.join(Array.isArray(U.config.of)?U.config.of:[U.config.of],D`, `)}`);if(U.config.noWait)w0.append(D` nowait`);else if(U.config.skipLocked)w0.append(D` skip locked`);_0.append(w0)}let e=D`${I}select${C} ${B} from ${q}${m}${c}${U0}${v}${h}${m0}${E}${_0}`;if(V.length>0)return this.buildSetOperations(e,V);return e}buildSetOperations(W,$){let[X,...Y]=$;if(!X)throw new Error("Cannot pass undefined values to any set operator");if(Y.length===0)return this.buildSetOperationQuery({leftSelect:W,setOperator:X});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:W,setOperator:X}),Y)}buildSetOperationQuery({leftSelect:W,setOperator:{type:$,isAll:X,rightSelect:Y,limit:J,orderBy:G,offset:H}}){let Q=D`(${W.getSQL()}) `,z=D`(${Y.getSQL()})`,F;if(G&&G.length>0){let V=[];for(let K of G)if(A(K,j))V.push(D.identifier(K.name));else if(A(K,g)){for(let N=0;N<K.queryChunks.length;N++){let I=K.queryChunks[N];if(A(I,j))K.queryChunks[N]=D.identifier(I.name)}V.push(D`${K}`)}else V.push(D`${K}`);F=D` order by ${D.join(V,D`, `)} `}let T=typeof J==="object"||typeof J==="number"&&J>=0?D` limit ${J}`:void 0,U=D.raw(`${$} ${X?"all ":""}`),M=H?D` offset ${H}`:void 0;return D`${Q}${U}${z}${F}${T}${M}`}buildInsertQuery({table:W,values:$,onConflict:X,returning:Y,withList:J,select:G,overridingSystemValue_:H}){let Q=[],z=W[y.Symbol.Columns],F=Object.entries(z).filter(([I,C])=>!C.shouldDisableInsert()),T=F.map(([,I])=>D.identifier(this.casing.getColumnCasing(I)));if(G){let I=$;if(A(I,g))Q.push(I);else Q.push(I.getSQL())}else{let I=$;Q.push(D.raw("values "));for(let[C,B]of I.entries()){let q=[];for(let[m,c]of F){let v=B[m];if(v===void 0||A(v,a1)&&v.value===void 0)if(c.defaultFn!==void 0){let h=c.defaultFn(),U0=A(h,g)?h:D.param(h,c);q.push(U0)}else if(!c.default&&c.onUpdateFn!==void 0){let h=c.onUpdateFn(),U0=A(h,g)?h:D.param(h,c);q.push(U0)}else q.push(D`default`);else q.push(v)}if(Q.push(q),C<I.length-1)Q.push(D`, `)}}let U=this.buildWithCTE(J),M=D.join(Q),V=Y?D` returning ${this.buildSelection(Y,{isSingleTable:!0})}`:void 0,K=X?D` on conflict ${X}`:void 0,N=H===!0?D`overriding system value `:void 0;return D`${U}insert into ${W} ${T} ${N}${M}${K}${V}`}buildRefreshMaterializedViewQuery({view:W,concurrently:$,withNoData:X}){let Y=$?D` concurrently`:void 0,J=X?D` with no data`:void 0;return D`refresh materialized view${Y} ${W}${J}`}prepareTyping(W){if(A(W,UY)||A(W,TY))return"json";else if(A(W,wY))return"decimal";else if(A(W,MY))return"time";else if(A(W,_Y)||A(W,DY))return"timestamp";else if(A(W,zY)||A(W,FY))return"date";else if(A(W,VY))return"uuid";else return"none"}sqlToQuery(W,$){return W.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:$})}buildRelationalQueryWithoutPK({fullSchema:W,schema:$,tableNamesMap:X,table:Y,tableConfig:J,queryConfig:G,tableAlias:H,nestedQueryRelation:Q,joinOn:z}){let F=[],T,U,M=[],V,K=[];if(G===!0)F=Object.entries(J.columns).map(([C,B])=>({dbKey:B.name,tsKey:C,field:gW(B,H),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let I=Object.fromEntries(Object.entries(J.columns).map(([v,h])=>[v,gW(h,H)]));if(G.where){let v=typeof G.where==="function"?G.where(I,CF()):G.where;V=v&&X6(v,H)}let C=[],B=[];if(G.columns){let v=!1;for(let[h,U0]of Object.entries(G.columns)){if(U0===void 0)continue;if(h in J.columns){if(!v&&U0===!0)v=!0;B.push(h)}}if(B.length>0)B=v?B.filter((h)=>G.columns?.[h]===!0):Object.keys(J.columns).filter((h)=>!B.includes(h))}else B=Object.keys(J.columns);for(let v of B){let h=J.columns[v];C.push({tsKey:v,value:h})}let q=[];if(G.with)q=Object.entries(G.with).filter((v)=>!!v[1]).map(([v,h])=>({tsKey:v,queryConfig:h,relation:J.relations[v]}));let m;if(G.extras){m=typeof G.extras==="function"?G.extras(I,{sql:D}):G.extras;for(let[v,h]of Object.entries(m))C.push({tsKey:v,value:pJ(h,H)})}for(let{tsKey:v,value:h}of C)F.push({dbKey:A(h,g.Aliased)?h.fieldAlias:J.columns[v].name,tsKey:v,field:A(h,S0)?gW(h,H):h,relationTableTsKey:void 0,isJson:!1,selection:[]});let c=typeof G.orderBy==="function"?G.orderBy(I,kF()):G.orderBy??[];if(!Array.isArray(c))c=[c];M=c.map((v)=>{if(A(v,S0))return gW(v,H);return X6(v,H)}),T=G.limit,U=G.offset;for(let{tsKey:v,queryConfig:h,relation:U0}of q){let m0=jF($,X,U0),E=_8(U0.referencedTable),_0=X[E],e=`${H}_${v}`,w0=Q6(...m0.fields.map((wW,q8)=>OY(gW(m0.references[q8],e),gW(wW,H)))),s0=this.buildRelationalQueryWithoutPK({fullSchema:W,schema:$,tableNamesMap:X,table:W[_0],tableConfig:$[_0],queryConfig:A(U0,P2)?h===!0?{limit:1}:{...h,limit:1}:h,tableAlias:e,joinOn:w0,nestedQueryRelation:U0}),D1=D`${D.identifier(e)}.${D.identifier("data")}`.as(v);K.push({on:D`true`,table:new G1(s0.sql,{},e),alias:e,joinType:"left",lateral:!0}),F.push({dbKey:v,tsKey:v,field:D1,relationTableTsKey:_0,isJson:!0,selection:s0.selection})}}if(F.length===0)throw new HY({message:`No fields selected for table "${J.tsName}" ("${H}")`});let N;if(V=Q6(z,V),Q){let I=D`json_build_array(${D.join(F.map(({field:q,tsKey:m,isJson:c})=>c?D`${D.identifier(`${H}_${m}`)}.${D.identifier("data")}`:A(q,g.Aliased)?q.sql:q),D`, `)})`;if(A(Q,z6))I=D`coalesce(json_agg(${I}${M.length>0?D` order by ${D.join(M,D`, `)}`:void 0}), '[]'::json)`;let C=[{dbKey:"data",tsKey:"data",field:I.as("data"),isJson:!0,relationTableTsKey:J.tsName,selection:F}];if(T!==void 0||U!==void 0||M.length>0)N=this.buildSelectQuery({table:GY(Y,H),fields:{},fieldsFlat:[{path:[],field:D.raw("*")}],where:V,limit:T,offset:U,orderBy:M,setOperators:[]}),V=void 0,T=void 0,U=void 0,M=[];else N=GY(Y,H);N=this.buildSelectQuery({table:A(N,_1)?N:new G1(N,{},H),fields:{},fieldsFlat:C.map(({field:q})=>({path:[],field:A(q,S0)?gW(q,H):q})),joins:K,where:V,limit:T,offset:U,orderBy:M,setOperators:[]})}else N=this.buildSelectQuery({table:GY(Y,H),fields:{},fieldsFlat:F.map(({field:I})=>({path:[],field:A(I,S0)?gW(I,H):I})),joins:K,where:V,limit:T,offset:U,orderBy:M,setOperators:[]});return{tableTsKey:J.tsName,sql:N,selection:F}}}class M5{static[_]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class I1{static[_]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(W){if(this.fields=W.fields,this.session=W.session,this.dialect=W.dialect,W.withList)this.withList=W.withList;this.distinct=W.distinct}authToken;setToken(W){return this.authToken=W,this}from(W){let $=!!this.fields,X=W,Y;if(this.fields)Y=this.fields;else if(A(X,G1))Y=Object.fromEntries(Object.keys(X._.selectedFields).map((J)=>[J,X[J]]));else if(A(X,_6))Y=X[f0].selectedFields;else if(A(X,g))Y={};else Y=zQ(X);return new _5({table:X,fields:Y,isPartialSelect:$,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class eF extends M5{static[_]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:W,fields:$,isPartialSelect:X,session:Y,dialect:J,withList:G,distinct:H}){super();this.config={withList:G,table:W,fields:{...$},distinct:H,setOperators:[]},this.isPartialSelect=X,this.session=Y,this.dialect=J,this._={selectedFields:$},this.tableName=Y2(W),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(W,$){return(X,Y)=>{let J=this.tableName,G=Y2(X);if(typeof G==="string"&&this.config.joins?.some((H)=>H.alias===G))throw new Error(`Alias "${G}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof J==="string")this.config.fields={[J]:this.config.fields};if(typeof G==="string"&&!A(X,g)){let H=A(X,G1)?X._.selectedFields:A(X,y1)?X[f0].selectedFields:X[y.Symbol.Columns];this.config.fields[G]=H}}if(typeof Y==="function")Y=Y(new Proxy(this.config.fields,new i0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:Y,table:X,joinType:W,alias:G,lateral:$}),typeof G==="string")switch(W){case"left":{this.joinsNotNullableMap[G]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([H])=>[H,!1])),this.joinsNotNullableMap[G]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[G]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([H])=>[H,!1])),this.joinsNotNullableMap[G]=!1;break}}return this}}leftJoin=this.createJoin("left",!1);leftJoinLateral=this.createJoin("left",!0);rightJoin=this.createJoin("right",!1);innerJoin=this.createJoin("inner",!1);innerJoinLateral=this.createJoin("inner",!0);fullJoin=this.createJoin("full",!1);crossJoin=this.createJoin("cross",!1);crossJoinLateral=this.createJoin("cross",!0);createSetOperator(W,$){return(X)=>{let Y=typeof X==="function"?X(bO()):X;if(!Y6(this.getSelectedFields(),Y.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:W,isAll:$,rightSelect:Y}),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(W){return this.config.setOperators.push(...W),this}where(W){if(typeof W==="function")W=W(new Proxy(this.config.fields,new i0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=W,this}having(W){if(typeof W==="function")W=W(new Proxy(this.config.fields,new i0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=W,this}groupBy(...W){if(typeof W[0]==="function"){let $=W[0](new Proxy(this.config.fields,new i0({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray($)?$:[$]}else this.config.groupBy=W;return this}orderBy(...W){if(typeof W[0]==="function"){let $=W[0](new Proxy(this.config.fields,new i0({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),X=Array.isArray($)?$:[$];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=X;else this.config.orderBy=X}else{let $=W;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=$;else this.config.orderBy=$}return this}limit(W){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=W;else this.config.limit=W;return this}offset(W){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=W;else this.config.offset=W;return this}for(W,$={}){return this.config.lockingClause={strength:W,config:$},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:W,...$}=this.dialect.sqlToQuery(this.getSQL());return $}as(W){return new Proxy(new G1(this.getSQL(),this.config.fields,W),new i0({alias:W,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new i0({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class _5 extends eF{static[_]="PgSelect";_prepare(W){let{session:$,config:X,dialect:Y,joinsNotNullableMap:J,authToken:G}=this;if(!$)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return q0.startActiveSpan("drizzle.prepareQuery",()=>{let H=GW(X.fields),Q=$.prepareQuery(Y.sqlToQuery(this.getSQL()),H,W,!0);return Q.joinsNotNullableMap=J,Q.setToken(G)})}prepare(W){return this._prepare(W)}authToken;setToken(W){return this.authToken=W,this}execute=(W)=>{return q0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(W,this.authToken)})}}QQ(_5,[C1]);function V$(W,$){return(X,Y,...J)=>{let G=[Y,...J].map((H)=>({type:W,isAll:$,rightSelect:H}));for(let H of G)if(!Y6(X.getSelectedFields(),H.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return X.addSetOperators(G)}}var bO=()=>({union:yO,unionAll:hO,intersect:gO,intersectAll:mO,except:pO,exceptAll:uO}),yO=V$("union",!1),hO=V$("union",!0),gO=V$("intersect",!1),mO=V$("intersect",!0),pO=V$("except",!1),uO=V$("except",!0);class D6{static[_]="PgQueryBuilder";dialect;dialectConfig;constructor(W){this.dialect=A(W,L8)?W:void 0,this.dialectConfig=A(W,L8)?void 0:W}$with=(W,$)=>{let X=this;return{as:(J)=>{if(typeof J==="function")J=J(X);return new Proxy(new e4(J.getSQL(),$??("getSelectedFields"in J?J.getSelectedFields()??{}:{}),W,!0),new i0({alias:W,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...W){let $=this;function X(G){return new I1({fields:G??void 0,session:void 0,dialect:$.getDialect(),withList:W})}function Y(G){return new I1({fields:G??void 0,session:void 0,dialect:$.getDialect(),distinct:!0})}function J(G,H){return new I1({fields:H??void 0,session:void 0,dialect:$.getDialect(),distinct:{on:G}})}return{select:X,selectDistinct:Y,selectDistinctOn:J}}select(W){return new I1({fields:W??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(W){return new I1({fields:W??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(W,$){return new I1({fields:$??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:W}})}getDialect(){if(!this.dialect)this.dialect=new L8(this.dialectConfig);return this.dialect}}class fY{constructor(W,$,X,Y,J){this.table=W,this.session=$,this.dialect=X,this.withList=Y,this.overridingSystemValue_=J}static[_]="PgInsertBuilder";authToken;setToken(W){return this.authToken=W,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(W){if(W=Array.isArray(W)?W:[W],W.length===0)throw new Error("values() must be called with at least one value");let $=W.map((X)=>{let Y={},J=this.table[y.Symbol.Columns];for(let G of Object.keys(X)){let H=X[G];Y[G]=A(H,g)?H:new a1(H,J[G])}return Y});return new D5(this.table,$,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(W){let $=typeof W==="function"?W(new D6):W;if(!A($,g)&&!Y6(this.table[YY],$._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new D5(this.table,$,this.session,this.dialect,this.withList,!0)}}class D5 extends C1{constructor(W,$,X,Y,J,G,H){super();this.session=X,this.dialect=Y,this.config={table:W,values:$,withList:J,select:G,overridingSystemValue_:H}}static[_]="PgInsert";config;returning(W=this.config.table[y.Symbol.Columns]){return this.config.returningFields=W,this.config.returning=GW(W),this}onConflictDoNothing(W={}){if(W.target===void 0)this.config.onConflict=D`do nothing`;else{let $="";$=Array.isArray(W.target)?W.target.map((Y)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(Y))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(W.target));let X=W.where?D` where ${W.where}`:void 0;this.config.onConflict=D`(${D.raw($)})${X} do nothing`}return this}onConflictDoUpdate(W){if(W.where&&(W.targetWhere||W.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');let $=W.where?D` where ${W.where}`:void 0,X=W.targetWhere?D` where ${W.targetWhere}`:void 0,Y=W.setWhere?D` where ${W.setWhere}`:void 0,J=this.dialect.buildUpdateSet(this.config.table,QY(this.config.table,W.set)),G="";return G=Array.isArray(W.target)?W.target.map((H)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(H))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(W.target)),this.config.onConflict=D`(${D.raw(G)})${X} do update set ${J}${$}${Y}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:W,...$}=this.dialect.sqlToQuery(this.getSQL());return $}_prepare(W){return q0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,W,!0)})}prepare(W){return this._prepare(W)}authToken;setToken(W){return this.authToken=W,this}execute=(W)=>{return q0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(W,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new i0({alias:U1(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class V5 extends C1{constructor(W,$,X){super();this.session=$,this.dialect=X,this.config={view:W}}static[_]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:W,...$}=this.dialect.sqlToQuery(this.getSQL());return $}_prepare(W){return q0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,W,!0)})}prepare(W){return this._prepare(W)}authToken;setToken(W){return this.authToken=W,this}execute=(W)=>{return q0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(W,this.authToken)})}}class PY{constructor(W,$,X,Y){this.table=W,this.session=$,this.dialect=X,this.withList=Y}static[_]="PgUpdateBuilder";authToken;setToken(W){return this.authToken=W,this}set(W){return new WT(this.table,QY(this.table,W),this.session,this.dialect,this.withList).setToken(this.authToken)}}class WT extends C1{constructor(W,$,X,Y,J){super();this.session=X,this.dialect=Y,this.config={set:$,table:W,withList:J,joins:[]},this.tableName=Y2(W),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[_]="PgUpdate";config;tableName;joinsNotNullableMap;from(W){let $=W,X=Y2($);if(typeof X==="string")this.joinsNotNullableMap[X]=!0;return this.config.from=$,this}getTableLikeFields(W){if(A(W,_1))return W[y.Symbol.Columns];else if(A(W,G1))return W._.selectedFields;return W[f0].selectedFields}createJoin(W){return($,X)=>{let Y=Y2($);if(typeof Y==="string"&&this.config.joins.some((J)=>J.alias===Y))throw new Error(`Alias "${Y}" is already used in this query`);if(typeof X==="function"){let J=this.config.from&&!A(this.config.from,g)?this.getTableLikeFields(this.config.from):void 0;X=X(new Proxy(this.config.table[y.Symbol.Columns],new i0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),J&&new Proxy(J,new i0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:X,table:$,joinType:W,alias:Y}),typeof Y==="string")switch(W){case"left":{this.joinsNotNullableMap[Y]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[Y]=!0;break}case"inner":{this.joinsNotNullableMap[Y]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[Y]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(W){return this.config.where=W,this}returning(W){if(!W){if(W=Object.assign({},this.config.table[y.Symbol.Columns]),this.config.from){let $=Y2(this.config.from);if(typeof $==="string"&&this.config.from&&!A(this.config.from,g)){let X=this.getTableLikeFields(this.config.from);W[$]=X}for(let X of this.config.joins){let Y=Y2(X.table);if(typeof Y==="string"&&!A(X.table,g)){let J=this.getTableLikeFields(X.table);W[Y]=J}}}}return this.config.returningFields=W,this.config.returning=GW(W),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:W,...$}=this.dialect.sqlToQuery(this.getSQL());return $}_prepare(W){let $=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,W,!0);return $.joinsNotNullableMap=this.joinsNotNullableMap,$}prepare(W){return this._prepare(W)}authToken;setToken(W){return this.authToken=W,this}execute=(W)=>{return this._prepare().execute(W,this.authToken)};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new i0({alias:U1(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class V6 extends g{constructor(W){super(V6.buildEmbeddedCount(W.source,W.filters).queryChunks);this.params=W,this.mapWith(Number),this.session=W.session,this.sql=V6.buildCount(W.source,W.filters)}sql;token;static[_]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(W,$){return D`(select count(*) from ${W}${D.raw(" where ").if($)}${$})`}static buildCount(W,$){return D`select count(*) as count from ${W}${D.raw(" where ").if($)}${$};`}setToken(W){return this.token=W,this}then(W,$){return Promise.resolve(this.session.count(this.sql,this.token)).then(W,$)}catch(W){return this.then(void 0,W)}finally(W){return this.then(($)=>{return W?.(),$},($)=>{throw W?.(),$})}}class K5{constructor(W,$,X,Y,J,G,H){this.fullSchema=W,this.schema=$,this.tableNamesMap=X,this.table=Y,this.tableConfig=J,this.dialect=G,this.session=H}static[_]="PgRelationalQueryBuilder";findMany(W){return new O5(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,W?W:{},"many")}findFirst(W){return new O5(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,W?{...W,limit:1}:{limit:1},"first")}}class O5 extends C1{constructor(W,$,X,Y,J,G,H,Q,z){super();this.fullSchema=W,this.schema=$,this.tableNamesMap=X,this.table=Y,this.tableConfig=J,this.dialect=G,this.session=H,this.config=Q,this.mode=z}static[_]="PgRelationalQuery";_prepare(W){return q0.startActiveSpan("drizzle.prepareQuery",()=>{let{query:$,builtQuery:X}=this._toSQL();return this.session.prepareQuery(X,void 0,W,!0,(Y,J)=>{let G=Y.map((H)=>LY(this.schema,this.tableConfig,H,$.selection,J));if(this.mode==="first")return G[0];return G})})}prepare(W){return this._prepare(W)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let W=this._getQuery(),$=this.dialect.sqlToQuery(W.sql);return{query:W,builtQuery:$}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(W){return this.authToken=W,this}execute(){return q0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class L5 extends C1{constructor(W,$,X,Y){super();this.execute=W,this.sql=$,this.query=X,this.mapBatchResult=Y}static[_]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(W,$){return $?this.mapBatchResult(W):W}_prepare(){return this}isResponseInArrayMode(){return!1}}class O6{constructor(W,$,X){if(this.dialect=W,this.session=$,this._=X?{schema:X.schema,fullSchema:X.fullSchema,tableNamesMap:X.tableNamesMap,session:$}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:$},this.query={},this._.schema)for(let[Y,J]of Object.entries(this._.schema))this.query[Y]=new K5(X.fullSchema,this._.schema,this._.tableNamesMap,X.fullSchema[Y],J,W,$)}static[_]="PgDatabase";query;$with=(W,$)=>{let X=this;return{as:(J)=>{if(typeof J==="function")J=J(new D6(X.dialect));return new Proxy(new e4(J.getSQL(),$??("getSelectedFields"in J?J.getSelectedFields()??{}:{}),W,!0),new i0({alias:W,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(W,$){return new V6({source:W,filters:$,session:this.session})}with(...W){let $=this;function X(z){return new I1({fields:z??void 0,session:$.session,dialect:$.dialect,withList:W})}function Y(z){return new I1({fields:z??void 0,session:$.session,dialect:$.dialect,withList:W,distinct:!0})}function J(z,F){return new I1({fields:F??void 0,session:$.session,dialect:$.dialect,withList:W,distinct:{on:z}})}function G(z){return new PY(z,$.session,$.dialect,W)}function H(z){return new fY(z,$.session,$.dialect,W)}function Q(z){return new jY(z,$.session,$.dialect,W)}return{select:X,selectDistinct:Y,selectDistinctOn:J,update:G,insert:H,delete:Q}}select(W){return new I1({fields:W??void 0,session:this.session,dialect:this.dialect})}selectDistinct(W){return new I1({fields:W??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(W,$){return new I1({fields:$??void 0,session:this.session,dialect:this.dialect,distinct:{on:W}})}update(W){return new PY(W,this.session,this.dialect)}insert(W){return new fY(W,this.session,this.dialect)}delete(W){return new jY(W,this.session,this.dialect)}refreshMaterializedView(W){return new V5(W,this.session,this.dialect)}authToken;execute(W){let $=typeof W==="string"?D.raw(W):W.getSQL(),X=this.dialect.sqlToQuery($),Y=this.session.prepareQuery(X,void 0,void 0,!1);return new L5(()=>Y.execute(void 0,this.authToken),$,X,(J)=>Y.mapResult(J,!0))}transaction(W,$){return this.session.transaction(W,$)}}class $T{constructor(W,$){this.unique=W,this.name=$}static[_]="PgIndexBuilderOn";on(...W){return new xY(W.map(($)=>{if(A($,g))return $;$=$;let X=new a4($.name,!!$.keyAsName,$.columnType,$.indexConfig);return $.indexConfig=JSON.parse(JSON.stringify($.defaultConfig)),X}),this.unique,!1,this.name)}onOnly(...W){return new xY(W.map(($)=>{if(A($,g))return $;$=$;let X=new a4($.name,!!$.keyAsName,$.columnType,$.indexConfig);return $.indexConfig=$.defaultConfig,X}),this.unique,!0,this.name)}using(W,...$){return new xY($.map((X)=>{if(A(X,g))return X;X=X;let Y=new a4(X.name,!!X.keyAsName,X.columnType,X.indexConfig);return X.indexConfig=JSON.parse(JSON.stringify(X.defaultConfig)),Y}),this.unique,!0,this.name,W)}}class xY{static[_]="PgIndexBuilder";config;constructor(W,$,X,Y,J="btree"){this.config={name:Y,columns:W,unique:$,only:X,method:J}}concurrently(){return this.config.concurrently=!0,this}with(W){return this.config.with=W,this}where(W){return this.config.where=W,this}build(W){return new XT(this.config,W)}}class XT{static[_]="PgIndex";config;constructor(W,$){this.config={...W,table:$}}}function A5(W){return new $T(!0,W)}class E5{constructor(W){this.query=W}authToken;getQuery(){return this.query}mapResult(W,$){return W}setToken(W){return this.authToken=W,this}static[_]="PgPreparedQuery";joinsNotNullableMap}class N5{constructor(W){this.dialect=W}static[_]="PgSession";execute(W,$){return q0.startActiveSpan("drizzle.operation",()=>{return q0.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(W),void 0,void 0,!1)}).setToken($).execute(void 0,$)})}all(W){return this.prepareQuery(this.dialect.sqlToQuery(W),void 0,void 0,!1).all()}async count(W,$){let X=await this.execute(W,$);return Number(X[0].count)}}class B5 extends O6{constructor(W,$,X,Y=0){super(W,$,X);this.schema=X,this.nestedIndex=Y}static[_]="PgTransaction";rollback(){throw new uJ}getTransactionConfigSQL(W){let $=[];if(W.isolationLevel)$.push(`isolation level ${W.isolationLevel}`);if(W.accessMode)$.push(W.accessMode);if(typeof W.deferrable==="boolean")$.push(W.deferrable?"deferrable":"not deferrable");return D.raw($.join(" "))}setTransaction(W){return this.session.execute(D`set transaction ${this.getTransactionConfigSQL(W)}`)}}class YT extends E5{constructor(W,$,X,Y,J,G,H){super({sql:$,params:X});this.client=W,this.queryString=$,this.params=X,this.logger=Y,this.fields=J,this._isResponseInArrayMode=G,this.customResultMapper=H}static[_]="PostgresJsPreparedQuery";async execute(W={}){return q0.startActiveSpan("drizzle.execute",async($)=>{let X=mJ(this.params,W);$?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(X)}),this.logger.logQuery(this.queryString,X);let{fields:Y,queryString:J,client:G,joinsNotNullableMap:H,customResultMapper:Q}=this;if(!Y&&!Q)return q0.startActiveSpan("drizzle.driver.execute",()=>{return G.unsafe(J,X)});let z=await q0.startActiveSpan("drizzle.driver.execute",()=>{return $?.setAttributes({"drizzle.query.text":J,"drizzle.query.params":JSON.stringify(X)}),G.unsafe(J,X).values()});return q0.startActiveSpan("drizzle.mapResponse",()=>{return Q?Q(z):z.map((F)=>HQ(Y,F,H))})})}all(W={}){return q0.startActiveSpan("drizzle.execute",async($)=>{let X=mJ(this.params,W);return $?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(X)}),this.logger.logQuery(this.queryString,X),q0.startActiveSpan("drizzle.driver.execute",()=>{return $?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(X)}),this.client.unsafe(this.queryString,X)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class K6 extends N5{constructor(W,$,X,Y={}){super($);this.client=W,this.schema=X,this.options=Y,this.logger=Y.logger??new dJ}static[_]="PostgresJsSession";logger;prepareQuery(W,$,X,Y,J){return new YT(this.client,W.sql,W.params,this.logger,$,Y,J)}query(W,$){return this.logger.logQuery(W,$),this.client.unsafe(W,$).values()}queryObjects(W,$){return this.client.unsafe(W,$)}transaction(W,$){return this.client.begin(async(X)=>{let Y=new K6(X,this.dialect,this.schema,this.options),J=new R5(this.dialect,Y,this.schema);if($)await J.setTransaction($);return W(J)})}}class R5 extends B5{constructor(W,$,X,Y=0){super(W,$,X,Y);this.session=$}static[_]="PostgresJsTransaction";transaction(W){return this.session.client.savepoint(($)=>{let X=new K6($,this.dialect,this.schema,this.session.options),Y=new R5(this.dialect,X,this.schema);return W(Y)})}}class JT extends O6{static[_]="PostgresJsDatabase"}function O$(W,$={}){let X=(z)=>z;for(let z of["1184","1082","1083","1114","1182","1185","1115","1231"])W.options.parsers[z]=X,W.options.serializers[z]=X;W.options.serializers["114"]=X,W.options.serializers["3802"]=X;let Y=new L8({casing:$.casing}),J;if($.logger===!0)J=new cJ;else if($.logger!==!1)J=$.logger;let G;if($.schema){let z=IF($.schema,fF);G={fullSchema:$.schema,schema:z.tables,tableNamesMap:z.tableNamesMap}}let H=new K6(W,Y,G,{logger:J}),Q=new JT(Y,H,G);return Q.$client=W,Q}function vY(...W){if(typeof W[0]==="string"){let $=D$(W[0]);return O$($,W[1])}if(FQ(W[0])){let{connection:$,client:X,...Y}=W[0];if(X)return O$(X,Y);if(typeof $==="object"&&$.url!==void 0){let{url:G,...H}=$,Q=D$(G,H);return O$(Q,Y)}let J=D$($);return O$(J,Y)}return O$(W[0],W[1])}((W)=>{function $(X){return O$({options:{parsers:{},serializers:{}}},X)}W.mock=$})(vY||(vY={}));function GT(W,$){if(W instanceof Promise)throw new Error($)}function cO(W,$){let X={},Y=[];for(let J in W){let G=W[J]["~standard"].validate($[J]);if(GT(G,`Validation must be synchronous, but ${J} returned a Promise.`),G.issues){Y.push(...G.issues.map((H)=>({...H,path:[J,...H.path??[]]})));continue}X[J]=G.value}if(Y.length)return{issues:Y};return{value:X}}function Z5(W){let $=W.runtimeEnvStrict??W.runtimeEnv??process.env;if(W.emptyStringAsUndefined??!1){for(let[B,q]of Object.entries($))if(q==="")delete $[B]}if(!!W.skipValidation)return $;let J=typeof W.client==="object"?W.client:{},G=typeof W.server==="object"?W.server:{},H=typeof W.shared==="object"?W.shared:{},Q=W.isServer??(typeof window==="undefined"||("Deno"in window)),z=Q?{...G,...H,...J}:{...J,...H},F=W.createFinalSchema?.(z,Q)["~standard"].validate($)??cO(z,$);GT(F,"Validation must be synchronous");let T=W.onValidationError??((B)=>{throw console.error("\u274C Invalid environment variables:",B),new Error("Invalid environment variables")}),U=W.onInvalidAccess??(()=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(F.issues)return T(F.issues);let M=(B)=>{if(!W.clientPrefix)return!0;return!B.startsWith(W.clientPrefix)&&!(B in H)},V=(B)=>{return Q||!M(B)},K=(B)=>{return B==="__esModule"||B==="$$typeof"},N=(W.extends??[]).reduce((B,q)=>{return Object.assign(B,q)},{}),I=Object.assign(N,F.value);return new Proxy(I,{get(B,q){if(typeof q!=="string")return;if(K(q))return;if(!V(q))return U(q);return Reflect.get(B,q)}})}var v2=(W)=>Array.isArray(W)?W:[W],HT=(W,$)=>{let X=[[],[]];for(let Y of W)if($(Y))X[0].push(Y);else X[1].push(Y);return X},bY=Array,G2=(W,$)=>W.includes($),QT=(W,$=0)=>[...new Array(W)].map((X,Y)=>Y+$),M0=(W,$,X)=>{if(W===void 0)return $===void 0?[]:Array.isArray($)?$:[$];if(X?.prepend)if(Array.isArray($))W.unshift(...$);else W.unshift($);else if(Array.isArray($))W.push(...$);else W.push($);return W},H2=(W,$)=>{if($===void 0||$===null)return W??[];if(W===void 0||W===null)return v2($);return W.concat($)},zT=(...W)=>W.reduce(H2,[]),pW=(W,$,X)=>{if(W===void 0)return Array.isArray($)?$:[$];let Y=X?.isEqual??((J,G)=>J===G);for(let J of v2($))if(!W.some((G)=>Y(G,J)))W.push(J);return W},FT=(W,$)=>W.reduce((X,Y)=>{let J=Y[$];return X[J]=M0(X[J],Y),X},{}),Q2=(W,$,X)=>W.length===$.length&&W.every(X?.isEqual?(Y,J)=>X.isEqual(Y,$[J]):(Y,J)=>Y===$[J]);var g1=(W,$)=>Q1(W)===$,Q1=(W)=>{let $=typeof W;return $==="object"?W===null?"null":"object":$==="function"?"object":$},m1={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},TT={...m1,function:"a function"};class UT extends Error{}var O0=(W)=>A8(W,UT),A8=(W,$=Error)=>{throw new $(W)};class L6 extends Error{name="ParseError"}var L=(W)=>A8(W,L6),BW=(W)=>` ${W}`;var $0=(W,$)=>{let X={},Y=Array.isArray(W),J=!1;for(let[G,H]of Object.entries(W).entries()){let Q=Y?$(G,H[1]):$(...H,G);J||=typeof Q[0]==="number";let z=Array.isArray(Q[0])||Q.length===0?Q:[Q];for(let[F,T]of z)if(typeof F==="object")X[F.group]=M0(X[F.group],T);else X[F]=T}return J?Object.values(X):X};var S5=Object.entries;var z1=(W,$)=>(W in $),K$=(W,$)=>($ in W);class q5{constructor(W){Object.assign(this,W)}}var wT=class{};class A6 extends wT{}var dO=(W,$)=>{let X={},Y={},J;for(J in W)if(J in $)X[J]=W[J];else Y[J]=W[J];return[X,Y]};var MT=(W,$)=>dO(W,$)[1],uW=(W)=>Object.keys(W).length===0,E8=(W)=>[...Object.entries(W),...Object.getOwnPropertySymbols(W).map(($)=>[$,W[$]])],_T=(W,$)=>Object.defineProperties(W,Object.getOwnPropertyDescriptors($)),DT=(W)=>{let $=Object.keys(W).sort(),X={};for(let Y=0;Y<$.length;Y++)X[$[Y]]=W[$[Y]];return X};var e1=BW("represents an uninitialized value"),VT=(W)=>Object.values(W).filter(($)=>{if(typeof $==="number")return!0;return typeof W[$]!=="number"});var C5={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},k5=globalThis.File??Blob,I5={ArrayBuffer,Blob,File:k5,FormData,Headers,Request,Response,URL},lO={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},N8={...C5,...I5,...lO,String,Number,Boolean},E6=(W)=>{let $=Object.getPrototypeOf(W);while($?.constructor&&(!z1($.constructor.name,N8)||!(W instanceof N8[$.constructor.name])))$=Object.getPrototypeOf($);let X=$?.constructor?.name;if(X===void 0||X==="Object")return;return X},N6=(W)=>typeof W==="object"&&W!==null?E6(W)??"object":Q1(W);var C0=Array.isArray,oO={Array:"an array",Function:"a function",Date:"a Date",RegExp:"a RegExp",Error:"an Error",Map:"a Map",Set:"a Set",String:"a String object",Number:"a Number object",Boolean:"a Boolean object",Promise:"a Promise",WeakMap:"a WeakMap",WeakSet:"a WeakSet"},iO={ArrayBuffer:"an ArrayBuffer instance",Blob:"a Blob instance",File:"a File instance",FormData:"a FormData instance",Headers:"a Headers instance",Request:"a Request instance",Response:"a Response instance",URL:"a URL instance"},nO={Int8Array:"an Int8Array",Uint8Array:"a Uint8Array",Uint8ClampedArray:"a Uint8ClampedArray",Int16Array:"an Int16Array",Uint16Array:"a Uint16Array",Int32Array:"an Int32Array",Uint32Array:"a Uint32Array",Float32Array:"a Float32Array",Float64Array:"a Float64Array",BigInt64Array:"a BigInt64Array",BigUint64Array:"a BigUint64Array"},OT={...oO,...iO,...nO},B6=(W)=>{let $=Object(W).name??null;return $&&z1($,N8)&&N8[$]===W?$:null};var j5=(W,$)=>{let X=W.prototype;while(X!==null){if(X===$.prototype)return!0;X=Object.getPrototypeOf(X)}return!1};var KT=(W)=>LT(W,new Map),LT=(W,$)=>{if(typeof W!=="object"||W===null)return W;if($?.has(W))return $.get(W);let X=B6(W.constructor);if(X==="Date")return new Date(W.getTime());if(X&&X!=="Array")return W;let Y=Array.isArray(W)?W.slice():Object.create(Object.getPrototypeOf(W)),J=Object.getOwnPropertyDescriptors(W);if($){$.set(W,Y);for(let G in J){let H=J[G];if("get"in H||"set"in H)continue;H.value=LT(H.value,$)}}return Object.defineProperties(Y,J),Y};var rO=(W)=>{let $=e1;return()=>$===e1?$=W():$},b2=(W)=>typeof W==="function"&&W.length===0;var AT=class extends Function{constructor(...W){let $=W.slice(0,-1),X=W.at(-1);try{super(...$,X)}catch(Y){return O0(`Encountered an unexpected error while compiling your definition:
84
+ Message: ${Y}
85
+ Source: (${W.slice(0,-1)}) => {
86
+ ${W.at(-1)}
87
+ }`)}}};class RW{constructor(W,...[$]){return Object.assign(Object.setPrototypeOf(W.bind($?.bind??this),this.constructor.prototype),$?.attach)}}var ET=rO(()=>{try{return new Function("return false")()}catch{return!0}});var Bp=BW("brand");var NT=BW("arkInferred");var Sp=BW("args");class N1{constructor(){}}var tO=()=>{try{return((new Error().stack?.split(`
88
+ `)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},aO=globalThis.process?.env??{},BT={fileName:tO,env:aO};var RT=(W)=>W[0].toUpperCase()+W.slice(1);var f5=(W)=>new RegExp(sO(W),typeof W==="string"?"":W.flags);var sO=(W)=>{return`^(?:${typeof W==="string"?W:W.source})$`};var z2={negativeLookahead:(W)=>`(?!${W})`,nonCapturingGroup:(W)=>`(?:${W})`},R6="\\",y2={" ":1,"\n":1,"\t":1};var eO=/^-0\.?0*$/.source,ST=/[1-9]\d*/.source,WK=/\.\d+/.source,$K=/\.\d*[1-9]/.source,qT=(W)=>f5(z2.negativeLookahead(eO)+z2.nonCapturingGroup("-?"+z2.nonCapturingGroup(z2.nonCapturingGroup("0|"+ST)+z2.nonCapturingGroup(W.decimalPattern)+"?")+(W.allowDecimalOnly?"|"+W.decimalPattern:"")+"?")),ZT=qT({decimalPattern:$K,allowDecimalOnly:!1}),XK=ZT.test.bind(ZT),yY=qT({decimalPattern:WK,allowDecimalOnly:!0}),Pp=yY.test.bind(yY),YK=/^-?\d*\.?\d*$/,JK=(W)=>W.length!==0&&YK.test(W),Z6=f5(z2.negativeLookahead("^-0$")+"-?"+z2.nonCapturingGroup(z2.nonCapturingGroup("0|"+ST))),GK=Z6.test.bind(Z6),P5=/^-?\d+$/,HK=P5.test.bind(P5),CT={number:"a number",bigint:"a bigint",integer:"an integer"},kT=(W,$)=>`'${W}' was parsed as ${CT[$]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,QK=(W,$)=>$==="number"?XK(W):GK(W),zK=(W,$)=>$==="number"?Number(W):Number.parseInt(W),FK=(W,$)=>$==="number"?JK(W):HK(W),IT=(W,$)=>x5(W,"number",$),jT=(W,$)=>x5(W,"number",{...$,strict:!0}),fT=(W,$)=>x5(W,"integer",$),x5=(W,$,X)=>{let Y=zK(W,$);if(!Number.isNaN(Y)){if(FK(W,$)){if(X?.strict)return QK(W,$)?Y:L(kT(W,$));return Y}}return X?.errorOnFail?L(X?.errorOnFail===!0?`Failed to parse ${CT[$]} from '${W}'`:X?.errorOnFail):void 0},PT=(W)=>{if(W[W.length-1]!=="n")return;let $=W.slice(0,-1),X;try{X=BigInt($)}catch{return}if(Z6.test($))return X;if(P5.test($))return L(kT(W,"bigint"))};var TK="0.46.0",UK={version:TK,filename:BT.fileName(),FileConstructor:k5},B8=UK,xT=new Map,v5=Object.create(null),S6=(W)=>{let $=xT.get(W);if($)return $;let X=wK(W);if(v5[X])X=`${X}${v5[X]++}`;else v5[X]=1;return B8[X]=W,xT.set(W,X),X},h2=(W)=>/^[$A-Z_a-z][\w$]*$/.test(W),wK=(W)=>{switch(typeof W){case"object":{if(W===null)break;let $=E6(W)??"object";return $[0].toLowerCase()+$.slice(1)}case"function":return h2(W.name)?W.name:"fn";case"symbol":return W.description&&h2(W.description)?W.description:"symbol"}return O0(`Unexpected attempt to register serializable value of type ${Q1(W)}`)};var q6=(W)=>typeof W==="string"?JSON.stringify(W):typeof W==="bigint"?`${W}n`:`${W}`;var vT=(W,$={})=>C6(W,{onUndefined:"$ark.undefined",onBigInt:(X)=>`$ark.bigint-${X}`,...$},[]);var X0=(W,$)=>{switch(Q1(W)){case"object":let X=W,Y=X.constructor.name;return Y==="Object"||Y==="Array"?$?.quoteKeys===!1?hY(X,$?.indent??0,""):JSON.stringify(C6(X,L$,[]),null,$?.indent):hY(X,$?.indent??0,"");case"symbol":return L$.onSymbol(W);default:return q6(W)}},hY=(W,$,X)=>{if(typeof W==="function")return L$.onFunction(W);if(typeof W!=="object"||W===null)return q6(W);let Y=X+" ".repeat($);if(Array.isArray(W)){if(W.length===0)return"[]";let G=W.map((H)=>hY(H,$,Y)).join(`,
89
+ `+Y);return $?`[
90
+ ${Y}${G}
91
+ ${X}]`:`[${G}]`}let J=W.constructor.name;if(J==="Object"){let G=E8(W).map(([H,Q])=>{let z=typeof H==="symbol"?L$.onSymbol(H):h2(H)?H:JSON.stringify(H),F=hY(Q,$,Y);return`${Y}${z}: ${F}`});if(G.length===0)return"{}";return $?`{
92
+ ${G.join(`,
104
93
  `)}
105
- ${J}}`:`{${F.join(", ")}}`}if(T instanceof Date)return i0(T);if("expression"in T&&typeof T.expression==="string")return T.expression;return X},nW={onCycle:()=>"(cycle)",onSymbol:(T)=>`Symbol(${T8(T)})`,onFunction:(T)=>`Function(${T8(T)})`},J8=(T,$,J)=>{switch(S$(T)){case"object":{let W=T;if("toJSON"in W&&typeof W.toJSON==="function")return W.toJSON();if(typeof W==="function")return nW.onFunction(W);if(J.includes(W))return"(cycle)";let X=[...J,W];if(Array.isArray(W))return W.map((Y)=>J8(Y,$,X));if(W instanceof Date)return W.toDateString();let F={};for(let Y in W)F[Y]=J8(W[Y],$,X);for(let Y of Object.getOwnPropertySymbols(W))F[$.onSymbol?.(Y)??Y.toString()]=J8(W[Y],$,X);return F}case"symbol":return nW.onSymbol(T);case"bigint":return $.onBigInt?.(T)??`${T}n`;case"undefined":return $.onUndefined??"undefined";case"string":return T.replaceAll("\\","\\\\");default:return T}},i0=(T)=>{let $=T.getFullYear(),J=T.getMonth(),W=T.getDate(),X=T.getHours(),F=T.getMinutes(),Y=T.getSeconds(),G=T.getMilliseconds();if(J===0&&W===1&&X===0&&F===0&&Y===0&&G===0)return`${$}`;let H=`${dS[J]} ${W}, ${$}`;if(X===0&&F===0&&Y===0&&G===0)return H;let M=T.toLocaleTimeString(),z=M.endsWith(" AM")||M.endsWith(" PM")?M.slice(-3):"";if(z)M=M.slice(0,-z.length);if(G)M+=`.${nS(G,3)}`;else if(lS.test(M))M=M.slice(0,-3);return`${M+z}, ${H}`},dS=["January","February","March","April","May","June","July","August","September","October","November","December"],lS=/:\d\d:00$/,nS=(T,$)=>String(T).padStart($,"0");var zw=(T,$,...[J])=>{let W=J?.stringifySymbol??GT,X=T;switch(typeof $){case"string":X=J0($)?T===""?$:`${T}.${$}`:`${T}[${JSON.stringify($)}]`;break;case"number":X=`${T}[${$}]`;break;case"symbol":X=`${T}[${W($)}]`;break;default:if(J?.stringifyNonKey)X=`${T}[${J.stringifyNonKey($)}]`;else R(`${GT($)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return X},N1=(T,...$)=>T.reduce((J,W)=>zw(J,W,...$),"");class W8 extends S6{cache={};constructor(...T){super();this.push(...T)}toJSON(){if(this.cache.json)return this.cache.json;this.cache.json=[];for(let T=0;T<this.length;T++)this.cache.json.push(typeof this[T]==="symbol"?GT(this[T]):this[T]);return this.cache.json}stringify(){if(this.cache.stringify)return this.cache.stringify;return this.cache.stringify=N1(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let T="",$=[T];for(let J of this)T=zw(T,J),$.push(T);return this.cache.stringifyAncestors=$}}class v9{chars;i;def;constructor(T){this.def=T,this.chars=[...T],this.i=0}shift(){return this.chars[this.i++]??""}get lookahead(){return this.chars[this.i]??""}get nextLookahead(){return this.chars[this.i+1]??""}get length(){return this.chars.length}shiftUntil(T){let $="";while(this.lookahead){if(T(this,$))if($[$.length-1]===s2)$=$.slice(0,-1);else break;$+=this.shift()}return $}shiftUntilLookahead(T){return typeof T==="string"?this.shiftUntil(($)=>$.lookahead===T):this.shiftUntil(($)=>($.lookahead in T))}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in $0))}jumpToIndex(T){this.i=T<0?this.length+T:T}jumpForward(T){this.i+=T}get location(){return this.i}get unscanned(){return this.chars.slice(this.i,this.length).join("")}get scanned(){return this.chars.slice(0,this.i).join("")}sliceChars(T,$){return this.chars.slice(T,$).join("")}lookaheadIs(T){return this.lookahead===T}lookaheadIsIn(T){return this.lookahead in T}}var Ma=vJ("implementedTraits");var h9="$ark",iS=2;while(h9 in globalThis)h9=`$ark${iS++}`;var Aw=h9;globalThis[Aw]=n0;var k=n0,tS=(T)=>`${Aw}.${T}`,sT=(T)=>tS(T8(T));class R6 extends i2{argNames;body="";constructor(...T){super();this.argNames=T;for(let $ of T){if($ in this)throw new Error(`Arg name '${$}' would overwrite an existing property on FunctionBody`);this[$]=$}}indentation=0;indent(){return this.indentation+=4,this}dedent(){return this.indentation-=4,this}prop(T,$=!1){return m9(T,$)}index(T,$=!1){return ww(`${T}`,$)}line(T){return this.body+=`${" ".repeat(this.indentation)}${T}
106
- `,this}const(T,$){return this.line(`const ${T} = ${$}`),this}let(T,$){return this.line(`let ${T} = ${$}`)}set(T,$){return this.line(`${T} = ${$}`)}if(T,$){return this.block(`if (${T})`,$)}elseIf(T,$){return this.block(`else if (${T})`,$)}else(T){return this.block("else",T)}for(T,$,J=0){return this.block(`for (let i = ${J}; ${T}; i++)`,$)}forIn(T,$){return this.block(`for (const k in ${T})`,$)}block(T,$,J=""){return this.line(`${T} {`),this.indent(),$(this),this.dedent(),this.line(`}${J}`)}return(T=""){return this.line(`return ${T}`)}write(T="anonymous",$=0){return`${T}(${this.argNames.join(", ")}) { ${$?this.body.split(`
107
- `).map((J)=>" ".repeat($)+`${J}`).join(`
108
- `):this.body} }`}compile(){return new iA(...this.argNames,this.body)}}var C1=(T)=>e$(T,"object")||typeof T==="symbol"?sT(T):$8(T),m9=(T,$=!1)=>{if(typeof T==="string"&&J0(T))return`${$?"?":""}.${T}`;return ww(rS(T),$)},rS=(T)=>typeof T==="symbol"?sT(T):JSON.stringify(T),ww=(T,$=!1)=>`${$?"?.":""}[${T}]`;class X8 extends R6{traversalKind;optimistic;constructor(T){super("data","ctx");this.traversalKind=T.kind,this.optimistic=T.optimistic===!0}invoke(T,$){let J=$?.arg??this.data,W=typeof T==="string"?!0:this.requiresContextFor(T),X=typeof T==="string"?T:T.id;if(W)return`${this.referenceToId(X,$)}(${J}, ${this.ctx})`;return`${this.referenceToId(X,$)}(${J})`}referenceToId(T,$){let J=$?.kind??this.traversalKind,W=`this.${T}${J}`;return $?.bind?`${W}.bind(${$?.bind})`:W}requiresContextFor(T){return this.traversalKind==="Apply"||T.allowsRequiresContext}initializeErrorCount(){return this.const("errorCount","ctx.currentErrorCount")}returnIfFail(){return this.if("ctx.currentErrorCount > errorCount",()=>this.return())}returnIfFailFast(){return this.if("ctx.failFast && ctx.currentErrorCount > errorCount",()=>this.return())}traverseKey(T,$,J){let W=this.requiresContextFor(J);if(W)this.line(`${this.ctx}.path.push(${T})`);if(this.check(J,{arg:$}),W)this.line(`${this.ctx}.path.pop()`);return this}check(T,$){return this.traversalKind==="Allows"?this.if(`!${this.invoke(T,$)}`,()=>this.return(!1)):this.line(this.invoke(T,$))}}var L6=(T)=>YT(T,($,J)=>[$,hT(J)?[...J]:J]),o$=vJ("arkKind"),l=(T,$)=>T?.[o$]===$,uT=(T)=>l(T,"root")||l(T,"constraint");var Qw=["unit","proto","domain"],iW=["required","optional","index","sequence"],g9=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],B6=[...g9,...iW,"structure","predicate"],tW=["alias","union","morph","unit","intersection","proto","domain"],aS=[...tW,...B6],f6=YT(B6,(T,$)=>[$,1]),Ow=YT([...iW,"undeclared"],(T,$)=>[$,1]),Uw=YT(aS,(T,$)=>[$,T]),rW=(T)=>typeof T==="string"&&(T in Uw);var aW=(T)=>Uw[T],N6=(T)=>tW.slice(aW(T)+1),la=[...N6("union"),"alias"],na=[...N6("morph"),"alias"],LJ=(T)=>{if(typeof T==="string"||typeof T==="boolean"||T===null)return T;if(typeof T==="number"){if(Number.isNaN(T))return"NaN";if(T===Number.POSITIVE_INFINITY)return"Infinity";if(T===Number.NEGATIVE_INFINITY)return"-Infinity";return T}return C1(T)},W0=(T)=>{let $="{ ";for(let[J,W]of Object.entries(T))$+=`${J}: ${C1(W)}, `;return $+" }"},HT=(T)=>{let $=T;if($.hasAssociatedError)$.defaults.expected??=(J)=>("description"in J)?J.description:$.defaults.description(J),$.defaults.actual??=(J)=>GT(J),$.defaults.problem??=(J)=>`must be ${J.expected}${J.actual?` (was ${J.actual})`:""}`,$.defaults.message??=(J)=>{if(J.path.length===0)return J.problem;let W=`${J.propString} ${J.problem}`;if(W[0]==="[")return`value at ${W}`;return W};return $};class _w extends Error{name="ToJsonSchemaError";code;context;constructor(T,$){super(GT($,{quoteKeys:!1,indent:4}));this.code=T,this.context=$}hasCode(T){return this.code===T}}var sS={dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:(T)=>nT.throw("arrayObject",T),arrayPostfix:(T)=>nT.throw("arrayPostfix",T),defaultValue:(T)=>nT.throw("defaultValue",T),domain:(T)=>nT.throw("domain",T),morph:(T)=>nT.throw("morph",T),patternIntersection:(T)=>nT.throw("patternIntersection",T),predicate:(T)=>nT.throw("predicate",T),proto:(T)=>nT.throw("proto",T),symbolKey:(T)=>nT.throw("symbolKey",T),unit:(T)=>nT.throw("unit",T),date:(T)=>nT.throw("date",T)}},nT={Error:_w,throw:(...T)=>{throw new nT.Error(...T)},throwInternalOperandError:(T,$)=>RT(`Unexpected JSON Schema input for ${T}: ${GT($)}`),defaultConfig:sS};k.config??={};var F8=(T,$)=>{if(!$)return T;let J={...T},W;for(W in $){let X={...T.keywords};if(W==="keywords"){for(let F in $[W]){let Y=$.keywords[F];if(Y===void 0)continue;X[F]=typeof Y==="string"?{description:Y}:Y}J.keywords=X}else if(W==="toJsonSchema")J[W]=p9(T.toJsonSchema,$.toJsonSchema);else if(rW(W))J[W]={...T[W],...$[W]};else J[W]=$[W]}return J},p9=(T,$)=>{if(!T)return $??{};if(!$)return T;let J={...T},W;for(W in $)if(W==="fallback")J.fallback=eS(T.fallback,$.fallback);else J[W]=$[W];return J},eS=(T,$)=>{T=Dw(T),$=Dw($);let J={},W;for(W in nT.defaultConfig.fallback)J[W]=$[W]??$.default??T[W]??T.default??nT.defaultConfig.fallback[W];return J},Dw=(T)=>typeof T==="function"?{default:T}:T??{};class X0 extends i2{[o$]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:T,relativePath:$,...J},W){super();this.input=J,this.ctx=W,uA(this,J);let X=W.data;if(J.code==="union")J.errors=J.errors.flatMap((Y)=>{let G=Y.hasCode("union")?Y.errors:[Y];if(!T&&!$)return G;return G.map((H)=>H.transform((M)=>({...M,path:bA(T,M.path,$)})))});this.nodeConfig=W.config[this.code];let F=[...J.path??W.path];if($)F.push(...$);if(T)F.unshift(...T);this.path=new W8(...F),this.data="data"in J?J.data:X}transform(T){return new X0(T({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(T){return this.code===T}get propString(){return N1(this.path)}get expected(){if(this.input.expected)return this.input.expected;let T=this.meta?.expected??this.nodeConfig.expected;return typeof T==="function"?T(this.input):T}get actual(){if(this.input.actual)return this.input.actual;let T=this.meta?.actual??this.nodeConfig.actual;return typeof T==="function"?T(this.data):T}get problem(){if(this.input.problem)return this.input.problem;let T=this.meta?.problem??this.nodeConfig.problem;return typeof T==="function"?T(this):T}get message(){if(this.input.message)return this.input.message;let T=this.meta?.message??this.nodeConfig.message;return typeof T==="function"?T(this):T}get flat(){return this.hasCode("intersection")?[...this.errors]:[this]}toJSON(){return{data:this.data,path:this.path,...this.input,expected:this.expected,actual:this.actual,problem:this.problem,message:this.message}}toString(){return this.message}throw(){throw this}}class $J extends S6{[o$]="errors";ctx;constructor(T){super();this.ctx=T}byPath=Object.create(null);get flatByPath(){return YT(this.byPath,(T,$)=>[T,$.flat])}get flatProblemsByPath(){return YT(this.byPath,(T,$)=>[T,$.flat.map((J)=>J.problem)])}byAncestorPath=Object.create(null);count=0;mutable=this;throw(){throw this.toTraversalError()}toTraversalError(){return new u9(this)}add(T){if(this.includes(T))return;this._add(T)}transform(T){let $=new $J(this.ctx);for(let J of this)$.add(T(J));return $}merge(T){for(let $ of T){if(this.includes($))continue;this._add(new X0({...$,path:[...this.ctx.path,...$.path]},this.ctx))}}affectsPath(T){if(this.length===0)return!1;return T.stringifyAncestors().some(($)=>($ in this.byPath))||T.stringify()in this.byAncestorPath}get summary(){return this.toString()}get issues(){return this}toJSON(){return[...this.map((T)=>T.toJSON())]}toString(){return this.join(`
109
- `)}_add(T){let $=this.byPath[T.propString];if($){if($.hasCode("union")&&$.errors.length===0)return;let J=T.hasCode("union")&&T.errors.length===0?T:new X0({code:"intersection",errors:$.hasCode("intersection")?[...$.errors,T]:[$,T]},this.ctx),W=this.indexOf($);this.mutable[W===-1?this.length:W]=J,this.byPath[T.propString]=J,this.addAncestorPaths(T)}else this.byPath[T.propString]=T,this.addAncestorPaths(T),this.mutable.push(T);this.count++}addAncestorPaths(T){for(let $ of T.path.stringifyAncestors())this.byAncestorPath[$]=ST(this.byAncestorPath[$],T)}}class u9 extends Error{name="TraversalError";constructor(T){if(T.length===1)super(T.summary);else super(`
110
- `+T.map(($)=>` \u2022 ${TV($)}`).join(`
111
- `));Object.defineProperty(this,"arkErrors",{value:T,enumerable:!1})}}var TV=(T)=>T.toString().split(`
94
+ ${X}}`:`{${G.join(", ")}}`}if(W instanceof Date)return R8(W);if("expression"in W&&typeof W.expression==="string")return W.expression;return J},L$={onCycle:()=>"(cycle)",onSymbol:(W)=>`Symbol(${S6(W)})`,onFunction:(W)=>`Function(${S6(W)})`},C6=(W,$,X)=>{switch(Q1(W)){case"object":{let Y=W;if("toJSON"in Y&&typeof Y.toJSON==="function")return Y.toJSON();if(typeof Y==="function")return L$.onFunction(Y);if(X.includes(Y))return"(cycle)";let J=[...X,Y];if(Array.isArray(Y))return Y.map((H)=>C6(H,$,J));if(Y instanceof Date)return Y.toDateString();let G={};for(let H in Y)G[H]=C6(Y[H],$,J);for(let H of Object.getOwnPropertySymbols(Y))G[$.onSymbol?.(H)??H.toString()]=C6(Y[H],$,J);return G}case"symbol":return L$.onSymbol(W);case"bigint":return $.onBigInt?.(W)??`${W}n`;case"undefined":return $.onUndefined??"undefined";case"string":return W.replaceAll("\\","\\\\");default:return W}},R8=(W)=>{let $=W.getFullYear(),X=W.getMonth(),Y=W.getDate(),J=W.getHours(),G=W.getMinutes(),H=W.getSeconds(),Q=W.getMilliseconds();if(X===0&&Y===1&&J===0&&G===0&&H===0&&Q===0)return`${$}`;let z=`${MK[X]} ${Y}, ${$}`;if(J===0&&G===0&&H===0&&Q===0)return z;let F=W.toLocaleTimeString(),T=F.endsWith(" AM")||F.endsWith(" PM")?F.slice(-3):"";if(T)F=F.slice(0,-T.length);if(Q)F+=`.${DK(Q,3)}`;else if(_K.test(F))F=F.slice(0,-3);return`${F+T}, ${z}`},MK=["January","February","March","April","May","June","July","August","September","October","November","December"],_K=/:\d\d:00$/,DK=(W,$)=>String(W).padStart($,"0");var bT=(W,$,...[X])=>{let Y=X?.stringifySymbol??X0,J=W;switch(typeof $){case"string":J=h2($)?W===""?$:`${W}.${$}`:`${W}[${JSON.stringify($)}]`;break;case"number":J=`${W}[${$}]`;break;case"symbol":J=`${W}[${Y($)}]`;break;default:if(X?.stringifyNonKey)J=`${W}[${X.stringifyNonKey($)}]`;else L(`${X0($)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return J},F2=(W,...$)=>W.reduce((X,Y)=>bT(X,Y,...$),"");class k6 extends bY{cache={};constructor(...W){super();this.push(...W)}toJSON(){if(this.cache.json)return this.cache.json;this.cache.json=[];for(let W=0;W<this.length;W++)this.cache.json.push(typeof this[W]==="symbol"?X0(this[W]):this[W]);return this.cache.json}stringify(){if(this.cache.stringify)return this.cache.stringify;return this.cache.stringify=F2(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let W="",$=[W];for(let X of this)W=bT(W,X),$.push(W);return this.cache.stringifyAncestors=$}}class b5{chars;i;def;constructor(W){this.def=W,this.chars=[...W],this.i=0}shift(){return this.chars[this.i++]??""}get lookahead(){return this.chars[this.i]??""}get nextLookahead(){return this.chars[this.i+1]??""}get length(){return this.chars.length}shiftUntil(W){let $="";while(this.lookahead){if(W(this,$))if($[$.length-1]===R6)$=$.slice(0,-1);else break;$+=this.shift()}return $}shiftUntilLookahead(W){return typeof W==="string"?this.shiftUntil(($)=>$.lookahead===W):this.shiftUntil(($)=>($.lookahead in W))}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in y2))}jumpToIndex(W){this.i=W<0?this.length+W:W}jumpForward(W){this.i+=W}get location(){return this.i}get unscanned(){return this.chars.slice(this.i,this.length).join("")}get scanned(){return this.chars.slice(0,this.i).join("")}sliceChars(W,$){return this.chars.slice(W,$).join("")}lookaheadIs(W){return this.lookahead===W}lookaheadIsIn(W){return this.lookahead in W}}var Ju=BW("implementedTraits");var y5="$ark",VK=2;while(y5 in globalThis)y5=`$ark${VK++}`;var yT=y5;globalThis[yT]=B8;var R=B8,OK=(W)=>`${yT}.${W}`,c0=(W)=>OK(S6(W));class gY extends A6{argNames;body="";constructor(...W){super();this.argNames=W;for(let $ of W){if($ in this)throw new Error(`Arg name '${$}' would overwrite an existing property on FunctionBody`);this[$]=$}}indentation=0;indent(){return this.indentation+=4,this}dedent(){return this.indentation-=4,this}prop(W,$=!1){return h5(W,$)}index(W,$=!1){return hT(`${W}`,$)}line(W){return this.body+=`${" ".repeat(this.indentation)}${W}
95
+ `,this}const(W,$){return this.line(`const ${W} = ${$}`),this}let(W,$){return this.line(`let ${W} = ${$}`)}set(W,$){return this.line(`${W} = ${$}`)}if(W,$){return this.block(`if (${W})`,$)}elseIf(W,$){return this.block(`else if (${W})`,$)}else(W){return this.block("else",W)}for(W,$,X=0){return this.block(`for (let i = ${X}; ${W}; i++)`,$)}forIn(W,$){return this.block(`for (const k in ${W})`,$)}block(W,$,X=""){return this.line(`${W} {`),this.indent(),$(this),this.dedent(),this.line(`}${X}`)}return(W=""){return this.line(`return ${W}`)}write(W="anonymous",$=0){return`${W}(${this.argNames.join(", ")}) { ${$?this.body.split(`
96
+ `).map((X)=>" ".repeat($)+`${X}`).join(`
97
+ `):this.body} }`}compile(){return new AT(...this.argNames,this.body)}}var T2=(W)=>g1(W,"object")||typeof W==="symbol"?c0(W):q6(W),h5=(W,$=!1)=>{if(typeof W==="string"&&h2(W))return`${$?"?":""}.${W}`;return hT(KK(W),$)},KK=(W)=>typeof W==="symbol"?c0(W):JSON.stringify(W),hT=(W,$=!1)=>`${$?"?.":""}[${W}]`;class I6 extends gY{traversalKind;optimistic;constructor(W){super("data","ctx");this.traversalKind=W.kind,this.optimistic=W.optimistic===!0}invoke(W,$){let X=$?.arg??this.data,Y=typeof W==="string"?!0:this.requiresContextFor(W),J=typeof W==="string"?W:W.id;if(Y)return`${this.referenceToId(J,$)}(${X}, ${this.ctx})`;return`${this.referenceToId(J,$)}(${X})`}referenceToId(W,$){let X=$?.kind??this.traversalKind,Y=`this.${W}${X}`;return $?.bind?`${Y}.bind(${$?.bind})`:Y}requiresContextFor(W){return this.traversalKind==="Apply"||W.allowsRequiresContext}initializeErrorCount(){return this.const("errorCount","ctx.currentErrorCount")}returnIfFail(){return this.if("ctx.currentErrorCount > errorCount",()=>this.return())}returnIfFailFast(){return this.if("ctx.failFast && ctx.currentErrorCount > errorCount",()=>this.return())}traverseKey(W,$,X){let Y=this.requiresContextFor(X);if(Y)this.line(`${this.ctx}.path.push(${W})`);if(this.check(X,{arg:$}),Y)this.line(`${this.ctx}.path.pop()`);return this}check(W,$){return this.traversalKind==="Allows"?this.if(`!${this.invoke(W,$)}`,()=>this.return(!1)):this.line(this.invoke(W,$))}}var mY=(W)=>$0(W,($,X)=>[$,C0(X)?[...X]:X]),j1=BW("arkKind"),d=(W,$)=>W?.[j1]===$,P0=(W)=>d(W,"root")||d(W,"constraint");var gT=["unit","proto","domain"],A$=["required","optional","index","sequence"],g5=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],pY=[...g5,...A$,"structure","predicate"],E$=["alias","union","morph","unit","intersection","proto","domain"],LK=[...E$,...pY],uY=$0(pY,(W,$)=>[$,1]),mT=$0([...A$,"undeclared"],(W,$)=>[$,1]),pT=$0(LK,(W,$)=>[$,W]),N$=(W)=>typeof W==="string"&&(W in pT);var B$=(W)=>pT[W],cY=(W)=>E$.slice(B$(W)+1),pu=[...cY("union"),"alias"],uu=[...cY("morph"),"alias"],zW=(W)=>{if(typeof W==="string"||typeof W==="boolean"||W===null)return W;if(typeof W==="number"){if(Number.isNaN(W))return"NaN";if(W===Number.POSITIVE_INFINITY)return"Infinity";if(W===Number.NEGATIVE_INFINITY)return"-Infinity";return W}return T2(W)},g2=(W)=>{let $="{ ";for(let[X,Y]of Object.entries(W))$+=`${X}: ${T2(Y)}, `;return $+" }"},Y0=(W)=>{let $=W;if($.hasAssociatedError)$.defaults.expected??=(X)=>("description"in X)?X.description:$.defaults.description(X),$.defaults.actual??=(X)=>X0(X),$.defaults.problem??=(X)=>`must be ${X.expected}${X.actual?` (was ${X.actual})`:""}`,$.defaults.message??=(X)=>{if(X.path.length===0)return X.problem;let Y=`${X.propString} ${X.problem}`;if(Y[0]==="[")return`value at ${Y}`;return Y};return $};class uT extends Error{name="ToJsonSchemaError";code;context;constructor(W,$){super(X0($,{quoteKeys:!1,indent:4}));this.code=W,this.context=$}hasCode(W){return this.code===W}}var AK={dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:(W)=>y0.throw("arrayObject",W),arrayPostfix:(W)=>y0.throw("arrayPostfix",W),defaultValue:(W)=>y0.throw("defaultValue",W),domain:(W)=>y0.throw("domain",W),morph:(W)=>y0.throw("morph",W),patternIntersection:(W)=>y0.throw("patternIntersection",W),predicate:(W)=>y0.throw("predicate",W),proto:(W)=>y0.throw("proto",W),symbolKey:(W)=>y0.throw("symbolKey",W),unit:(W)=>y0.throw("unit",W),date:(W)=>y0.throw("date",W)}},y0={Error:uT,throw:(...W)=>{throw new y0.Error(...W)},throwInternalOperandError:(W,$)=>O0(`Unexpected JSON Schema input for ${W}: ${X0($)}`),defaultConfig:AK};R.config??={};var j6=(W,$)=>{if(!$)return W;let X={...W},Y;for(Y in $){let J={...W.keywords};if(Y==="keywords"){for(let G in $[Y]){let H=$.keywords[G];if(H===void 0)continue;J[G]=typeof H==="string"?{description:H}:H}X.keywords=J}else if(Y==="toJsonSchema")X[Y]=m5(W.toJsonSchema,$.toJsonSchema);else if(N$(Y))X[Y]={...W[Y],...$[Y]};else X[Y]=$[Y]}return X},m5=(W,$)=>{if(!W)return $??{};if(!$)return W;let X={...W},Y;for(Y in $)if(Y==="fallback")X.fallback=EK(W.fallback,$.fallback);else X[Y]=$[Y];return X},EK=(W,$)=>{W=cT(W),$=cT($);let X={},Y;for(Y in y0.defaultConfig.fallback)X[Y]=$[Y]??$.default??W[Y]??W.default??y0.defaultConfig.fallback[Y];return X},cT=(W)=>typeof W==="function"?{default:W}:W??{};class m2 extends A6{[j1]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:W,relativePath:$,...X},Y){super();this.input=X,this.ctx=Y,_T(this,X);let J=Y.data;if(X.code==="union")X.errors=X.errors.flatMap((H)=>{let Q=H.hasCode("union")?H.errors:[H];if(!W&&!$)return Q;return Q.map((z)=>z.transform((F)=>({...F,path:zT(W,F.path,$)})))});this.nodeConfig=Y.config[this.code];let G=[...X.path??Y.path];if($)G.push(...$);if(W)G.unshift(...W);this.path=new k6(...G),this.data="data"in X?X.data:J}transform(W){return new m2(W({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(W){return this.code===W}get propString(){return F2(this.path)}get expected(){if(this.input.expected)return this.input.expected;let W=this.meta?.expected??this.nodeConfig.expected;return typeof W==="function"?W(this.input):W}get actual(){if(this.input.actual)return this.input.actual;let W=this.meta?.actual??this.nodeConfig.actual;return typeof W==="function"?W(this.data):W}get problem(){if(this.input.problem)return this.input.problem;let W=this.meta?.problem??this.nodeConfig.problem;return typeof W==="function"?W(this):W}get message(){if(this.input.message)return this.input.message;let W=this.meta?.message??this.nodeConfig.message;return typeof W==="function"?W(this):W}get flat(){return this.hasCode("intersection")?[...this.errors]:[this]}toJSON(){return{data:this.data,path:this.path,...this.input,expected:this.expected,actual:this.actual,problem:this.problem,message:this.message}}toString(){return this.message}throw(){throw this}}class p1 extends bY{[j1]="errors";ctx;constructor(W){super();this.ctx=W}byPath=Object.create(null);get flatByPath(){return $0(this.byPath,(W,$)=>[W,$.flat])}get flatProblemsByPath(){return $0(this.byPath,(W,$)=>[W,$.flat.map((X)=>X.problem)])}byAncestorPath=Object.create(null);count=0;mutable=this;throw(){throw this.toTraversalError()}toTraversalError(){return new p5(this)}add(W){if(this.includes(W))return;this._add(W)}transform(W){let $=new p1(this.ctx);for(let X of this)$.add(W(X));return $}merge(W){for(let $ of W){if(this.includes($))continue;this._add(new m2({...$,path:[...this.ctx.path,...$.path]},this.ctx))}}affectsPath(W){if(this.length===0)return!1;return W.stringifyAncestors().some(($)=>($ in this.byPath))||W.stringify()in this.byAncestorPath}get summary(){return this.toString()}get issues(){return this}toJSON(){return[...this.map((W)=>W.toJSON())]}toString(){return this.join(`
98
+ `)}_add(W){let $=this.byPath[W.propString];if($){if($.hasCode("union")&&$.errors.length===0)return;let X=W.hasCode("union")&&W.errors.length===0?W:new m2({code:"intersection",errors:$.hasCode("intersection")?[...$.errors,W]:[$,W]},this.ctx),Y=this.indexOf($);this.mutable[Y===-1?this.length:Y]=X,this.byPath[W.propString]=X,this.addAncestorPaths(W)}else this.byPath[W.propString]=W,this.addAncestorPaths(W),this.mutable.push(W);this.count++}addAncestorPaths(W){for(let $ of W.path.stringifyAncestors())this.byAncestorPath[$]=M0(this.byAncestorPath[$],W)}}class p5 extends Error{name="TraversalError";constructor(W){if(W.length===1)super(W.summary);else super(`
99
+ `+W.map(($)=>` \u2022 ${NK($)}`).join(`
100
+ `));Object.defineProperty(this,"arkErrors",{value:W,enumerable:!1})}}var NK=(W)=>W.toString().split(`
112
101
  `).join(`
113
- `);class mJ{path=[];errors=new $J(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(T,$){this.root=T,this.config=$}get data(){let T=this.root;for(let $ of this.path)T=T?.[$];return T}get propString(){return N1(this.path)}reject(T){return this.error(T),!1}mustBe(T){return this.error(T),!1}error(T){let $=typeof T==="object"?T.code?T:{...T,code:"predicate"}:{code:"predicate",expected:T};return this.errorFromContext($)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches.at(-1)}queueMorphs(T){let $={path:new W8(...this.path),morphs:T};if(this.currentBranch)this.currentBranch.queuedMorphs.push($);else this.queuedMorphs.push($)}finalize(T){if(this.queuedMorphs.length){if(typeof this.root==="object"&&this.root!==null&&this.config.clone)this.root=this.config.clone(this.root);this.applyQueuedMorphs()}if(this.hasError())return T?T(this.errors):this.errors;return this.root}get currentErrorCount(){return this.currentBranch?this.currentBranch.error?1:0:this.errors.count}get failFast(){return this.branches.length!==0}pushBranch(){this.branches.push({error:void 0,queuedMorphs:[]})}popBranch(){return this.branches.pop()}get external(){return this}errorFromNodeContext(T){return this.errorFromContext(T)}errorFromContext(T){let $=new X0(T,this);if(this.currentBranch)this.currentBranch.error=$;else this.errors.add($);return $}applyQueuedMorphs(){while(this.queuedMorphs.length){let T=this.queuedMorphs;this.queuedMorphs=[];for(let{path:$,morphs:J}of T){if(this.errors.affectsPath($))continue;this.applyMorphsAtPath($,J)}}}applyMorphsAtPath(T,$){let J=T.at(-1),W;if(J!==void 0){W=this.root;for(let X=0;X<T.length-1;X++)W=W[T[X]]}this.path=[...T];for(let X of $){let F=uT(X),Y=X(W===void 0?this.root:W[J],this);if(Y instanceof X0){this.errors.add(Y);break}if(Y instanceof $J){if(!F)this.errors.merge(Y);break}if(W===void 0)this.root=Y;else W[J]=Y;this.applyQueuedMorphs()}}}var JJ=(T,$,J)=>{if(!J)return $();J.path.push(T);let W=$();return J.path.pop(),W};class G8 extends hJ{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(T,$){super((W,X,F=this.onFail)=>{if(X)return this.traverseApply(W,X),X.hasError()?X.errors:X.data;return this.rootApply(W,F)},{attach:T});this.attachments=T,this.$=$,this.onFail=this.meta.onFail??this.$.resolvedConfig.onFail,this.includesTransform=this.hasKind("morph")||this.hasKind("structure")&&this.structuralMorph!==void 0,this.includesContextualPredicate=this.hasKind("predicate")&&this.inner.predicate.length!==1,this.isCyclic=this.kind==="alias",this.referencesById={[this.id]:this},this.shallowReferences=this.hasKind("structure")?[this,...this.children]:this.children.reduce((W,X)=>XV(W,X.shallowReferences),[this]);let J=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let W=0;W<this.children.length;W++){if(this.includesTransform||=this.children[W].includesTransform,this.includesContextualPredicate||=this.children[W].includesContextualPredicate,this.isCyclic||=this.children[W].isCyclic,!J){let X=this.children[W].flatRefs;for(let F=0;F<X.length;F++){let Y=X[F];if(!this.flatRefs.some((G)=>Sw(G,Y))){this.flatRefs.push(Y);for(let G of Y.node.branches)if(G.hasKind("morph")||G.hasKind("intersection")&&G.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:Y.path,propString:Y.propString,node:G})}}}Object.assign(this.referencesById,this.children[W].referencesById)}this.flatRefs.sort((W,X)=>W.path.length>X.path.length?1:W.path.length<X.path.length?-1:W.propString>X.propString?1:W.propString<X.propString?-1:W.node.expression<X.node.expression?-1:1),this.allowsRequiresContext=this.includesContextualPredicate||this.isCyclic,this.rootApplyStrategy=!this.allowsRequiresContext&&this.flatMorphs.length===0?this.shallowMorphs.length===0?"allows":this.shallowMorphs.every((W)=>W.length===1||W.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((W)=>W.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(W)=>this.traverseAllows(W,new mJ(W,this.$.resolvedConfig)):(W)=>this.traverseAllows(W)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return($,J)=>{if(this.allows($))return $;let W=new mJ($,this.$.resolvedConfig);return this.traverseApply($,W),W.finalize(J)};case"contextual":return($,J)=>{let W=new mJ($,this.$.resolvedConfig);return this.traverseApply($,W),W.finalize(J)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let T=this.$.resolvedConfig.clone;return($,J)=>{if(this.allows($))return this.contextFreeMorph(T&&(typeof $==="object"&&$!==null||typeof $==="function")?T($):$);let W=new mJ($,this.$.resolvedConfig);return this.traverseApply($,W),W.finalize(J)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,RT(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=WV(this.metaJson);cacheGetter(T,$){return Object.defineProperty(this,T,{value:$}),$}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=aW(this.kind);precompilation;assert=(T,$)=>this(T,$,(J)=>J.throw());traverse(T,$){return this(T,$,null)}get in(){return this.cacheGetter("in",this.getIo("in"))}get out(){return this.cacheGetter("out",this.getIo("out"))}getIo(T){if(!this.includesTransform)return this;let $={};for(let[J,W]of this.innerEntries){let X=this.impl.keys[J];if(X.reduceIo)X.reduceIo(T,$,W);else if(X.child){let F=W;$[J]=hT(F)?F.map((Y)=>Y[T]):F[T]}else $[J]=W}return this.$.node(this.kind,$)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(T){let $=uT(T)?T:this.$.parseDefinition(T);return this.innerHash===$.innerHash}ifEquals(T){return this.equals(T)?this:void 0}hasKind(T){return this.kind===T}assertHasKind(T){if(this.kind!==T)o0(`${this.kind} node was not of asserted kind ${T}`);return this}hasKindIn(...T){return T.includes(this.kind)}assertHasKindIn(...T){if(!R1(T,this.kind))o0(`${this.kind} node was not one of asserted kinds ${T}`);return this}isBasis(){return R1(Qw,this.kind)}isConstraint(){return R1(B6,this.kind)}isStructural(){return R1(iW,this.kind)}isRefinement(){return R1(g9,this.kind)}isRoot(){return R1(tW,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(T){return this.hasKind("unit")&&this.allows(T)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(T){let $=Y8.normalize(T);return this._select($)}_select(T){let $=Y8.applyBoundary[T.boundary??"references"](this);if(T.kind)$=$.filter((J)=>J.kind===T.kind);if(T.where)$=$.filter(T.where);return Y8.applyMethod[T.method??"filter"]($,this,T)}transform(T,$){return this._transform(T,this._createTransformContext($))}_createTransformContext(T){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:T?.prereduced??!1},undeclaredKeyHandling:void 0,...T}}_transform(T,$){let J=$.bindScope??this.$;if($.seen[this.id])return this.$.lazilyResolve($.seen[this.id]);if($.shouldTransform?.(this,$)===!1)return this;let W;if($.seen[this.id]=()=>W,this.hasKind("structure")&&this.undeclared!==$.undeclaredKeyHandling)$={...$,undeclaredKeyHandling:this.undeclared};let X=YT(this.inner,(M,z)=>{if(!this.impl.keys[M].child)return[M,z];let A=z;if(!hT(A)){let _=A._transform(T,$);return _?[M,_]:[]}if(A.length===0)return[M,z];let w=A.flatMap((_)=>{return _._transform(T,$)??[]});return w.length?[M,w]:[]});delete $.seen[this.id];let F=Object.assign(X,{meta:this.meta}),Y=$.selected&&!$.selected.includes(this)?F:T(this.kind,F,$);if(Y===null)return null;if(uT(Y))return W=Y;let G=Object.keys(Y);if((G.length===0||G.length===1&&G[0]==="meta")&&!T1(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in Y))return $.undeclaredKeyHandling?{...Y,value:k.intrinsic.unknown}:null;if(this.kind==="morph")Y.in??=k.intrinsic.unknown;return W=J.node(this.kind,Y,$.parseOptions)}configureReferences(T,$="references"){let J=Y8.normalize($),W=typeof T==="string"?(G,H)=>({...H,meta:{...H.meta,description:T}}):typeof T==="function"?(G,H)=>({...H,meta:T(H.meta)}):(G,H)=>({...H,meta:{...H.meta,...T}});if(J.boundary==="self")return this.$.node(this.kind,W(this.kind,{...this.inner,meta:this.meta}));let X=this._select(J),F=X&&e1(X),Y=J.boundary==="child"?(G,H)=>H.root.children.includes(G):J.boundary==="shallow"?(G)=>G.kind!=="structure":()=>!0;return this.$.finalize(this.transform(W,{shouldTransform:Y,selected:F}))}}var Y8={applyBoundary:{self:(T)=>[T],child:(T)=>[...T.children],shallow:(T)=>[...T.shallowReferences],references:(T)=>[...T.references]},applyMethod:{filter:(T)=>T,assertFilter:(T,$,J)=>{if(T.length===0)o0(Kw($,J));return T},find:(T)=>T[0],assertFind:(T,$,J)=>{if(T.length===0)o0(Kw($,J));return T[0]}},normalize:(T)=>typeof T==="function"?{boundary:"references",method:"filter",where:T}:typeof T==="string"?V$(T,Y8.applyBoundary)?{method:"filter",boundary:T}:{boundary:"references",method:"filter",kind:T}:{boundary:"references",method:"filter",...T}},Kw=(T,$)=>`${T} had no references matching ${GT($)}.`,$V=(T)=>N1(T,{stringifyNonKey:($)=>$.expression}),JV=/"(\$ark\.[^"]+)"/g,WV=(T)=>JSON.stringify(T).replaceAll(JV,"$1"),gJ=(T,$)=>({path:T,node:$,propString:$V(T)}),Sw=(T,$)=>T.propString===$.propString&&T.node.equals($.node),c9=(T,$)=>eJ(T,$,{isEqual:Sw}),XV=(T,$)=>eJ(T,$,{isEqual:(J,W)=>J.equals(W)});class v extends Array{static init(T,$,J,W){return new v({kind:T,l:$,r:J,path:W?.path??[],optional:W?.optional??!1})}add(T,$,J,W){return this.push({kind:T,l:$,r:J,path:W?.path??[],optional:W?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:T,l:$,r:J}=this[0],W=N1(T);return d9(`Intersection${W&&` at ${W}`} of ${Vw($,J)}`)}return`The following intersections result in unsatisfiable types:
114
- \u2022 ${this.map(({path:T,l:$,r:J})=>`${T}: ${Vw($,J)}`).join(`
115
- \u2022 `)}`}throw(){return R(this.describeReasons())}invert(){let T=this.map(($)=>({...$,l:$.r,r:$.l}));if(!(T instanceof v))return new v(...T);return T}withPrefixKey(T,$){return this.map((J)=>({...J,path:[T,...J.path],optional:J.optional||$==="optional"}))}toNeverIfDisjoint(){return k.intrinsic.never}}var Vw=(T,$)=>`${o9(T)} and ${o9($)}`,o9=(T)=>uT(T)?T.expression:hT(T)?T.map(o9).join(" | ")||"never":String(T),d9=(T)=>`${T} results in an unsatisfiable type`;var sW={},WJ=(T,$,J)=>cT(T,$,{$:J,invert:!1,pipe:!1}),H8=(T,$,J)=>cT(T,$,{$:J,invert:!1,pipe:!0}),cT=(T,$,J)=>{let W=J.pipe?"|>":"&",X=`${T.hash}${W}${$.hash}`;if(sW[X]!==void 0)return sW[X];if(!J.pipe){let G=`${$.hash}${W}${T.hash}`;if(sW[G]!==void 0){let H=sW[G],M=H instanceof v?H.invert():H;return sW[X]=M,M}}let F=!J.pipe||!T.includesTransform&&!$.includesTransform;if(F&&T.equals($))return T;let Y=F?l9(T,$,J):T.hasKindIn(...tW)?FV(T,$,J):l9(T,$,J);if(uT(Y)){if(T.equals(Y))Y=T;else if($.equals(Y))Y=$}return sW[X]=Y,Y},l9=(T,$,J)=>{let W=T.precedence<$.precedence?T.kind:$.kind,X=T.impl.intersections[$.kind]??$.impl.intersections[T.kind];if(X===void 0)return null;else if(W===T.kind)return X(T,$,J);else{let F=X($,T,{...J,invert:!J.invert});if(F instanceof v)F=F.invert();return F}},FV=(T,$,J)=>T.includesTransform||$.includesTransform?J.invert?Ew($,T,J):Ew(T,$,J):l9(T,$,J),Ew=(T,$,J)=>T.distribute((W)=>YV(W,$,J),(W)=>{let X=W.filter(uT);if(X.length===0)return v.init("union",T.branches,$.branches);if(X.length<T.branches.length||!T.branches.every((G,H)=>G.in.equals(X[H].in)))return J.$.parseSchema(X);let F;if(X.length===1){let G=X[0];if(!F)return G;return J.$.node("morph",{...G.inner,in:G.in.configure(F,"self")})}let Y={branches:X};if(F)Y.meta=F;return J.$.parseSchema(Y)}),YV=(T,$,J)=>{if(T.hasKind("morph")){let X=[...T.morphs];if(T.lastMorphIfNode){let F=cT(T.lastMorphIfNode,$,J);if(F instanceof v)return F;X[X.length-1]=F}else X.push($);return J.$.node("morph",{morphs:X,in:T.inner.in})}if($.hasKind("morph")){let X=cT(T,$.in,J);if(X instanceof v)return X;return J.$.node("morph",{morphs:[$],in:X})}return J.$.node("morph",{morphs:[$],in:T})};class BJ extends G8{constructor(T,$){super(T,$);Object.defineProperty(this,o$,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(T){return WJ(this,T,this.$)}}class Z1 extends BJ{traverseApply=(T,$)=>{if(!this.traverseAllows(T,$))$.errorFromNodeContext(this.errorContext)};compile(T){if(T.traversalKind==="Allows")T.return(this.compiledCondition);else T.if(this.compiledNegation,()=>T.line(`${T.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return W0(this.errorContext)}}var h$=(T)=>($,J)=>{if(hT($)){if($.length===0)return;let X=$.map((F)=>J.$.node(T,F));if(T==="predicate")return X;return X.sort((F,Y)=>F.hash<Y.hash?-1:1)}let W=J.$.node(T,$);return W.hasOpenIntersection()?[W]:W},eW=(T)=>{let $=T.r.shift();if(!$){let W=T.l.length===0&&T.kind==="structure"?k.intrinsic.unknown.internal:T.ctx.$.node(T.kind,Object.assign(T.baseInner,GV(T.l)),{prereduced:!0});for(let X of T.roots){if(W instanceof v)return W;W=cT(X,W,T.ctx)}return W}let J=!1;for(let W=0;W<T.l.length;W++){let X=cT(T.l[W],$,T.ctx);if(X===null)continue;if(X instanceof v)return X;if(!J){if(X.isRoot())return T.roots.push(X),T.l.splice(W),eW(T);T.l[W]=X,J=!0}else if(!T.l.includes(X))return RT(`Unexpectedly encountered multiple distinct intersection results for refinement ${X}`)}if(!J)T.l.push($);if(T.kind==="intersection"){if($.impliedSiblings)for(let W of $.impliedSiblings)eJ(T.r,W)}return eW(T)},TX=(T)=>{return Object.entries(T).flatMap(([J,W])=>(J in f6)?W:[]).sort((J,W)=>J.precedence<W.precedence?-1:J.precedence>W.precedence?1:J.kind==="predicate"&&W.kind==="predicate"?0:J.hash<W.hash?-1:1)},GV=(T)=>{let $={};for(let J of T)if(J.hasOpenIntersection())$[J.kind]=ST($[J.kind],J);else{if($[J.kind])return RT(`Unexpected intersection of closed refinements of kind ${J.kind}`);$[J.kind]=J}return $},Rw=(...T)=>R(Lw(...T)),Lw=(T,$,J)=>{let W=J.hasKind("morph")?"a morph":J.isUnknown()?"unknown":J.exclude($).defaultShortDescription;return`${sA(T)} operand must be ${$.description} (was ${W})`};var Bw=(T,$,J)=>new F0(T,$,J,J,null);class C6 extends hJ{}class F0 extends hJ{[o$]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(T,$,J,W,X){super((...F)=>{let Y=YT(this.names,(G,H)=>{let M=this.arg$.parse(F[G]);if(!M.extends(this.constraints[G]))R(HV(H,this.constraints[G].expression,M.expression));return[H,M]});if(this.defIsLazy()){let G=this.bodyDef(Y);return this.$.parse(G)}return this.$.parse($,{args:Y})});this.paramDefs=T,this.bodyDef=$,this.$=J,this.arg$=W,this.hkt=X,this.description=X?new X().description??`a generic type for ${X.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof C6}cacheGetter(T,$){return Object.defineProperty(this,T,{value:$}),$}get json(){return this.cacheGetter("json",{params:this.params.map((T)=>T[1].isUnknown()?T[0]:[T[0],T[1].json]),body:Mw(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((T)=>typeof T==="string"?[T,k.intrinsic.unknown]:[T[0],this.$.parse(T[1])]))}get names(){return this.cacheGetter("names",this.params.map((T)=>T[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map((T)=>T[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}var HV=(T,$,J)=>`${T} must be assignable to ${$} (was ${J})`;var MV=HT({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:(T)=>typeof T==="function"?{predicate:T}:T,defaults:{description:(T)=>`valid according to ${T.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class fw extends BJ{serializedPredicate=sT(this.predicate);compiledCondition=`${this.serializedPredicate}(data, ctx)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=null;expression=this.serializedPredicate;traverseAllows=this.predicate;errorContext={code:"predicate",description:this.description,meta:this.meta};compiledErrorContext=W0(this.errorContext);traverseApply=(T,$)=>{if(!this.predicate(T,$.external)&&!$.hasError())$.errorFromNodeContext(this.errorContext)};compile(T){if(T.traversalKind==="Allows"){T.return(this.compiledCondition);return}T.if(`${this.compiledNegation} && !ctx.hasError()`,()=>T.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(T,$){return $.fallback.predicate({code:"predicate",base:T,predicate:this.predicate})}}var n9={implementation:MV,Node:fw};var zV=HT({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(T)=>Number.isInteger(T)?T:R(AV(T))}},normalize:(T)=>typeof T==="number"?{rule:T}:T,hasAssociatedError:!0,defaults:{description:(T)=>T.rule===1?"an integer":T.rule===2?"even":`a multiple of ${T.rule}`},intersections:{divisor:(T,$,J)=>J.$.node("divisor",{rule:Math.abs(T.rule*$.rule/wV(T.rule,$.rule))})},obviatesBasisDescription:!0});class Nw extends Z1{traverseAllows=(T)=>T%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=k.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(T){if(T.type="integer",this.rule===1)return T;return T.multipleOf=this.rule,T}}var i9={implementation:zV,Node:Nw};var AV=(T)=>`divisor must be an integer (was ${T})`,wV=(T,$)=>{let J,W=T,X=$;while(X!==0)J=X,X=W%X,W=J;return W};class OJ extends Z1{boundOperandKind=_V[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=DV(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${QV[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?KV(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator["0"]==="<"?"upper":"lower";isStricterThan(T){return(this.limitKind==="upper"?this.numericLimit<T.numericLimit:this.numericLimit>T.numericLimit)||this.numericLimit===T.numericLimit&&this.exclusive===!0&&!T.exclusive}overlapsRange(T){if(this.isStricterThan(T))return!1;if(this.numericLimit===T.numericLimit&&(this.exclusive||T.exclusive))return!1;return!0}overlapIsUnit(T){return this.numericLimit===T.numericLimit&&!this.exclusive&&!T.exclusive}}var QV={"<":">=","<=":">",">":"<=",">=":"<"},OV={min:"max",minLength:"maxLength",after:"before"},Z6={parse:(T)=>T||void 0},q6=(T)=>($)=>{if(typeof $==="number")return{rule:$};let{exclusive:J,...W}=$;return J?{...W,rule:T==="minLength"?W.rule+1:W.rule-1}:W},k6=(T)=>($)=>{if(typeof $==="number"||typeof $==="string"||$ instanceof Date)return{rule:$};let{exclusive:J,...W}=$;if(!J)return W;let X=typeof W.rule==="number"?W.rule:typeof W.rule==="string"?new Date(W.rule).valueOf():W.rule.valueOf();return J?{...W,rule:T==="after"?X+1:X-1}:W},y6=(T)=>typeof T==="string"||typeof T==="number"?new Date(T):T,UV=(T,$)=>`${T} bound must be a positive integer (was ${$})`,$X=(T)=>($)=>{if(!Number.isInteger($)||$<0)R(UV(T,$));return $},_V={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},DV=(T,$)=>`${V$(T,OV)?">":"<"}${$?"":"="}`,KV=(T)=>typeof T==="string"?T:new Date(T).toLocaleString(),Cw=(T)=>`Bounded expression ${T} must be exactly one of number, string, Array, or Date`;var SV=HT({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:y6,serialize:(T)=>T.toISOString()}},normalize:k6("after"),defaults:{description:(T)=>`${T.collapsibleLimitString} or later`,actual:i0},intersections:{after:(T,$)=>T.isStricterThan($)?T:$}});class Zw extends OJ{impliedBasis=k.intrinsic.Date.internal;collapsibleLimitString=i0(this.rule);traverseAllows=(T)=>T>=this.rule;reduceJsonSchema(T,$){return $.fallback.date({code:"date",base:T,after:this.rule})}}var t9={implementation:SV,Node:Zw};var VV=HT({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:y6,serialize:(T)=>T.toISOString()}},normalize:k6("before"),defaults:{description:(T)=>`${T.collapsibleLimitString} or earlier`,actual:i0},intersections:{before:(T,$)=>T.isStricterThan($)?T:$,after:(T,$,J)=>T.overlapsRange($)?T.overlapIsUnit($)?J.$.node("unit",{unit:T.rule}):null:v.init("range",T,$)}});class qw extends OJ{collapsibleLimitString=i0(this.rule);traverseAllows=(T)=>T<=this.rule;impliedBasis=k.intrinsic.Date.internal;reduceJsonSchema(T,$){return $.fallback.date({code:"date",base:T,before:this.rule})}}var r9={implementation:VV,Node:qw};var EV=HT({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:$X("exactLength")}},normalize:(T)=>typeof T==="number"?{rule:T}:T,hasAssociatedError:!0,defaults:{description:(T)=>`exactly length ${T.rule}`,actual:(T)=>`${T.length}`},intersections:{exactLength:(T,$,J)=>v.init("unit",J.$.node("unit",{unit:T.rule}),J.$.node("unit",{unit:$.rule}),{path:["length"]}),minLength:(T,$)=>T.rule>=$.rule?T:v.init("range",T,$),maxLength:(T,$)=>T.rule<=$.rule?T:v.init("range",T,$)}});class kw extends Z1{traverseAllows=(T)=>T.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=k.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(T){switch(T.type){case"string":return T.minLength=this.rule,T.maxLength=this.rule,T;case"array":return T.minItems=this.rule,T.maxItems=this.rule,T;default:return nT.throwInternalOperandError("exactLength",T)}}}var a9={implementation:EV,Node:kw};var RV=HT({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:Z6},normalize:(T)=>typeof T==="number"?{rule:T}:T,defaults:{description:(T)=>{if(T.rule===0)return T.exclusive?"negative":"non-positive";return`${T.exclusive?"less than":"at most"} ${T.rule}`}},intersections:{max:(T,$)=>T.isStricterThan($)?T:$,min:(T,$,J)=>T.overlapsRange($)?T.overlapIsUnit($)?J.$.node("unit",{unit:T.rule}):null:v.init("range",T,$)},obviatesBasisDescription:!0});class yw extends OJ{impliedBasis=k.intrinsic.number.internal;traverseAllows=this.exclusive?(T)=>T<this.rule:(T)=>T<=this.rule;reduceJsonSchema(T){if(this.exclusive)T.exclusiveMaximum=this.rule;else T.maximum=this.rule;return T}}var s9={implementation:RV,Node:yw};var LV=HT({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:$X("maxLength")}},reduce:(T,$)=>T.rule===0?$.node("exactLength",T):void 0,normalize:q6("maxLength"),defaults:{description:(T)=>`at most length ${T.rule}`,actual:(T)=>`${T.length}`},intersections:{maxLength:(T,$)=>T.isStricterThan($)?T:$,minLength:(T,$,J)=>T.overlapsRange($)?T.overlapIsUnit($)?J.$.node("exactLength",{rule:T.rule}):null:v.init("range",T,$)}});class Iw extends OJ{impliedBasis=k.intrinsic.lengthBoundable.internal;traverseAllows=(T)=>T.length<=this.rule;reduceJsonSchema(T){switch(T.type){case"string":return T.maxLength=this.rule,T;case"array":return T.maxItems=this.rule,T;default:return nT.throwInternalOperandError("maxLength",T)}}}var e9={implementation:LV,Node:Iw};var BV=HT({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:Z6},normalize:(T)=>typeof T==="number"?{rule:T}:T,defaults:{description:(T)=>{if(T.rule===0)return T.exclusive?"positive":"non-negative";return`${T.exclusive?"more than":"at least"} ${T.rule}`}},intersections:{min:(T,$)=>T.isStricterThan($)?T:$},obviatesBasisDescription:!0});class jw extends OJ{impliedBasis=k.intrinsic.number.internal;traverseAllows=this.exclusive?(T)=>T>this.rule:(T)=>T>=this.rule;reduceJsonSchema(T){if(this.exclusive)T.exclusiveMinimum=this.rule;else T.minimum=this.rule;return T}}var T5={implementation:BV,Node:jw};var fV=HT({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:$X("minLength")}},reduce:(T)=>T.rule===0?k.intrinsic.unknown:void 0,normalize:q6("minLength"),defaults:{description:(T)=>T.rule===1?"non-empty":`at least length ${T.rule}`,actual:(T)=>T.length===0?"":`${T.length}`},intersections:{minLength:(T,$)=>T.isStricterThan($)?T:$}});class xw extends OJ{impliedBasis=k.intrinsic.lengthBoundable.internal;traverseAllows=(T)=>T.length>=this.rule;reduceJsonSchema(T){switch(T.type){case"string":return T.minLength=this.rule,T;case"array":return T.minItems=this.rule,T;default:return nT.throwInternalOperandError("minLength",T)}}}var $5={implementation:fV,Node:xw};var Pw={min:T5.implementation,max:s9.implementation,minLength:$5.implementation,maxLength:e9.implementation,exactLength:a9.implementation,after:t9.implementation,before:r9.implementation},bw={min:T5.Node,max:s9.Node,minLength:$5.Node,maxLength:e9.Node,exactLength:a9.Node,after:t9.Node,before:r9.Node};var NV=HT({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:(T)=>typeof T==="string"?{rule:T}:T instanceof RegExp?T.flags?{rule:T.source,flags:T.flags}:{rule:T.source}:T,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:(T)=>`matched by ${T.rule}`},intersections:{pattern:()=>null}});class vw extends Z1{instance=new RegExp(this.rule,this.flags);expression=`${this.instance}`;traverseAllows=this.instance.test.bind(this.instance);compiledCondition=`${this.expression}.test(data)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=k.intrinsic.string.internal;reduceJsonSchema(T,$){if(T.pattern)return $.fallback.patternIntersection({code:"patternIntersection",base:T,pattern:this.rule});return T.pattern=this.rule,T}}var J5={implementation:NV,Node:vw};var M8=(T,$)=>{let J=CV(T);if($&&!$.includes(J))return R(`Root of kind ${J} should be one of ${$}`);return J},CV=(T)=>{if(l(T,"root"))return T.kind;if(typeof T==="string")return T[0]==="$"?"alias":(T in TJ)?"domain":"proto";if(typeof T==="function")return"proto";if(typeof T!=="object"||T===null)return R(hw(T));if("morphs"in T)return"morph";if("branches"in T||hT(T))return"union";if("unit"in T)return"unit";if("reference"in T)return"alias";let $=Object.keys(T);if($.length===0||$.some((J)=>(J in f6)))return"intersection";if("proto"in T)return"proto";if("domain"in T)return"domain";return R(hw(T))},hw=(T)=>`${GT(T)} is not a valid type schema`,mw={},ZV=(T)=>hT(T)?T.map(($)=>$.collapsibleJson):T.collapsibleJson,d$={};k.nodesByRegisteredId=d$;var W5=(T)=>{return mw[T]??=0,`${T}${++mw[T]}`},X5=(T)=>{let $=JX[T.kind],J=$.applyConfig?.(T.def,T.$.resolvedConfig)??T.def,W={},{meta:X,...F}=J,Y=X===void 0?{}:typeof X==="string"?{description:X}:X,G=C9(F).sort(([M],[z])=>rW(M)?rW(z)?aW(M)-aW(z):1:rW(z)?-1:M<z?-1:1).filter(([M,z])=>{if(M.startsWith("meta.")){let A=M.slice(5);return Y[A]=z,!1}return!0});for(let M of G){let z=M[0],A=$.keys[z];if(!A)return R(`Key ${z} is not valid on ${T.kind} schema`);let w=A.parse?A.parse(M[1],T):M[1];if(w!==QJ&&(w!==void 0||A.preserveUndefined))W[z]=w}if($.reduce&&!T.prereduced){let M=$.reduce(W,T.$);if(M){if(M instanceof v)return M.throw();return qV(M,Y)}}return F5({id:T.id,kind:T.kind,inner:W,meta:Y,$:T.$})},F5=({id:T,kind:$,inner:J,meta:W,$:X,ignoreCache:F})=>{let Y=JX[$],G=C9(J),H=[],M={};for(let[q,N]of G){let y=Y.keys[q],V=y.serialize??(y.child?ZV:LJ);if(M[q]=V(N),y.child===!0){let f=N;if(hT(f))H.push(...f);else H.push(f)}else if(typeof y.child==="function")H.push(...y.child(N))}if(Y.finalizeInnerJson)M=Y.finalizeInnerJson(M);let z={...M},A={};if(!T1(W))A=YT(W,(q,N)=>[q,q==="examples"?N:LJ(N)]),z.meta=I6(A,"description",!0);M=I6(M,Y.collapsibleKey,!1);let w=JSON.stringify({kind:$,...M});z=I6(z,Y.collapsibleKey,!1);let _=I6(z,Y.collapsibleKey,!0),D=JSON.stringify({kind:$,...z});if(X.nodesByHash[D]&&!F)return X.nodesByHash[D];let S={id:T,kind:$,impl:Y,inner:J,innerEntries:G,innerJson:M,innerHash:w,meta:W,metaJson:A,json:z,hash:D,collapsibleJson:_,children:H};if($!=="intersection"){for(let q in J)if(q!=="in"&&q!=="out")S[q]=J[q]}let Z=new pw[$](S,X);return X.nodesByHash[D]=Z},gw=(T,$)=>{if(T.id===$)return T;if(uT(d$[$]))RT(`Unexpected attempt to overwrite node id ${$}`);return F5({id:$,kind:T.kind,inner:T.inner,meta:T.meta,$:T.$,ignoreCache:!0})},qV=(T,$,J)=>{if(J&&uT(d$[J]))RT(`Unexpected attempt to overwrite node id ${J}`);return F5({id:J??W5($.alias??T.kind),kind:T.kind,inner:T.inner,meta:$,$:T.$})},I6=(T,$,J)=>{let W=Object.keys(T);if(W.length===1&&W[0]===$){let X=T[$];if(J)return X;if(e$(X,"object")&&(Object.keys(X).length===1||Array.isArray(X)))return X}return T};var z8=(T,$,J)=>{if(T.key!==$.key)return null;let W=T.key,X=cT(T.value,$.value,J),F=T.required||$.required?"required":"optional";if(X instanceof v)if(F==="optional")X=k.intrinsic.never.internal;else return X.withPrefixKey(T.key,T.required&&$.required?"required":"optional");if(F==="required")return J.$.node("required",{key:W,value:X});let Y=T.hasDefault()?$.hasDefault()?T.default===$.default?T.default:R(Y5(T.default,$.default)):T.default:$.hasDefault()?$.default:QJ;return J.$.node("optional",{key:W,value:X,default:Y})};class A8 extends BJ{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=k.intrinsic.object.internal;serializedKey=C1(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=ST(this.value.flatRefs.map((T)=>gJ([this.key,...T.path],T.node)),gJ([this.key],this.value));_transform(T,$){$.path.push(this.key);let J=super._transform(T,$);return $.path.pop(),J}hasDefault(){return"default"in this.inner}traverseAllows=(T,$)=>{if(this.key in T)return JJ(this.key,()=>this.value.traverseAllows(T[this.key],$),$);return this.optional};traverseApply=(T,$)=>{if(this.key in T)JJ(this.key,()=>this.value.traverseApply(T[this.key],$),$);else if(this.hasKind("required"))$.errorFromNodeContext(this.errorContext)};compile(T){if(T.if(`${this.serializedKey} in data`,()=>T.traverseKey(this.serializedKey,`data${T.prop(this.key)}`,this.value)),this.hasKind("required"))T.else(()=>T.traversalKind==="Apply"?T.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):T.return(!1));if(T.traversalKind==="Allows")T.return(!0)}}var Y5=(T,$)=>`Invalid intersection of default values ${GT(T)} & ${GT($)}`;var kV=HT({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(T,$)=>$.$.parseSchema(T)},default:{preserveUndefined:!0}},normalize:(T)=>T,reduce:(T,$)=>{if($.resolvedConfig.exactOptionalPropertyTypes===!1){if(!T.value.allows(void 0))return $.node("optional",{...T,value:T.value.or(e.undefined)},{prereduced:!0})}},defaults:{description:(T)=>`${T.compiledKey}?: ${T.value.description}`},intersections:{optional:z8}});class uw extends A8{constructor(...T){super(...T);if("default"in this.inner)Q8(this.value,this.inner.default,this.key)}get outProp(){if(!this.hasDefault())return this;let{default:T,...$}=this.inner;return this.cacheGetter("outProp",this.$.node("required",$,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${GT(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=IV(this);defaultValueMorphRef=this.defaultValueMorph&&sT(this.defaultValueMorph)}var w8={implementation:kV,Node:uw},yV={},IV=(T)=>{if(!T.hasDefault())return;let $=`{${T.compiledKey}: ${T.value.id} = ${LJ(T.default)}}`;return yV[$]??=G5(T.key,T.value,T.default)},G5=(T,$,J)=>{if(typeof J==="function")return $.includesTransform?(X,F)=>{return JJ(T,()=>$(X[T]=J(),F),F),X}:(X)=>{return X[T]=J(),X};let W=$.includesTransform?$.assert(J):J;return e$(W,"object")?(X,F)=>{return JJ(T,()=>$(X[T]=J,F),F),X}:(X)=>{return X[T]=W,X}},Q8=(T,$,J)=>{let W=T0($);if(e$($,"object")&&!W)R(jV(J));let X=T.in(W?$():$);if(X instanceof $J){if(J===null)R(`Default ${X.summary}`);let F=X.transform((Y)=>Y.transform((G)=>({...G,prefixPath:[J]})));R(`Default for ${F.summary}`)}return $},jV=(T)=>{return`Non-primitive default ${T===null?"":typeof T==="number"?`for value at [${T}] `:`for ${C1(T)} `}must be specified as a function like () => ({my: 'object'})`};class fJ extends G8{constructor(T,$){super(T,$);Object.defineProperty(this,o$,{value:"root",enumerable:!1})}get internal(){return this}get "~standard"(){return{vendor:"arktype",version:1,validate:(T)=>{let $=this(T);if($ instanceof $J)return $;return{value:$}}}}as(){return this}brand(T){if(T==="")return R(xV);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(T,$){let J=this.branches.map(T);return $?.(J)??J}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(T={}){let $=p9(this.$.resolvedConfig.toJsonSchema,T);$.useRefs||=this.isCyclic;let J=typeof $.dialect==="string"?{$schema:$.dialect}:{};if(Object.assign(J,this.toJsonSchemaRecurse($)),$.useRefs)J.$defs=YT(this.references,(W,X)=>X.isRoot()&&!X.alwaysExpandJsonSchema?[X.id,X.toResolvedJsonSchema($)]:[]);return J}toJsonSchemaRecurse(T){if(T.useRefs&&!this.alwaysExpandJsonSchema)return{$ref:`#/$defs/${this.id}`};return this.toResolvedJsonSchema(T)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(T){let $=this.innerToJsonSchema(T);return Object.assign($,this.metaJson)}intersect(T){let $=this.$.parseDefinition(T),J=this.rawIntersect($);if(J instanceof v)return J;return this.$.finalize(J)}rawIntersect(T){return WJ(this,T,this.$)}toNeverIfDisjoint(){return this}and(T){let $=this.intersect(T);return $ instanceof v?$.throw():$}rawAnd(T){let $=this.rawIntersect(T);return $ instanceof v?$.throw():$}or(T){let $=this.$.parseDefinition(T);return this.$.finalize(this.rawOr($))}rawOr(T){let $=[...this.branches,...T.branches];return this.$.node("union",$)}map(T){return this.$.schema(this.applyStructuralOperation("map",[T]))}pick(...T){return this.$.schema(this.applyStructuralOperation("pick",T))}omit(...T){return this.$.schema(this.applyStructuralOperation("omit",T))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let T=this.applyStructuralOperation("keyof",[]).reduce(($,J)=>$.intersect(J).toNeverIfDisjoint(),k.intrinsic.unknown.internal);if(T.branches.length===0)R(d9(`keyof ${this.expression}`));return this._keyof=this.$.finalize(T)}get props(){if(this.branches.length!==1)return R(PV(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(T){let $=this.$.parseDefinition(T);return this.$.schema($.distribute((J)=>this.applyStructuralOperation("merge",[cw(J)??R(ow("merge",J.expression))])))}applyStructuralOperation(T,$){return this.distribute((J)=>{if(J.equals(k.intrinsic.object)&&T!=="merge")return J;let W=cw(J);if(!W)R(ow(T,J.expression));if(T==="keyof")return W.keyof();if(T==="get")return W.get(...$);if(T==="props")return W.props;let X=T==="required"?"require":T==="partial"?"optionalize":T;return this.$.node("intersection",{...J.inner,structure:W[X](...$)})})}get(...T){if(T[0]===void 0)return this;return this.$.schema(this.applyStructuralOperation("get",T))}extract(T){let $=this.$.parseDefinition(T);return this.$.schema(this.branches.filter((J)=>J.extends($)))}exclude(T){let $=this.$.parseDefinition(T);return this.$.schema(this.branches.filter((J)=>!J.extends($)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(T){return!(this.intersect(T)instanceof v)}extends(T){let $=this.intersect(T);return!($ instanceof v)&&this.equals($)}ifExtends(T){return this.extends(T)?this:void 0}subsumes(T){return this.$.parseDefinition(T).extends(this)}configure(T,$="shallow"){return this.configureReferences(T,$)}describe(T,$="shallow"){return this.configure({description:T},$)}optional(){return[this,"?"]}default(T){return Q8(this,T,null),[this,"=",T]}from(T){return this.assert(T)}_pipe(...T){let $=T.reduce((J,W)=>J.rawPipeOnce(W),this);return this.$.finalize($)}tryPipe(...T){let $=T.reduce((J,W)=>J.rawPipeOnce(l(W,"root")?W:(X,F)=>{try{return W(X,F)}catch(Y){return F.error({code:"predicate",predicate:W,actual:`aborted due to error:
116
- ${Y}
117
- `})}}),this);return this.$.finalize($)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(T){return this.$.finalize(this.toNode(this.$.parseDefinition(T)))}toNode(T){let $=H8(this,T,this.$);if($ instanceof v)return $.throw();return $}rawPipeOnce(T){if(l(T,"root"))return this.toNode(T);return this.distribute(($)=>$.hasKind("morph")?this.$.node("morph",{in:$.inner.in,morphs:[...$.morphs,T]}):this.$.node("morph",{in:$,morphs:[T]}),this.$.parseSchema)}narrow(T){return this.constrainOut("predicate",T)}constrain(T,$){return this._constrain("root",T,$)}constrainIn(T,$){return this._constrain("in",T,$)}constrainOut(T,$){return this._constrain("out",T,$)}_constrain(T,$,J){let W=this.$.node($,J);if(W.isRoot())return W.isUnknown()?this:RT(`Unexpected constraint node ${W}`);let X=T==="root"?this:this[T];if(X.hasKind("morph")||W.impliedBasis&&!X.extends(W.impliedBasis))return Rw($,W.impliedBasis,this);let F=this.$.node("intersection",{[W.kind]:W}),Y=T==="out"?H8(this,F,this.$):WJ(this,F,this.$);if(Y instanceof v)Y.throw();return this.$.finalize(Y)}onUndeclaredKey(T){let $=typeof T==="string"?T:T.rule,J=typeof T==="string"?!1:T.deep;return this.$.finalize(this.transform((W,X)=>W==="structure"?$==="ignore"?pA(X,{undeclared:1}):{...X,undeclared:$}:X,J?void 0:{shouldTransform:(W)=>!R1(iW,W.kind)}))}hasEqualMorphs(T){if(!this.includesTransform&&!T.includesTransform)return!0;if(!B1(this.shallowMorphs,T.shallowMorphs))return!1;if(!B1(this.flatMorphs,T.flatMorphs,{isEqual:($,J)=>$.propString===J.propString&&($.node.hasKind("morph")&&J.node.hasKind("morph")?$.node.hasEqualMorphs(J.node):$.node.hasKind("intersection")&&J.node.hasKind("intersection")?$.node.structure?.structuralMorphRef===J.node.structure?.structuralMorphRef:!1)}))return!1;return!0}onDeepUndeclaredKey(T){return this.onUndeclaredKey({rule:T,deep:!0})}filter(T){return this.constrainIn("predicate",T)}divisibleBy(T){return this.constrain("divisor",T)}matching(T){return this.constrain("pattern",T)}atLeast(T){return this.constrain("min",T)}atMost(T){return this.constrain("max",T)}moreThan(T){return this.constrain("min",WX(T))}lessThan(T){return this.constrain("max",WX(T))}atLeastLength(T){return this.constrain("minLength",T)}atMostLength(T){return this.constrain("maxLength",T)}moreThanLength(T){return this.constrain("minLength",WX(T))}lessThanLength(T){return this.constrain("maxLength",WX(T))}exactlyLength(T){return this.constrain("exactLength",T)}atOrAfter(T){return this.constrain("after",T)}atOrBefore(T){return this.constrain("before",T)}laterThan(T){return this.constrain("after",WX(T))}earlierThan(T){return this.constrain("before",WX(T))}}var xV="Expected a non-empty brand name after #",WX=(T)=>typeof T==="object"&&!(T instanceof Date)?{...T,exclusive:!0}:{rule:T,exclusive:!0},O8=(T,$)=>l($,"root")?l(T,"root")?T.extends($):$.allows(T):l(T,"root")?T.hasUnit($):$===T,cw=(T)=>{if(T.hasKind("morph"))return null;if(T.hasKind("intersection"))return T.inner.structure??(T.basis?.domain==="object"?T.$.bindReference(k.intrinsic.emptyStructure):null);if(T.isBasis()&&T.domain==="object")return T.$.bindReference(k.intrinsic.emptyStructure);return null},PV=(T)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
118
- ${T}`,ow=(T,$)=>`${T} operand must be an object (was ${$})`;var $1=(T,$)=>YT(N6(T),(J,W)=>[W,$]);var bV=(T)=>typeof T==="string"?{reference:T}:T,dw=(T)=>T instanceof v?k.intrinsic.never.internal:T,vV=HT({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(T)=>T.startsWith("$")?T:`$ark.${T}`},resolve:{}},normalize:bV,defaults:{description:(T)=>T.reference},intersections:{alias:(T,$,J)=>J.$.lazilyResolve(()=>dw(cT(T.resolution,$.resolution,J)),`${T.reference}${J.pipe?"=>":"&"}${$.reference}`),...$1("alias",(T,$,J)=>{if($.isUnknown())return T;if($.isNever())return $;if($.isBasis()&&!$.overlaps(k.intrinsic.object))return v.init("assignability",k.intrinsic.object,$);return J.$.lazilyResolve(()=>dw(cT(T.resolution,$,J)),`${T.reference}${J.pipe?"=>":"&"}${$.id}`)})}});class lw extends fJ{expression=this.reference;structure=void 0;get resolution(){let T=this._resolve();return d$[this.id]=T}_resolve(){if(this.resolve)return this.resolve();if(this.reference[0]==="$")return this.$.resolveRoot(this.reference.slice(1));let T=this.reference,$=d$[T],J=[];while(l($,"context")){if(J.includes($.id))return R(hV($.id,J));J.push($.id),$=d$[$.id]}if(!l($,"root"))return RT(`Unexpected resolution for reference ${this.reference}
119
- Seen: [${J.join("->")}]
120
- Resolution: ${GT($)}`);return $}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;let T=this.reference.slice(1),$=this.$.resolutions[T];if(typeof $==="string")return $;if(l($,"root"))return $.id;return RT(`Unexpected resolution for reference ${this.reference}: ${GT($)}`)}get defaultShortDescription(){return TJ.object}innerToJsonSchema(T){return this.resolution.toJsonSchemaRecurse(T)}traverseAllows=(T,$)=>{let J=$.seen[this.reference];if(J?.includes(T))return!0;return $.seen[this.reference]=ST(J,T),this.resolution.traverseAllows(T,$)};traverseApply=(T,$)=>{let J=$.seen[this.reference];if(J?.includes(T))return;$.seen[this.reference]=ST(J,T),this.resolution.traverseApply(T,$)};compile(T){let $=this.resolutionId;T.if(`ctx.seen.${$} && ctx.seen.${$}.includes(data)`,()=>T.return(!0)),T.if(`!ctx.seen.${$}`,()=>T.line(`ctx.seen.${$} = []`)),T.line(`ctx.seen.${$}.push(data)`),T.return(T.invoke($))}}var hV=(T,$)=>`Alias '${T}' has a shallow resolution cycle: ${[...$,T].join("->")}`,U8={implementation:vV,Node:lw};class t0 extends fJ{traverseApply=(T,$)=>{if(!this.traverseAllows(T,$))$.errorFromNodeContext(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return W0(this.errorContext)}compile(T){if(T.traversalKind==="Allows")T.return(this.compiledCondition);else T.if(this.compiledNegation,()=>T.line(`${T.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}}var mV=HT({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(T)=>typeof T==="string"?{domain:T}:lW(T,"numberAllowsNaN")&&T.domain!=="number"?R(j6.writeBadAllowNanMessage(T.domain)):T,applyConfig:(T,$)=>T.numberAllowsNaN===void 0&&T.domain==="number"&&$.numberAllowsNaN?{...T,numberAllowsNaN:!0}:T,defaults:{description:(T)=>TJ[T.domain],actual:(T)=>Number.isNaN(T)?"NaN":TJ[S$(T)]},intersections:{domain:(T,$)=>T.domain==="number"&&$.domain==="number"?T.numberAllowsNaN?$:T:v.init("domain",T,$)}});class nw extends t0{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?(T)=>typeof T==="number"&&!Number.isNaN(T):(T)=>S$(T)===this.domain;compiledCondition=this.domain==="object"?'((typeof data === "object" && data !== null) || typeof data === "function")':`typeof data === "${this.domain}"${this.requiresNaNCheck?" && !Number.isNaN(data)":""}`;compiledNegation=this.domain==="object"?'((typeof data !== "object" || data === null) && typeof data !== "function")':`typeof data !== "${this.domain}"${this.requiresNaNCheck?" || Number.isNaN(data)":""}`;expression=this.numberAllowsNaN?"number | NaN":this.domain;get nestableExpression(){return this.numberAllowsNaN?`(${this.expression})`:this.expression}get defaultShortDescription(){return TJ[this.domain]}innerToJsonSchema(T){if(this.domain==="bigint"||this.domain==="symbol")return T.fallback.domain({code:"domain",base:{},domain:this.domain});return{type:this.domain}}}var j6={implementation:mV,Node:nw,writeBadAllowNanMessage:(T)=>`numberAllowsNaN may only be specified with domain "number" (was ${T})`};var gV=HT({kind:"intersection",hasAssociatedError:!0,normalize:(T)=>{if(uT(T))return T;let{structure:$,...J}=T,W=!!$,X=$??{},F=YT(J,(Y,G)=>{if(V$(Y,Ow)){if(W)R(`Flattened structure key ${Y} cannot be specified alongside a root 'structure' key.`);return X[Y]=G,[]}return[Y,G]});if(l(X,"constraint")||!T1(X))F.structure=X;return F},finalizeInnerJson:({structure:T,...$})=>e$(T,"object")?{...T,...$}:$,keys:{domain:{child:!0,parse:(T,$)=>$.$.node("domain",T)},proto:{child:!0,parse:(T,$)=>$.$.node("proto",T)},structure:{child:!0,parse:(T,$)=>$.$.node("structure",T),serialize:(T)=>{if(!T.sequence?.minLength)return T.collapsibleJson;let{sequence:$,...J}=T.collapsibleJson,{minVariadicLength:W,...X}=$,F=X.variadic&&Object.keys(X).length===1?X.variadic:X;return{...J,sequence:F}}},divisor:{child:!0,parse:h$("divisor")},max:{child:!0,parse:h$("max")},min:{child:!0,parse:h$("min")},maxLength:{child:!0,parse:h$("maxLength")},minLength:{child:!0,parse:h$("minLength")},exactLength:{child:!0,parse:h$("exactLength")},before:{child:!0,parse:h$("before")},after:{child:!0,parse:h$("after")},pattern:{child:!0,parse:h$("pattern")},predicate:{child:!0,parse:h$("predicate")}},reduce:(T,$)=>iw({},T,{$,invert:!1,pipe:!1}),defaults:{description:(T)=>{if(T.children.length===0)return"unknown";if(T.structure)return T.structure.description;let $=[];if(T.basis&&!T.refinements.some((J)=>J.impl.obviatesBasisDescription))$.push(T.basis.description);if(T.refinements.length){let J=T.refinements.toSorted((W,X)=>W.kind==="min"&&X.kind==="max"?-1:0).map((W)=>W.description);$.push(...J)}if(T.inner.predicate)$.push(...T.inner.predicate.map((J)=>J.description));return $.join(" and ")},expected:(T)=>` \u25E6 ${T.errors.map(($)=>$.expected).join(`
121
- \u25E6 `)}`,problem:(T)=>`(${T.actual}) must be...
122
- ${T.expected}`},intersections:{intersection:(T,$,J)=>iw(T.inner,$.inner,J),...$1("intersection",(T,$,J)=>{if(T.children.length===0)return $;let{domain:W,proto:X,...F}=T.inner,Y=X??W,G=Y?cT(Y,$,J):$;return G instanceof v?G:T?.basis?.equals(G)?T:T.$.node("intersection",{...F,[G.kind]:G},{prereduced:!0})})}});class tw extends fJ{basis=this.inner.domain??this.inner.proto??null;refinements=this.children.filter((T)=>T.isRefinement());structure=this.inner.structure;expression=pV(this);get shallowMorphs(){return this.inner.structure?.structuralMorph?[this.inner.structure.structuralMorph]:[]}get defaultShortDescription(){return this.basis?.defaultShortDescription??"present"}innerToJsonSchema(T){return this.children.reduce(($,J)=>J.isBasis()?J.toJsonSchemaRecurse(T):J.reduceJsonSchema($,T),{})}traverseAllows=(T,$)=>this.children.every((J)=>J.traverseAllows(T,$));traverseApply=(T,$)=>{let J=$.currentErrorCount;if(this.basis){if(this.basis.traverseApply(T,$),$.currentErrorCount>J)return}if(this.refinements.length){for(let W=0;W<this.refinements.length-1;W++)if(this.refinements[W].traverseApply(T,$),$.failFast&&$.currentErrorCount>J)return;if(this.refinements.at(-1).traverseApply(T,$),$.currentErrorCount>J)return}if(this.structure){if(this.structure.traverseApply(T,$),$.currentErrorCount>J)return}if(this.inner.predicate){for(let W=0;W<this.inner.predicate.length-1;W++)if(this.inner.predicate[W].traverseApply(T,$),$.failFast&&$.currentErrorCount>J)return;this.inner.predicate.at(-1).traverseApply(T,$)}};compile(T){if(T.traversalKind==="Allows"){for(let $ of this.children)T.check($);T.return(!0);return}if(T.initializeErrorCount(),this.basis){if(T.check(this.basis),this.children.length>1)T.returnIfFail()}if(this.refinements.length){for(let $=0;$<this.refinements.length-1;$++)T.check(this.refinements[$]),T.returnIfFailFast();if(T.check(this.refinements.at(-1)),this.structure||this.inner.predicate)T.returnIfFail()}if(this.structure){if(T.check(this.structure),this.inner.predicate)T.returnIfFail()}if(this.inner.predicate){for(let $=0;$<this.inner.predicate.length-1;$++)T.check(this.inner.predicate[$]),T.returnIfFail();T.check(this.inner.predicate.at(-1))}}}var H5={implementation:gV,Node:tw},pV=(T)=>{let $=T.structure?.expression||`${T.basis&&!T.refinements.some((J)=>J.impl.obviatesBasisExpression)?T.basis.nestableExpression+" ":""}${T.refinements.map((J)=>J.expression).join(" & ")}`||"unknown";if($==="Array == 0")$="[]";return $},iw=(T,$,J)=>{let W={},X=T.proto??T.domain,F=$.proto??$.domain,Y=X?F?cT(X,F,J):X:F;if(Y instanceof v)return Y;if(Y)W[Y.kind]=Y;return eW({kind:"intersection",baseInner:W,l:TX(T),r:TX($),roots:[],ctx:J})};var uV=HT({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(T,$)=>$.$.parseSchema(T)},morphs:{parse:e1,serialize:(T)=>T.map(($)=>l($,"root")?$.json:sT($))},declaredIn:{child:!1,serialize:(T)=>T.json},declaredOut:{child:!1,serialize:(T)=>T.json}},normalize:(T)=>T,defaults:{description:(T)=>`a morph from ${T.in.description} to ${T.out?.description??"unknown"}`},intersections:{morph:(T,$,J)=>{if(!T.hasEqualMorphs($))return R(cV(T.expression,$.expression));let W=cT(T.in,$.in,J);if(W instanceof v)return W;let X={morphs:T.morphs};if(T.declaredIn||$.declaredIn){let F=cT(T.in,$.in,J);if(F instanceof v)return F.throw();else X.declaredIn=F}if(T.declaredOut||$.declaredOut){let F=cT(T.out,$.out,J);if(F instanceof v)return F.throw();else X.declaredOut=F}return W.distribute((F)=>J.$.node("morph",{...X,in:F}),J.$.parseSchema)},...$1("morph",(T,$,J)=>{let W=T.inner.in?cT(T.inner.in,$,J):$;return W instanceof v?W:W.equals(T.inner.in)?T:J.$.node("morph",{...T.inner,in:W})})}});class rw extends fJ{serializedMorphs=this.morphs.map(sT);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs.at(-1);lastMorphIfNode=l(this.lastMorph,"root")?this.lastMorph:void 0;introspectableIn=this.inner.in;introspectableOut=this.lastMorphIfNode?Object.assign(this.referencesById,this.lastMorphIfNode.referencesById)&&this.lastMorphIfNode.out:void 0;get shallowMorphs(){return Array.isArray(this.inner.in?.shallowMorphs)?[...this.inner.in.shallowMorphs,...this.morphs]:this.morphs}get in(){return this.declaredIn??this.inner.in?.in??k.intrinsic.unknown.internal}get out(){return this.declaredOut??this.introspectableOut??k.intrinsic.unknown.internal}declareIn(T){return this.$.node("morph",{...this.inner,declaredIn:T})}declareOut(T){return this.$.node("morph",{...this.inner,declaredOut:T})}expression=`(In: ${this.in.expression}) => ${this.lastMorphIfNode?"To":"Out"}<${this.out.expression}>`;get defaultShortDescription(){return this.in.meta.description??this.in.defaultShortDescription}innerToJsonSchema(T){return T.fallback.morph({code:"morph",base:this.in.toJsonSchemaRecurse(T),out:this.introspectableOut?.toJsonSchemaRecurse(T)??null})}compile(T){if(T.traversalKind==="Allows"){if(!this.introspectableIn)return;T.return(T.invoke(this.introspectableIn));return}if(this.introspectableIn)T.line(T.invoke(this.introspectableIn));T.line(`ctx.queueMorphs(${this.compiledMorphs})`)}traverseAllows=(T,$)=>!this.introspectableIn||this.introspectableIn.traverseAllows(T,$);traverseApply=(T,$)=>{if(this.introspectableIn)this.introspectableIn.traverseApply(T,$);$.queueMorphs(this.morphs)};hasEqualMorphs(T){return B1(this.morphs,T.morphs,{isEqual:($,J)=>$===J||l($,"root")&&l(J,"root")&&$.equals(J)})}}var M5={implementation:uV,Node:rw},cV=(T,$)=>`The intersection of distinct morphs at a single path is indeterminate:
123
- Left: ${T}
124
- Right: ${$}`;var oV=HT({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(T)=>a2(T)??LJ(T)},dateAllowsInvalid:{}},normalize:(T)=>{let $=typeof T==="string"?{proto:l0[T]}:typeof T==="function"?uT(T)?T:{proto:T}:typeof T.proto==="string"?{...T,proto:l0[T.proto]}:T;if(typeof $.proto!=="function")R(_8.writeInvalidSchemaMessage($.proto));if(lW($,"dateAllowsInvalid")&&$.proto!==Date)R(_8.writeBadInvalidDateMessage($.proto));return $},applyConfig:(T,$)=>{if(T.dateAllowsInvalid===void 0&&T.proto===Date&&$.dateAllowsInvalid)return{...T,dateAllowsInvalid:!0};return T},defaults:{description:(T)=>T.builtinName?dA[T.builtinName]:`an instance of ${T.proto.name}`,actual:(T)=>T instanceof Date&&T.toString()==="Invalid Date"?"an invalid Date":r2(T)},intersections:{proto:(T,$)=>T.proto===Date&&$.proto===Date?T.dateAllowsInvalid?$:T:I9(T.proto,$.proto)?T:I9($.proto,T.proto)?$:v.init("proto",T,$),domain:(T,$)=>$.domain==="object"?T:v.init("domain",k.intrinsic.object.internal,$)}});class aw extends t0{builtinName=a2(this.proto);serializedConstructor=this.json.proto;requiresInvalidDateCheck=this.proto===Date&&!this.dateAllowsInvalid;traverseAllows=this.requiresInvalidDateCheck?(T)=>T instanceof Date&&T.toString()!=="Invalid Date":(T)=>T instanceof this.proto;compiledCondition=`data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck?' && data.toString() !== "Invalid Date"':""}`;compiledNegation=`!(${this.compiledCondition})`;innerToJsonSchema(T){switch(this.builtinName){case"Array":return{type:"array"};case"Date":return T.fallback.date?.({code:"date",base:{}})??T.fallback.proto({code:"proto",base:{},proto:this.proto});default:return T.fallback.proto({code:"proto",base:{},proto:this.proto})}}expression=this.dateAllowsInvalid?"Date | InvalidDate":this.proto.name;get nestableExpression(){return this.dateAllowsInvalid?`(${this.expression})`:this.expression}domain="object";get defaultShortDescription(){return this.description}}var _8={implementation:oV,Node:aw,writeBadInvalidDateMessage:(T)=>`dateAllowsInvalid may only be specified with constructor Date (was ${T.name})`,writeInvalidSchemaMessage:(T)=>`instanceOf operand must be a function (was ${S$(T)})`};var dV=HT({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(T,$)=>{let J=[];for(let W of T){let X=l(W,"root")?W.branches:$.$.parseSchema(W).branches;for(let F of X)if(F.hasKind("morph")){let Y=J.findIndex((G)=>G.hasKind("morph")&&G.hasEqualMorphs(F));if(Y===-1)J.push(F);else{let G=J[Y];J[Y]=$.$.node("morph",{...G.inner,in:G.in.rawOr(F.in)})}}else J.push(F)}if(!$.def.ordered)J.sort((W,X)=>W.hash<X.hash?-1:1);return J}}},normalize:(T)=>hT(T)?{branches:T}:T,reduce:(T,$)=>{let J=$E(T);if(J.length===1)return J[0];if(J.length===T.branches.length)return;return $.node("union",{...T,branches:J},{prereduced:!0})},defaults:{description:(T)=>T.distribute(($)=>$.description,XX),expected:(T)=>{let $=vA(T.errors,"propString"),J=Object.entries($).map(([W,X])=>{let F=[];for(let H of X)eJ(F,H.expected);let Y=XX(F),G=X.every((H)=>H.actual===X[0].actual)?X[0].actual:GT(X[0].data);return`${W&&`${W} `}must be ${Y}${G&&` (was ${G})`}`});return XX(J)},problem:(T)=>T.expected,message:(T)=>T.problem},intersections:{union:(T,$,J)=>{if(T.isNever!==$.isNever)return v.init("presence",T,$);let W;if(T.ordered){if($.ordered)R(WE(T.expression,$.expression));if(W=z5($.branches,T.branches,J),W instanceof v)W.invert()}else W=z5(T.branches,$.branches,J);if(W instanceof v)return W;return J.$.parseSchema(T.ordered||$.ordered?{branches:W,ordered:!0}:{branches:W})},...$1("union",(T,$,J)=>{let W=z5(T.branches,[$],J);if(W instanceof v)return W;if(W.length===1)return W[0];return J.$.parseSchema(T.ordered?{branches:W,ordered:!0}:{branches:W})})}});class TQ extends fJ{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){let T=[],$=-1;for(let J of this.branches){if(J.hasKind("unit")&&J.domain==="boolean"){if($===-1)$=T.length,T.push(J);else T[$]=k.intrinsic.boolean;continue}T.push(J)}return T}unitBranches=this.branches.filter((T)=>T.in.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?sV(this.discriminant):null;expression=this.distribute((T)=>T.nestableExpression,TE);createBranchedOptimisticRootApply(){return(T,$)=>{let J=this.traverseOptimistic(T);if(J!==QJ)return J;let W=new mJ(T,this.$.resolvedConfig);return this.traverseApply(T,W),W.finalize($)}}get shallowMorphs(){return this.branches.reduce((T,$)=>eJ(T,$.shallowMorphs),[])}get defaultShortDescription(){return this.distribute((T)=>T.defaultShortDescription,XX)}innerToJsonSchema(T){if(this.branchGroups.length===1&&this.branchGroups[0].equals(k.intrinsic.boolean))return{type:"boolean"};let $=this.branchGroups.map((J)=>J.toJsonSchemaRecurse(T));if($.every((J)=>Object.keys(J).length===1&&lW(J,"const")))return{enum:$.map((J)=>J.const)};return{anyOf:$}}traverseAllows=(T,$)=>this.branches.some((J)=>J.traverseAllows(T,$));traverseApply=(T,$)=>{let J=[];for(let W=0;W<this.branches.length;W++){if($.pushBranch(),this.branches[W].traverseApply(T,$),!$.hasError()){if(this.branches[W].includesTransform)return $.queuedMorphs.push(...$.popBranch().queuedMorphs);return $.popBranch()}J.push($.popBranch().error)}$.errorFromNodeContext({code:"union",errors:J,meta:this.meta})};traverseOptimistic=(T)=>{for(let $=0;$<this.branches.length;$++){let J=this.branches[$];if(J.traverseAllows(T)){if(J.contextFreeMorph)return J.contextFreeMorph(T);return T}}return QJ};compile(T){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(T);let $=this.discriminant.optionallyChainedPropString;if(this.discriminant.kind==="domain")$=`typeof ${$} === "object" ? ${$} === null ? "null" : "object" : typeof ${$} === "function" ? "object" : typeof ${$}`;let J=this.discriminant.cases,W=Object.keys(J),{optimistic:X}=T;if(T.optimistic=!1,T.block(`switch(${$})`,()=>{for(let M in J){let z=J[M],A=M==="default"?M:`case ${M}`;T.line(`${A}: return ${z===!0?X?T.data:z:X?`${T.invoke(z)} ? ${z.contextFreeMorph?`${sT(z.contextFreeMorph)}(${T.data})`:T.data} : "${QJ}"`:T.invoke(z)}`)}return T}),T.traversalKind==="Allows"){T.return(X?`"${QJ}"`:!1);return}let F=XX(this.discriminant.kind==="domain"?W.map((M)=>{let z=M.slice(1,-1);return z==="function"?TJ.object:TJ[z]}):W),Y=this.discriminant.path.map((M)=>typeof M==="symbol"?sT(M):JSON.stringify(M)),G=JSON.stringify(F),H=this.discriminant.kind==="domain"?`${rV}[${$}]`:`${aV}(${$})`;T.line(`ctx.errorFromNodeContext({
102
+ `);class ZW{path=[];errors=new p1(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(W,$){this.root=W,this.config=$}get data(){let W=this.root;for(let $ of this.path)W=W?.[$];return W}get propString(){return F2(this.path)}reject(W){return this.error(W),!1}mustBe(W){return this.error(W),!1}error(W){let $=typeof W==="object"?W.code?W:{...W,code:"predicate"}:{code:"predicate",expected:W};return this.errorFromContext($)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches.at(-1)}queueMorphs(W){let $={path:new k6(...this.path),morphs:W};if(this.currentBranch)this.currentBranch.queuedMorphs.push($);else this.queuedMorphs.push($)}finalize(W){if(this.queuedMorphs.length){if(typeof this.root==="object"&&this.root!==null&&this.config.clone)this.root=this.config.clone(this.root);this.applyQueuedMorphs()}if(this.hasError())return W?W(this.errors):this.errors;return this.root}get currentErrorCount(){return this.currentBranch?this.currentBranch.error?1:0:this.errors.count}get failFast(){return this.branches.length!==0}pushBranch(){this.branches.push({error:void 0,queuedMorphs:[]})}popBranch(){return this.branches.pop()}get external(){return this}errorFromNodeContext(W){return this.errorFromContext(W)}errorFromContext(W){let $=new m2(W,this);if(this.currentBranch)this.currentBranch.error=$;else this.errors.add($);return $}applyQueuedMorphs(){while(this.queuedMorphs.length){let W=this.queuedMorphs;this.queuedMorphs=[];for(let{path:$,morphs:X}of W){if(this.errors.affectsPath($))continue;this.applyMorphsAtPath($,X)}}}applyMorphsAtPath(W,$){let X=W.at(-1),Y;if(X!==void 0){Y=this.root;for(let J=0;J<W.length-1;J++)Y=Y[W[J]]}this.path=[...W];for(let J of $){let G=P0(J),H=J(Y===void 0?this.root:Y[X],this);if(H instanceof m2){this.errors.add(H);break}if(H instanceof p1){if(!G)this.errors.merge(H);break}if(Y===void 0)this.root=H;else Y[X]=H;this.applyQueuedMorphs()}}}var u1=(W,$,X)=>{if(!X)return $();X.path.push(W);let Y=$();return X.path.pop(),Y};class P6 extends RW{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(W,$){super((Y,J,G=this.onFail)=>{if(J)return this.traverseApply(Y,J),J.hasError()?J.errors:J.data;return this.rootApply(Y,G)},{attach:W});this.attachments=W,this.$=$,this.onFail=this.meta.onFail??this.$.resolvedConfig.onFail,this.includesTransform=this.hasKind("morph")||this.hasKind("structure")&&this.structuralMorph!==void 0,this.includesContextualPredicate=this.hasKind("predicate")&&this.inner.predicate.length!==1,this.isCyclic=this.kind==="alias",this.referencesById={[this.id]:this},this.shallowReferences=this.hasKind("structure")?[this,...this.children]:this.children.reduce((Y,J)=>SK(Y,J.shallowReferences),[this]);let X=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let Y=0;Y<this.children.length;Y++){if(this.includesTransform||=this.children[Y].includesTransform,this.includesContextualPredicate||=this.children[Y].includesContextualPredicate,this.isCyclic||=this.children[Y].isCyclic,!X){let J=this.children[Y].flatRefs;for(let G=0;G<J.length;G++){let H=J[G];if(!this.flatRefs.some((Q)=>lT(Q,H))){this.flatRefs.push(H);for(let Q of H.node.branches)if(Q.hasKind("morph")||Q.hasKind("intersection")&&Q.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:H.path,propString:H.propString,node:Q})}}}Object.assign(this.referencesById,this.children[Y].referencesById)}this.flatRefs.sort((Y,J)=>Y.path.length>J.path.length?1:Y.path.length<J.path.length?-1:Y.propString>J.propString?1:Y.propString<J.propString?-1:Y.node.expression<J.node.expression?-1:1),this.allowsRequiresContext=this.includesContextualPredicate||this.isCyclic,this.rootApplyStrategy=!this.allowsRequiresContext&&this.flatMorphs.length===0?this.shallowMorphs.length===0?"allows":this.shallowMorphs.every((Y)=>Y.length===1||Y.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((Y)=>Y.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(Y)=>this.traverseAllows(Y,new ZW(Y,this.$.resolvedConfig)):(Y)=>this.traverseAllows(Y)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return($,X)=>{if(this.allows($))return $;let Y=new ZW($,this.$.resolvedConfig);return this.traverseApply($,Y),Y.finalize(X)};case"contextual":return($,X)=>{let Y=new ZW($,this.$.resolvedConfig);return this.traverseApply($,Y),Y.finalize(X)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let W=this.$.resolvedConfig.clone;return($,X)=>{if(this.allows($))return this.contextFreeMorph(W&&(typeof $==="object"&&$!==null||typeof $==="function")?W($):$);let Y=new ZW($,this.$.resolvedConfig);return this.traverseApply($,Y),Y.finalize(X)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,O0(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=ZK(this.metaJson);cacheGetter(W,$){return Object.defineProperty(this,W,{value:$}),$}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=B$(this.kind);precompilation;assert=(W,$)=>this(W,$,(X)=>X.throw());traverse(W,$){return this(W,$,null)}get in(){return this.cacheGetter("in",this.getIo("in"))}get out(){return this.cacheGetter("out",this.getIo("out"))}getIo(W){if(!this.includesTransform)return this;let $={};for(let[X,Y]of this.innerEntries){let J=this.impl.keys[X];if(J.reduceIo)J.reduceIo(W,$,Y);else if(J.child){let G=Y;$[X]=C0(G)?G.map((H)=>H[W]):G[W]}else $[X]=Y}return this.$.node(this.kind,$)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(W){let $=P0(W)?W:this.$.parseDefinition(W);return this.innerHash===$.innerHash}ifEquals(W){return this.equals(W)?this:void 0}hasKind(W){return this.kind===W}assertHasKind(W){if(this.kind!==W)A8(`${this.kind} node was not of asserted kind ${W}`);return this}hasKindIn(...W){return W.includes(this.kind)}assertHasKindIn(...W){if(!G2(W,this.kind))A8(`${this.kind} node was not one of asserted kinds ${W}`);return this}isBasis(){return G2(gT,this.kind)}isConstraint(){return G2(pY,this.kind)}isStructural(){return G2(A$,this.kind)}isRefinement(){return G2(g5,this.kind)}isRoot(){return G2(E$,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(W){return this.hasKind("unit")&&this.allows(W)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(W){let $=f6.normalize(W);return this._select($)}_select(W){let $=f6.applyBoundary[W.boundary??"references"](this);if(W.kind)$=$.filter((X)=>X.kind===W.kind);if(W.where)$=$.filter(W.where);return f6.applyMethod[W.method??"filter"]($,this,W)}transform(W,$){return this._transform(W,this._createTransformContext($))}_createTransformContext(W){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:W?.prereduced??!1},undeclaredKeyHandling:void 0,...W}}_transform(W,$){let X=$.bindScope??this.$;if($.seen[this.id])return this.$.lazilyResolve($.seen[this.id]);if($.shouldTransform?.(this,$)===!1)return this;let Y;if($.seen[this.id]=()=>Y,this.hasKind("structure")&&this.undeclared!==$.undeclaredKeyHandling)$={...$,undeclaredKeyHandling:this.undeclared};let J=$0(this.inner,(F,T)=>{if(!this.impl.keys[F].child)return[F,T];let U=T;if(!C0(U)){let V=U._transform(W,$);return V?[F,V]:[]}if(U.length===0)return[F,T];let M=U.flatMap((V)=>{return V._transform(W,$)??[]});return M.length?[F,M]:[]});delete $.seen[this.id];let G=Object.assign(J,{meta:this.meta}),H=$.selected&&!$.selected.includes(this)?G:W(this.kind,G,$);if(H===null)return null;if(P0(H))return Y=H;let Q=Object.keys(H);if((Q.length===0||Q.length===1&&Q[0]==="meta")&&!uW(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in H))return $.undeclaredKeyHandling?{...H,value:R.intrinsic.unknown}:null;if(this.kind==="morph")H.in??=R.intrinsic.unknown;return Y=X.node(this.kind,H,$.parseOptions)}configureReferences(W,$="references"){let X=f6.normalize($),Y=typeof W==="string"?(Q,z)=>({...z,meta:{...z.meta,description:W}}):typeof W==="function"?(Q,z)=>({...z,meta:W(z.meta)}):(Q,z)=>({...z,meta:{...z.meta,...W}});if(X.boundary==="self")return this.$.node(this.kind,Y(this.kind,{...this.inner,meta:this.meta}));let J=this._select(X),G=J&&v2(J),H=X.boundary==="child"?(Q,z)=>z.root.children.includes(Q):X.boundary==="shallow"?(Q)=>Q.kind!=="structure":()=>!0;return this.$.finalize(this.transform(Y,{shouldTransform:H,selected:G}))}}var f6={applyBoundary:{self:(W)=>[W],child:(W)=>[...W.children],shallow:(W)=>[...W.shallowReferences],references:(W)=>[...W.references]},applyMethod:{filter:(W)=>W,assertFilter:(W,$,X)=>{if(W.length===0)A8(dT($,X));return W},find:(W)=>W[0],assertFind:(W,$,X)=>{if(W.length===0)A8(dT($,X));return W[0]}},normalize:(W)=>typeof W==="function"?{boundary:"references",method:"filter",where:W}:typeof W==="string"?z1(W,f6.applyBoundary)?{method:"filter",boundary:W}:{boundary:"references",method:"filter",kind:W}:{boundary:"references",method:"filter",...W}},dT=(W,$)=>`${W} had no references matching ${X0($)}.`,BK=(W)=>F2(W,{stringifyNonKey:($)=>$.expression}),RK=/"(\$ark\.[^"]+)"/g,ZK=(W)=>JSON.stringify(W).replaceAll(RK,"$1"),SW=(W,$)=>({path:W,node:$,propString:BK(W)}),lT=(W,$)=>W.propString===$.propString&&W.node.equals($.node),u5=(W,$)=>pW(W,$,{isEqual:lT}),SK=(W,$)=>pW(W,$,{isEqual:(X,Y)=>X.equals(Y)});class P extends Array{static init(W,$,X,Y){return new P({kind:W,l:$,r:X,path:Y?.path??[],optional:Y?.optional??!1})}add(W,$,X,Y){return this.push({kind:W,l:$,r:X,path:Y?.path??[],optional:Y?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:W,l:$,r:X}=this[0],Y=F2(W);return d5(`Intersection${Y&&` at ${Y}`} of ${oT($,X)}`)}return`The following intersections result in unsatisfiable types:
103
+ \u2022 ${this.map(({path:W,l:$,r:X})=>`${W}: ${oT($,X)}`).join(`
104
+ \u2022 `)}`}throw(){return L(this.describeReasons())}invert(){let W=this.map(($)=>({...$,l:$.r,r:$.l}));if(!(W instanceof P))return new P(...W);return W}withPrefixKey(W,$){return this.map((X)=>({...X,path:[W,...X.path],optional:X.optional||$==="optional"}))}toNeverIfDisjoint(){return R.intrinsic.never}}var oT=(W,$)=>`${c5(W)} and ${c5($)}`,c5=(W)=>P0(W)?W.expression:C0(W)?W.map(c5).join(" | ")||"never":String(W),d5=(W)=>`${W} results in an unsatisfiable type`;var R$={},c1=(W,$,X)=>x0(W,$,{$:X,invert:!1,pipe:!1}),x6=(W,$,X)=>x0(W,$,{$:X,invert:!1,pipe:!0}),x0=(W,$,X)=>{let Y=X.pipe?"|>":"&",J=`${W.hash}${Y}${$.hash}`;if(R$[J]!==void 0)return R$[J];if(!X.pipe){let Q=`${$.hash}${Y}${W.hash}`;if(R$[Q]!==void 0){let z=R$[Q],F=z instanceof P?z.invert():z;return R$[J]=F,F}}let G=!X.pipe||!W.includesTransform&&!$.includesTransform;if(G&&W.equals($))return W;let H=G?l5(W,$,X):W.hasKindIn(...E$)?qK(W,$,X):l5(W,$,X);if(P0(H)){if(W.equals(H))H=W;else if($.equals(H))H=$}return R$[J]=H,H},l5=(W,$,X)=>{let Y=W.precedence<$.precedence?W.kind:$.kind,J=W.impl.intersections[$.kind]??$.impl.intersections[W.kind];if(J===void 0)return null;else if(Y===W.kind)return J(W,$,X);else{let G=J($,W,{...X,invert:!X.invert});if(G instanceof P)G=G.invert();return G}},qK=(W,$,X)=>W.includesTransform||$.includesTransform?X.invert?iT($,W,X):iT(W,$,X):l5(W,$,X),iT=(W,$,X)=>W.distribute((Y)=>CK(Y,$,X),(Y)=>{let J=Y.filter(P0);if(J.length===0)return P.init("union",W.branches,$.branches);if(J.length<W.branches.length||!W.branches.every((Q,z)=>Q.in.equals(J[z].in)))return X.$.parseSchema(J);let G;if(J.length===1){let Q=J[0];if(!G)return Q;return X.$.node("morph",{...Q.inner,in:Q.in.configure(G,"self")})}let H={branches:J};if(G)H.meta=G;return X.$.parseSchema(H)}),CK=(W,$,X)=>{if(W.hasKind("morph")){let J=[...W.morphs];if(W.lastMorphIfNode){let G=x0(W.lastMorphIfNode,$,X);if(G instanceof P)return G;J[J.length-1]=G}else J.push($);return X.$.node("morph",{morphs:J,in:W.inner.in})}if($.hasKind("morph")){let J=x0(W,$.in,X);if(J instanceof P)return J;return X.$.node("morph",{morphs:[$],in:J})}return X.$.node("morph",{morphs:[$],in:W})};class FW extends P6{constructor(W,$){super(W,$);Object.defineProperty(this,j1,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(W){return c1(this,W,this.$)}}class U2 extends FW{traverseApply=(W,$)=>{if(!this.traverseAllows(W,$))$.errorFromNodeContext(this.errorContext)};compile(W){if(W.traversalKind==="Allows")W.return(this.compiledCondition);else W.if(this.compiledNegation,()=>W.line(`${W.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return g2(this.errorContext)}}var B1=(W)=>($,X)=>{if(C0($)){if($.length===0)return;let J=$.map((G)=>X.$.node(W,G));if(W==="predicate")return J;return J.sort((G,H)=>G.hash<H.hash?-1:1)}let Y=X.$.node(W,$);return Y.hasOpenIntersection()?[Y]:Y},Z$=(W)=>{let $=W.r.shift();if(!$){let Y=W.l.length===0&&W.kind==="structure"?R.intrinsic.unknown.internal:W.ctx.$.node(W.kind,Object.assign(W.baseInner,kK(W.l)),{prereduced:!0});for(let J of W.roots){if(Y instanceof P)return Y;Y=x0(J,Y,W.ctx)}return Y}let X=!1;for(let Y=0;Y<W.l.length;Y++){let J=x0(W.l[Y],$,W.ctx);if(J===null)continue;if(J instanceof P)return J;if(!X){if(J.isRoot())return W.roots.push(J),W.l.splice(Y),Z$(W);W.l[Y]=J,X=!0}else if(!W.l.includes(J))return O0(`Unexpectedly encountered multiple distinct intersection results for refinement ${J}`)}if(!X)W.l.push($);if(W.kind==="intersection"){if($.impliedSiblings)for(let Y of $.impliedSiblings)pW(W.r,Y)}return Z$(W)},S$=(W)=>{return Object.entries(W).flatMap(([X,Y])=>(X in uY)?Y:[]).sort((X,Y)=>X.precedence<Y.precedence?-1:X.precedence>Y.precedence?1:X.kind==="predicate"&&Y.kind==="predicate"?0:X.hash<Y.hash?-1:1)},kK=(W)=>{let $={};for(let X of W)if(X.hasOpenIntersection())$[X.kind]=M0($[X.kind],X);else{if($[X.kind])return O0(`Unexpected intersection of closed refinements of kind ${X.kind}`);$[X.kind]=X}return $},nT=(...W)=>L(rT(...W)),rT=(W,$,X)=>{let Y=X.hasKind("morph")?"a morph":X.isUnknown()?"unknown":X.exclude($).defaultShortDescription;return`${RT(W)} operand must be ${$.description} (was ${Y})`};var tT=(W,$,X)=>new p2(W,$,X,X,null);class dY extends RW{}class p2 extends RW{[j1]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(W,$,X,Y,J){super((...G)=>{let H=$0(this.names,(Q,z)=>{let F=this.arg$.parse(G[Q]);if(!F.extends(this.constraints[Q]))L(IK(z,this.constraints[Q].expression,F.expression));return[z,F]});if(this.defIsLazy()){let Q=this.bodyDef(H);return this.$.parse(Q)}return this.$.parse($,{args:H})});this.paramDefs=W,this.bodyDef=$,this.$=X,this.arg$=Y,this.hkt=J,this.description=J?new J().description??`a generic type for ${J.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof dY}cacheGetter(W,$){return Object.defineProperty(this,W,{value:$}),$}get json(){return this.cacheGetter("json",{params:this.params.map((W)=>W[1].isUnknown()?W[0]:[W[0],W[1].json]),body:vT(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((W)=>typeof W==="string"?[W,R.intrinsic.unknown]:[W[0],this.$.parse(W[1])]))}get names(){return this.cacheGetter("names",this.params.map((W)=>W[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map((W)=>W[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}var IK=(W,$,X)=>`${W} must be assignable to ${$} (was ${X})`;var jK=Y0({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:(W)=>typeof W==="function"?{predicate:W}:W,defaults:{description:(W)=>`valid according to ${W.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class aT extends FW{serializedPredicate=c0(this.predicate);compiledCondition=`${this.serializedPredicate}(data, ctx)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=null;expression=this.serializedPredicate;traverseAllows=this.predicate;errorContext={code:"predicate",description:this.description,meta:this.meta};compiledErrorContext=g2(this.errorContext);traverseApply=(W,$)=>{if(!this.predicate(W,$.external)&&!$.hasError())$.errorFromNodeContext(this.errorContext)};compile(W){if(W.traversalKind==="Allows"){W.return(this.compiledCondition);return}W.if(`${this.compiledNegation} && !ctx.hasError()`,()=>W.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(W,$){return $.fallback.predicate({code:"predicate",base:W,predicate:this.predicate})}}var o5={implementation:jK,Node:aT};var fK=Y0({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(W)=>Number.isInteger(W)?W:L(PK(W))}},normalize:(W)=>typeof W==="number"?{rule:W}:W,hasAssociatedError:!0,defaults:{description:(W)=>W.rule===1?"an integer":W.rule===2?"even":`a multiple of ${W.rule}`},intersections:{divisor:(W,$,X)=>X.$.node("divisor",{rule:Math.abs(W.rule*$.rule/xK(W.rule,$.rule))})},obviatesBasisDescription:!0});class sT extends U2{traverseAllows=(W)=>W%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=R.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(W){if(W.type="integer",this.rule===1)return W;return W.multipleOf=this.rule,W}}var i5={implementation:fK,Node:sT};var PK=(W)=>`divisor must be an integer (was ${W})`,xK=(W,$)=>{let X,Y=W,J=$;while(J!==0)X=J,J=Y%J,Y=X;return Y};class WW extends U2{boundOperandKind=hK[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=gK(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${vK[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?mK(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator["0"]==="<"?"upper":"lower";isStricterThan(W){return(this.limitKind==="upper"?this.numericLimit<W.numericLimit:this.numericLimit>W.numericLimit)||this.numericLimit===W.numericLimit&&this.exclusive===!0&&!W.exclusive}overlapsRange(W){if(this.isStricterThan(W))return!1;if(this.numericLimit===W.numericLimit&&(this.exclusive||W.exclusive))return!1;return!0}overlapIsUnit(W){return this.numericLimit===W.numericLimit&&!this.exclusive&&!W.exclusive}}var vK={"<":">=","<=":">",">":"<=",">=":"<"},bK={min:"max",minLength:"maxLength",after:"before"},lY={parse:(W)=>W||void 0},oY=(W)=>($)=>{if(typeof $==="number")return{rule:$};let{exclusive:X,...Y}=$;return X?{...Y,rule:W==="minLength"?Y.rule+1:Y.rule-1}:Y},iY=(W)=>($)=>{if(typeof $==="number"||typeof $==="string"||$ instanceof Date)return{rule:$};let{exclusive:X,...Y}=$;if(!X)return Y;let J=typeof Y.rule==="number"?Y.rule:typeof Y.rule==="string"?new Date(Y.rule).valueOf():Y.rule.valueOf();return X?{...Y,rule:W==="after"?J+1:J-1}:Y},nY=(W)=>typeof W==="string"||typeof W==="number"?new Date(W):W,yK=(W,$)=>`${W} bound must be a positive integer (was ${$})`,q$=(W)=>($)=>{if(!Number.isInteger($)||$<0)L(yK(W,$));return $},hK={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},gK=(W,$)=>`${z1(W,bK)?">":"<"}${$?"":"="}`,mK=(W)=>typeof W==="string"?W:new Date(W).toLocaleString(),eT=(W)=>`Bounded expression ${W} must be exactly one of number, string, Array, or Date`;var pK=Y0({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:nY,serialize:(W)=>W.toISOString()}},normalize:iY("after"),defaults:{description:(W)=>`${W.collapsibleLimitString} or later`,actual:R8},intersections:{after:(W,$)=>W.isStricterThan($)?W:$}});class WU extends WW{impliedBasis=R.intrinsic.Date.internal;collapsibleLimitString=R8(this.rule);traverseAllows=(W)=>W>=this.rule;reduceJsonSchema(W,$){return $.fallback.date({code:"date",base:W,after:this.rule})}}var n5={implementation:pK,Node:WU};var uK=Y0({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:nY,serialize:(W)=>W.toISOString()}},normalize:iY("before"),defaults:{description:(W)=>`${W.collapsibleLimitString} or earlier`,actual:R8},intersections:{before:(W,$)=>W.isStricterThan($)?W:$,after:(W,$,X)=>W.overlapsRange($)?W.overlapIsUnit($)?X.$.node("unit",{unit:W.rule}):null:P.init("range",W,$)}});class $U extends WW{collapsibleLimitString=R8(this.rule);traverseAllows=(W)=>W<=this.rule;impliedBasis=R.intrinsic.Date.internal;reduceJsonSchema(W,$){return $.fallback.date({code:"date",base:W,before:this.rule})}}var r5={implementation:uK,Node:$U};var cK=Y0({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:q$("exactLength")}},normalize:(W)=>typeof W==="number"?{rule:W}:W,hasAssociatedError:!0,defaults:{description:(W)=>`exactly length ${W.rule}`,actual:(W)=>`${W.length}`},intersections:{exactLength:(W,$,X)=>P.init("unit",X.$.node("unit",{unit:W.rule}),X.$.node("unit",{unit:$.rule}),{path:["length"]}),minLength:(W,$)=>W.rule>=$.rule?W:P.init("range",W,$),maxLength:(W,$)=>W.rule<=$.rule?W:P.init("range",W,$)}});class XU extends U2{traverseAllows=(W)=>W.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=R.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(W){switch(W.type){case"string":return W.minLength=this.rule,W.maxLength=this.rule,W;case"array":return W.minItems=this.rule,W.maxItems=this.rule,W;default:return y0.throwInternalOperandError("exactLength",W)}}}var t5={implementation:cK,Node:XU};var dK=Y0({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:lY},normalize:(W)=>typeof W==="number"?{rule:W}:W,defaults:{description:(W)=>{if(W.rule===0)return W.exclusive?"negative":"non-positive";return`${W.exclusive?"less than":"at most"} ${W.rule}`}},intersections:{max:(W,$)=>W.isStricterThan($)?W:$,min:(W,$,X)=>W.overlapsRange($)?W.overlapIsUnit($)?X.$.node("unit",{unit:W.rule}):null:P.init("range",W,$)},obviatesBasisDescription:!0});class YU extends WW{impliedBasis=R.intrinsic.number.internal;traverseAllows=this.exclusive?(W)=>W<this.rule:(W)=>W<=this.rule;reduceJsonSchema(W){if(this.exclusive)W.exclusiveMaximum=this.rule;else W.maximum=this.rule;return W}}var a5={implementation:dK,Node:YU};var lK=Y0({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:q$("maxLength")}},reduce:(W,$)=>W.rule===0?$.node("exactLength",W):void 0,normalize:oY("maxLength"),defaults:{description:(W)=>`at most length ${W.rule}`,actual:(W)=>`${W.length}`},intersections:{maxLength:(W,$)=>W.isStricterThan($)?W:$,minLength:(W,$,X)=>W.overlapsRange($)?W.overlapIsUnit($)?X.$.node("exactLength",{rule:W.rule}):null:P.init("range",W,$)}});class JU extends WW{impliedBasis=R.intrinsic.lengthBoundable.internal;traverseAllows=(W)=>W.length<=this.rule;reduceJsonSchema(W){switch(W.type){case"string":return W.maxLength=this.rule,W;case"array":return W.maxItems=this.rule,W;default:return y0.throwInternalOperandError("maxLength",W)}}}var s5={implementation:lK,Node:JU};var oK=Y0({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:lY},normalize:(W)=>typeof W==="number"?{rule:W}:W,defaults:{description:(W)=>{if(W.rule===0)return W.exclusive?"positive":"non-negative";return`${W.exclusive?"more than":"at least"} ${W.rule}`}},intersections:{min:(W,$)=>W.isStricterThan($)?W:$},obviatesBasisDescription:!0});class GU extends WW{impliedBasis=R.intrinsic.number.internal;traverseAllows=this.exclusive?(W)=>W>this.rule:(W)=>W>=this.rule;reduceJsonSchema(W){if(this.exclusive)W.exclusiveMinimum=this.rule;else W.minimum=this.rule;return W}}var e5={implementation:oK,Node:GU};var iK=Y0({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:q$("minLength")}},reduce:(W)=>W.rule===0?R.intrinsic.unknown:void 0,normalize:oY("minLength"),defaults:{description:(W)=>W.rule===1?"non-empty":`at least length ${W.rule}`,actual:(W)=>W.length===0?"":`${W.length}`},intersections:{minLength:(W,$)=>W.isStricterThan($)?W:$}});class HU extends WW{impliedBasis=R.intrinsic.lengthBoundable.internal;traverseAllows=(W)=>W.length>=this.rule;reduceJsonSchema(W){switch(W.type){case"string":return W.minLength=this.rule,W;case"array":return W.minItems=this.rule,W;default:return y0.throwInternalOperandError("minLength",W)}}}var W7={implementation:iK,Node:HU};var QU={min:e5.implementation,max:a5.implementation,minLength:W7.implementation,maxLength:s5.implementation,exactLength:t5.implementation,after:n5.implementation,before:r5.implementation},zU={min:e5.Node,max:a5.Node,minLength:W7.Node,maxLength:s5.Node,exactLength:t5.Node,after:n5.Node,before:r5.Node};var nK=Y0({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:(W)=>typeof W==="string"?{rule:W}:W instanceof RegExp?W.flags?{rule:W.source,flags:W.flags}:{rule:W.source}:W,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:(W)=>`matched by ${W.rule}`},intersections:{pattern:()=>null}});class FU extends U2{instance=new RegExp(this.rule,this.flags);expression=`${this.instance}`;traverseAllows=this.instance.test.bind(this.instance);compiledCondition=`${this.expression}.test(data)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=R.intrinsic.string.internal;reduceJsonSchema(W,$){if(W.pattern)return $.fallback.patternIntersection({code:"patternIntersection",base:W,pattern:this.rule});return W.pattern=this.rule,W}}var $7={implementation:nK,Node:FU};var v6=(W,$)=>{let X=rK(W);if($&&!$.includes(X))return L(`Root of kind ${X} should be one of ${$}`);return X},rK=(W)=>{if(d(W,"root"))return W.kind;if(typeof W==="string")return W[0]==="$"?"alias":(W in m1)?"domain":"proto";if(typeof W==="function")return"proto";if(typeof W!=="object"||W===null)return L(TU(W));if("morphs"in W)return"morph";if("branches"in W||C0(W))return"union";if("unit"in W)return"unit";if("reference"in W)return"alias";let $=Object.keys(W);if($.length===0||$.some((X)=>(X in uY)))return"intersection";if("proto"in W)return"proto";if("domain"in W)return"domain";return L(TU(W))},TU=(W)=>`${X0(W)} is not a valid type schema`,UU={},tK=(W)=>C0(W)?W.map(($)=>$.collapsibleJson):W.collapsibleJson,f1={};R.nodesByRegisteredId=f1;var X7=(W)=>{return UU[W]??=0,`${W}${++UU[W]}`},Y7=(W)=>{let $=C$[W.kind],X=$.applyConfig?.(W.def,W.$.resolvedConfig)??W.def,Y={},{meta:J,...G}=X,H=J===void 0?{}:typeof J==="string"?{description:J}:J,Q=S5(G).sort(([F],[T])=>N$(F)?N$(T)?B$(F)-B$(T):1:N$(T)?-1:F<T?-1:1).filter(([F,T])=>{if(F.startsWith("meta.")){let U=F.slice(5);return H[U]=T,!1}return!0});for(let F of Q){let T=F[0],U=$.keys[T];if(!U)return L(`Key ${T} is not valid on ${W.kind} schema`);let M=U.parse?U.parse(F[1],W):F[1];if(M!==e1&&(M!==void 0||U.preserveUndefined))Y[T]=M}if($.reduce&&!W.prereduced){let F=$.reduce(Y,W.$);if(F){if(F instanceof P)return F.throw();return aK(F,H)}}return J7({id:W.id,kind:W.kind,inner:Y,meta:H,$:W.$})},J7=({id:W,kind:$,inner:X,meta:Y,$:J,ignoreCache:G})=>{let H=C$[$],Q=S5(X),z=[],F={};for(let[C,B]of Q){let q=H.keys[C],m=q.serialize??(q.child?tK:zW);if(F[C]=m(B),q.child===!0){let c=B;if(C0(c))z.push(...c);else z.push(c)}else if(typeof q.child==="function")z.push(...q.child(B))}if(H.finalizeInnerJson)F=H.finalizeInnerJson(F);let T={...F},U={};if(!uW(Y))U=$0(Y,(C,B)=>[C,C==="examples"?B:zW(B)]),T.meta=rY(U,"description",!0);F=rY(F,H.collapsibleKey,!1);let M=JSON.stringify({kind:$,...F});T=rY(T,H.collapsibleKey,!1);let V=rY(T,H.collapsibleKey,!0),K=JSON.stringify({kind:$,...T});if(J.nodesByHash[K]&&!G)return J.nodesByHash[K];let N={id:W,kind:$,impl:H,inner:X,innerEntries:Q,innerJson:F,innerHash:M,meta:Y,metaJson:U,json:T,hash:K,collapsibleJson:V,children:z};if($!=="intersection"){for(let C in X)if(C!=="in"&&C!=="out")N[C]=X[C]}let I=new MU[$](N,J);return J.nodesByHash[K]=I},wU=(W,$)=>{if(W.id===$)return W;if(P0(f1[$]))O0(`Unexpected attempt to overwrite node id ${$}`);return J7({id:$,kind:W.kind,inner:W.inner,meta:W.meta,$:W.$,ignoreCache:!0})},aK=(W,$,X)=>{if(X&&P0(f1[X]))O0(`Unexpected attempt to overwrite node id ${X}`);return J7({id:X??X7($.alias??W.kind),kind:W.kind,inner:W.inner,meta:$,$:W.$})},rY=(W,$,X)=>{let Y=Object.keys(W);if(Y.length===1&&Y[0]===$){let J=W[$];if(X)return J;if(g1(J,"object")&&(Object.keys(J).length===1||Array.isArray(J)))return J}return W};var b6=(W,$,X)=>{if(W.key!==$.key)return null;let Y=W.key,J=x0(W.value,$.value,X),G=W.required||$.required?"required":"optional";if(J instanceof P)if(G==="optional")J=R.intrinsic.never.internal;else return J.withPrefixKey(W.key,W.required&&$.required?"required":"optional");if(G==="required")return X.$.node("required",{key:Y,value:J});let H=W.hasDefault()?$.hasDefault()?W.default===$.default?W.default:L(G7(W.default,$.default)):W.default:$.hasDefault()?$.default:e1;return X.$.node("optional",{key:Y,value:J,default:H})};class y6 extends FW{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=R.intrinsic.object.internal;serializedKey=T2(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=M0(this.value.flatRefs.map((W)=>SW([this.key,...W.path],W.node)),SW([this.key],this.value));_transform(W,$){$.path.push(this.key);let X=super._transform(W,$);return $.path.pop(),X}hasDefault(){return"default"in this.inner}traverseAllows=(W,$)=>{if(this.key in W)return u1(this.key,()=>this.value.traverseAllows(W[this.key],$),$);return this.optional};traverseApply=(W,$)=>{if(this.key in W)u1(this.key,()=>this.value.traverseApply(W[this.key],$),$);else if(this.hasKind("required"))$.errorFromNodeContext(this.errorContext)};compile(W){if(W.if(`${this.serializedKey} in data`,()=>W.traverseKey(this.serializedKey,`data${W.prop(this.key)}`,this.value)),this.hasKind("required"))W.else(()=>W.traversalKind==="Apply"?W.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):W.return(!1));if(W.traversalKind==="Allows")W.return(!0)}}var G7=(W,$)=>`Invalid intersection of default values ${X0(W)} & ${X0($)}`;var sK=Y0({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(W,$)=>$.$.parseSchema(W)},default:{preserveUndefined:!0}},normalize:(W)=>W,reduce:(W,$)=>{if($.resolvedConfig.exactOptionalPropertyTypes===!1){if(!W.value.allows(void 0))return $.node("optional",{...W,value:W.value.or(r.undefined)},{prereduced:!0})}},defaults:{description:(W)=>`${W.compiledKey}?: ${W.value.description}`},intersections:{optional:b6}});class _U extends y6{constructor(...W){super(...W);if("default"in this.inner)g6(this.value,this.inner.default,this.key)}get outProp(){if(!this.hasDefault())return this;let{default:W,...$}=this.inner;return this.cacheGetter("outProp",this.$.node("required",$,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${X0(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=WL(this);defaultValueMorphRef=this.defaultValueMorph&&c0(this.defaultValueMorph)}var h6={implementation:sK,Node:_U},eK={},WL=(W)=>{if(!W.hasDefault())return;let $=`{${W.compiledKey}: ${W.value.id} = ${zW(W.default)}}`;return eK[$]??=H7(W.key,W.value,W.default)},H7=(W,$,X)=>{if(typeof X==="function")return $.includesTransform?(J,G)=>{return u1(W,()=>$(J[W]=X(),G),G),J}:(J)=>{return J[W]=X(),J};let Y=$.includesTransform?$.assert(X):X;return g1(Y,"object")?(J,G)=>{return u1(W,()=>$(J[W]=X,G),G),J}:(J)=>{return J[W]=Y,J}},g6=(W,$,X)=>{let Y=b2($);if(g1($,"object")&&!Y)L($L(X));let J=W.in(Y?$():$);if(J instanceof p1){if(X===null)L(`Default ${J.summary}`);let G=J.transform((H)=>H.transform((Q)=>({...Q,prefixPath:[X]})));L(`Default for ${G.summary}`)}return $},$L=(W)=>{return`Non-primitive default ${W===null?"":typeof W==="number"?`for value at [${W}] `:`for ${T2(W)} `}must be specified as a function like () => ({my: 'object'})`};class TW extends P6{constructor(W,$){super(W,$);Object.defineProperty(this,j1,{value:"root",enumerable:!1})}get internal(){return this}get "~standard"(){return{vendor:"arktype",version:1,validate:(W)=>{let $=this(W);if($ instanceof p1)return $;return{value:$}}}}as(){return this}brand(W){if(W==="")return L(XL);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(W,$){let X=this.branches.map(W);return $?.(X)??X}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(W={}){let $=m5(this.$.resolvedConfig.toJsonSchema,W);$.useRefs||=this.isCyclic;let X=typeof $.dialect==="string"?{$schema:$.dialect}:{};if(Object.assign(X,this.toJsonSchemaRecurse($)),$.useRefs)X.$defs=$0(this.references,(Y,J)=>J.isRoot()&&!J.alwaysExpandJsonSchema?[J.id,J.toResolvedJsonSchema($)]:[]);return X}toJsonSchemaRecurse(W){if(W.useRefs&&!this.alwaysExpandJsonSchema)return{$ref:`#/$defs/${this.id}`};return this.toResolvedJsonSchema(W)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(W){let $=this.innerToJsonSchema(W);return Object.assign($,this.metaJson)}intersect(W){let $=this.$.parseDefinition(W),X=this.rawIntersect($);if(X instanceof P)return X;return this.$.finalize(X)}rawIntersect(W){return c1(this,W,this.$)}toNeverIfDisjoint(){return this}and(W){let $=this.intersect(W);return $ instanceof P?$.throw():$}rawAnd(W){let $=this.rawIntersect(W);return $ instanceof P?$.throw():$}or(W){let $=this.$.parseDefinition(W);return this.$.finalize(this.rawOr($))}rawOr(W){let $=[...this.branches,...W.branches];return this.$.node("union",$)}map(W){return this.$.schema(this.applyStructuralOperation("map",[W]))}pick(...W){return this.$.schema(this.applyStructuralOperation("pick",W))}omit(...W){return this.$.schema(this.applyStructuralOperation("omit",W))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let W=this.applyStructuralOperation("keyof",[]).reduce(($,X)=>$.intersect(X).toNeverIfDisjoint(),R.intrinsic.unknown.internal);if(W.branches.length===0)L(d5(`keyof ${this.expression}`));return this._keyof=this.$.finalize(W)}get props(){if(this.branches.length!==1)return L(YL(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(W){let $=this.$.parseDefinition(W);return this.$.schema($.distribute((X)=>this.applyStructuralOperation("merge",[DU(X)??L(VU("merge",X.expression))])))}applyStructuralOperation(W,$){return this.distribute((X)=>{if(X.equals(R.intrinsic.object)&&W!=="merge")return X;let Y=DU(X);if(!Y)L(VU(W,X.expression));if(W==="keyof")return Y.keyof();if(W==="get")return Y.get(...$);if(W==="props")return Y.props;let J=W==="required"?"require":W==="partial"?"optionalize":W;return this.$.node("intersection",{...X.inner,structure:Y[J](...$)})})}get(...W){if(W[0]===void 0)return this;return this.$.schema(this.applyStructuralOperation("get",W))}extract(W){let $=this.$.parseDefinition(W);return this.$.schema(this.branches.filter((X)=>X.extends($)))}exclude(W){let $=this.$.parseDefinition(W);return this.$.schema(this.branches.filter((X)=>!X.extends($)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(W){return!(this.intersect(W)instanceof P)}extends(W){let $=this.intersect(W);return!($ instanceof P)&&this.equals($)}ifExtends(W){return this.extends(W)?this:void 0}subsumes(W){return this.$.parseDefinition(W).extends(this)}configure(W,$="shallow"){return this.configureReferences(W,$)}describe(W,$="shallow"){return this.configure({description:W},$)}optional(){return[this,"?"]}default(W){return g6(this,W,null),[this,"=",W]}from(W){return this.assert(W)}_pipe(...W){let $=W.reduce((X,Y)=>X.rawPipeOnce(Y),this);return this.$.finalize($)}tryPipe(...W){let $=W.reduce((X,Y)=>X.rawPipeOnce(d(Y,"root")?Y:(J,G)=>{try{return Y(J,G)}catch(H){return G.error({code:"predicate",predicate:Y,actual:`aborted due to error:
105
+ ${H}
106
+ `})}}),this);return this.$.finalize($)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(W){return this.$.finalize(this.toNode(this.$.parseDefinition(W)))}toNode(W){let $=x6(this,W,this.$);if($ instanceof P)return $.throw();return $}rawPipeOnce(W){if(d(W,"root"))return this.toNode(W);return this.distribute(($)=>$.hasKind("morph")?this.$.node("morph",{in:$.inner.in,morphs:[...$.morphs,W]}):this.$.node("morph",{in:$,morphs:[W]}),this.$.parseSchema)}narrow(W){return this.constrainOut("predicate",W)}constrain(W,$){return this._constrain("root",W,$)}constrainIn(W,$){return this._constrain("in",W,$)}constrainOut(W,$){return this._constrain("out",W,$)}_constrain(W,$,X){let Y=this.$.node($,X);if(Y.isRoot())return Y.isUnknown()?this:O0(`Unexpected constraint node ${Y}`);let J=W==="root"?this:this[W];if(J.hasKind("morph")||Y.impliedBasis&&!J.extends(Y.impliedBasis))return nT($,Y.impliedBasis,this);let G=this.$.node("intersection",{[Y.kind]:Y}),H=W==="out"?x6(this,G,this.$):c1(this,G,this.$);if(H instanceof P)H.throw();return this.$.finalize(H)}onUndeclaredKey(W){let $=typeof W==="string"?W:W.rule,X=typeof W==="string"?!1:W.deep;return this.$.finalize(this.transform((Y,J)=>Y==="structure"?$==="ignore"?MT(J,{undeclared:1}):{...J,undeclared:$}:J,X?void 0:{shouldTransform:(Y)=>!G2(A$,Y.kind)}))}hasEqualMorphs(W){if(!this.includesTransform&&!W.includesTransform)return!0;if(!Q2(this.shallowMorphs,W.shallowMorphs))return!1;if(!Q2(this.flatMorphs,W.flatMorphs,{isEqual:($,X)=>$.propString===X.propString&&($.node.hasKind("morph")&&X.node.hasKind("morph")?$.node.hasEqualMorphs(X.node):$.node.hasKind("intersection")&&X.node.hasKind("intersection")?$.node.structure?.structuralMorphRef===X.node.structure?.structuralMorphRef:!1)}))return!1;return!0}onDeepUndeclaredKey(W){return this.onUndeclaredKey({rule:W,deep:!0})}filter(W){return this.constrainIn("predicate",W)}divisibleBy(W){return this.constrain("divisor",W)}matching(W){return this.constrain("pattern",W)}atLeast(W){return this.constrain("min",W)}atMost(W){return this.constrain("max",W)}moreThan(W){return this.constrain("min",k$(W))}lessThan(W){return this.constrain("max",k$(W))}atLeastLength(W){return this.constrain("minLength",W)}atMostLength(W){return this.constrain("maxLength",W)}moreThanLength(W){return this.constrain("minLength",k$(W))}lessThanLength(W){return this.constrain("maxLength",k$(W))}exactlyLength(W){return this.constrain("exactLength",W)}atOrAfter(W){return this.constrain("after",W)}atOrBefore(W){return this.constrain("before",W)}laterThan(W){return this.constrain("after",k$(W))}earlierThan(W){return this.constrain("before",k$(W))}}var XL="Expected a non-empty brand name after #",k$=(W)=>typeof W==="object"&&!(W instanceof Date)?{...W,exclusive:!0}:{rule:W,exclusive:!0},m6=(W,$)=>d($,"root")?d(W,"root")?W.extends($):$.allows(W):d(W,"root")?W.hasUnit($):$===W,DU=(W)=>{if(W.hasKind("morph"))return null;if(W.hasKind("intersection"))return W.inner.structure??(W.basis?.domain==="object"?W.$.bindReference(R.intrinsic.emptyStructure):null);if(W.isBasis()&&W.domain==="object")return W.$.bindReference(R.intrinsic.emptyStructure);return null},YL=(W)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
107
+ ${W}`,VU=(W,$)=>`${W} operand must be an object (was ${$})`;var cW=(W,$)=>$0(cY(W),(X,Y)=>[Y,$]);var JL=(W)=>typeof W==="string"?{reference:W}:W,OU=(W)=>W instanceof P?R.intrinsic.never.internal:W,GL=Y0({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(W)=>W.startsWith("$")?W:`$ark.${W}`},resolve:{}},normalize:JL,defaults:{description:(W)=>W.reference},intersections:{alias:(W,$,X)=>X.$.lazilyResolve(()=>OU(x0(W.resolution,$.resolution,X)),`${W.reference}${X.pipe?"=>":"&"}${$.reference}`),...cW("alias",(W,$,X)=>{if($.isUnknown())return W;if($.isNever())return $;if($.isBasis()&&!$.overlaps(R.intrinsic.object))return P.init("assignability",R.intrinsic.object,$);return X.$.lazilyResolve(()=>OU(x0(W.resolution,$,X)),`${W.reference}${X.pipe?"=>":"&"}${$.id}`)})}});class KU extends TW{expression=this.reference;structure=void 0;get resolution(){let W=this._resolve();return f1[this.id]=W}_resolve(){if(this.resolve)return this.resolve();if(this.reference[0]==="$")return this.$.resolveRoot(this.reference.slice(1));let W=this.reference,$=f1[W],X=[];while(d($,"context")){if(X.includes($.id))return L(HL($.id,X));X.push($.id),$=f1[$.id]}if(!d($,"root"))return O0(`Unexpected resolution for reference ${this.reference}
108
+ Seen: [${X.join("->")}]
109
+ Resolution: ${X0($)}`);return $}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;let W=this.reference.slice(1),$=this.$.resolutions[W];if(typeof $==="string")return $;if(d($,"root"))return $.id;return O0(`Unexpected resolution for reference ${this.reference}: ${X0($)}`)}get defaultShortDescription(){return m1.object}innerToJsonSchema(W){return this.resolution.toJsonSchemaRecurse(W)}traverseAllows=(W,$)=>{let X=$.seen[this.reference];if(X?.includes(W))return!0;return $.seen[this.reference]=M0(X,W),this.resolution.traverseAllows(W,$)};traverseApply=(W,$)=>{let X=$.seen[this.reference];if(X?.includes(W))return;$.seen[this.reference]=M0(X,W),this.resolution.traverseApply(W,$)};compile(W){let $=this.resolutionId;W.if(`ctx.seen.${$} && ctx.seen.${$}.includes(data)`,()=>W.return(!0)),W.if(`!ctx.seen.${$}`,()=>W.line(`ctx.seen.${$} = []`)),W.line(`ctx.seen.${$}.push(data)`),W.return(W.invoke($))}}var HL=(W,$)=>`Alias '${W}' has a shallow resolution cycle: ${[...$,W].join("->")}`,p6={implementation:GL,Node:KU};class Z8 extends TW{traverseApply=(W,$)=>{if(!this.traverseAllows(W,$))$.errorFromNodeContext(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return g2(this.errorContext)}compile(W){if(W.traversalKind==="Allows")W.return(this.compiledCondition);else W.if(this.compiledNegation,()=>W.line(`${W.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}}var QL=Y0({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(W)=>typeof W==="string"?{domain:W}:K$(W,"numberAllowsNaN")&&W.domain!=="number"?L(tY.writeBadAllowNanMessage(W.domain)):W,applyConfig:(W,$)=>W.numberAllowsNaN===void 0&&W.domain==="number"&&$.numberAllowsNaN?{...W,numberAllowsNaN:!0}:W,defaults:{description:(W)=>m1[W.domain],actual:(W)=>Number.isNaN(W)?"NaN":m1[Q1(W)]},intersections:{domain:(W,$)=>W.domain==="number"&&$.domain==="number"?W.numberAllowsNaN?$:W:P.init("domain",W,$)}});class LU extends Z8{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?(W)=>typeof W==="number"&&!Number.isNaN(W):(W)=>Q1(W)===this.domain;compiledCondition=this.domain==="object"?'((typeof data === "object" && data !== null) || typeof data === "function")':`typeof data === "${this.domain}"${this.requiresNaNCheck?" && !Number.isNaN(data)":""}`;compiledNegation=this.domain==="object"?'((typeof data !== "object" || data === null) && typeof data !== "function")':`typeof data !== "${this.domain}"${this.requiresNaNCheck?" || Number.isNaN(data)":""}`;expression=this.numberAllowsNaN?"number | NaN":this.domain;get nestableExpression(){return this.numberAllowsNaN?`(${this.expression})`:this.expression}get defaultShortDescription(){return m1[this.domain]}innerToJsonSchema(W){if(this.domain==="bigint"||this.domain==="symbol")return W.fallback.domain({code:"domain",base:{},domain:this.domain});return{type:this.domain}}}var tY={implementation:QL,Node:LU,writeBadAllowNanMessage:(W)=>`numberAllowsNaN may only be specified with domain "number" (was ${W})`};var zL=Y0({kind:"intersection",hasAssociatedError:!0,normalize:(W)=>{if(P0(W))return W;let{structure:$,...X}=W,Y=!!$,J=$??{},G=$0(X,(H,Q)=>{if(z1(H,mT)){if(Y)L(`Flattened structure key ${H} cannot be specified alongside a root 'structure' key.`);return J[H]=Q,[]}return[H,Q]});if(d(J,"constraint")||!uW(J))G.structure=J;return G},finalizeInnerJson:({structure:W,...$})=>g1(W,"object")?{...W,...$}:$,keys:{domain:{child:!0,parse:(W,$)=>$.$.node("domain",W)},proto:{child:!0,parse:(W,$)=>$.$.node("proto",W)},structure:{child:!0,parse:(W,$)=>$.$.node("structure",W),serialize:(W)=>{if(!W.sequence?.minLength)return W.collapsibleJson;let{sequence:$,...X}=W.collapsibleJson,{minVariadicLength:Y,...J}=$,G=J.variadic&&Object.keys(J).length===1?J.variadic:J;return{...X,sequence:G}}},divisor:{child:!0,parse:B1("divisor")},max:{child:!0,parse:B1("max")},min:{child:!0,parse:B1("min")},maxLength:{child:!0,parse:B1("maxLength")},minLength:{child:!0,parse:B1("minLength")},exactLength:{child:!0,parse:B1("exactLength")},before:{child:!0,parse:B1("before")},after:{child:!0,parse:B1("after")},pattern:{child:!0,parse:B1("pattern")},predicate:{child:!0,parse:B1("predicate")}},reduce:(W,$)=>AU({},W,{$,invert:!1,pipe:!1}),defaults:{description:(W)=>{if(W.children.length===0)return"unknown";if(W.structure)return W.structure.description;let $=[];if(W.basis&&!W.refinements.some((X)=>X.impl.obviatesBasisDescription))$.push(W.basis.description);if(W.refinements.length){let X=W.refinements.toSorted((Y,J)=>Y.kind==="min"&&J.kind==="max"?-1:0).map((Y)=>Y.description);$.push(...X)}if(W.inner.predicate)$.push(...W.inner.predicate.map((X)=>X.description));return $.join(" and ")},expected:(W)=>` \u25E6 ${W.errors.map(($)=>$.expected).join(`
110
+ \u25E6 `)}`,problem:(W)=>`(${W.actual}) must be...
111
+ ${W.expected}`},intersections:{intersection:(W,$,X)=>AU(W.inner,$.inner,X),...cW("intersection",(W,$,X)=>{if(W.children.length===0)return $;let{domain:Y,proto:J,...G}=W.inner,H=J??Y,Q=H?x0(H,$,X):$;return Q instanceof P?Q:W?.basis?.equals(Q)?W:W.$.node("intersection",{...G,[Q.kind]:Q},{prereduced:!0})})}});class EU extends TW{basis=this.inner.domain??this.inner.proto??null;refinements=this.children.filter((W)=>W.isRefinement());structure=this.inner.structure;expression=FL(this);get shallowMorphs(){return this.inner.structure?.structuralMorph?[this.inner.structure.structuralMorph]:[]}get defaultShortDescription(){return this.basis?.defaultShortDescription??"present"}innerToJsonSchema(W){return this.children.reduce(($,X)=>X.isBasis()?X.toJsonSchemaRecurse(W):X.reduceJsonSchema($,W),{})}traverseAllows=(W,$)=>this.children.every((X)=>X.traverseAllows(W,$));traverseApply=(W,$)=>{let X=$.currentErrorCount;if(this.basis){if(this.basis.traverseApply(W,$),$.currentErrorCount>X)return}if(this.refinements.length){for(let Y=0;Y<this.refinements.length-1;Y++)if(this.refinements[Y].traverseApply(W,$),$.failFast&&$.currentErrorCount>X)return;if(this.refinements.at(-1).traverseApply(W,$),$.currentErrorCount>X)return}if(this.structure){if(this.structure.traverseApply(W,$),$.currentErrorCount>X)return}if(this.inner.predicate){for(let Y=0;Y<this.inner.predicate.length-1;Y++)if(this.inner.predicate[Y].traverseApply(W,$),$.failFast&&$.currentErrorCount>X)return;this.inner.predicate.at(-1).traverseApply(W,$)}};compile(W){if(W.traversalKind==="Allows"){for(let $ of this.children)W.check($);W.return(!0);return}if(W.initializeErrorCount(),this.basis){if(W.check(this.basis),this.children.length>1)W.returnIfFail()}if(this.refinements.length){for(let $=0;$<this.refinements.length-1;$++)W.check(this.refinements[$]),W.returnIfFailFast();if(W.check(this.refinements.at(-1)),this.structure||this.inner.predicate)W.returnIfFail()}if(this.structure){if(W.check(this.structure),this.inner.predicate)W.returnIfFail()}if(this.inner.predicate){for(let $=0;$<this.inner.predicate.length-1;$++)W.check(this.inner.predicate[$]),W.returnIfFail();W.check(this.inner.predicate.at(-1))}}}var Q7={implementation:zL,Node:EU},FL=(W)=>{let $=W.structure?.expression||`${W.basis&&!W.refinements.some((X)=>X.impl.obviatesBasisExpression)?W.basis.nestableExpression+" ":""}${W.refinements.map((X)=>X.expression).join(" & ")}`||"unknown";if($==="Array == 0")$="[]";return $},AU=(W,$,X)=>{let Y={},J=W.proto??W.domain,G=$.proto??$.domain,H=J?G?x0(J,G,X):J:G;if(H instanceof P)return H;if(H)Y[H.kind]=H;return Z$({kind:"intersection",baseInner:Y,l:S$(W),r:S$($),roots:[],ctx:X})};var TL=Y0({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(W,$)=>$.$.parseSchema(W)},morphs:{parse:v2,serialize:(W)=>W.map(($)=>d($,"root")?$.json:c0($))},declaredIn:{child:!1,serialize:(W)=>W.json},declaredOut:{child:!1,serialize:(W)=>W.json}},normalize:(W)=>W,defaults:{description:(W)=>`a morph from ${W.in.description} to ${W.out?.description??"unknown"}`},intersections:{morph:(W,$,X)=>{if(!W.hasEqualMorphs($))return L(UL(W.expression,$.expression));let Y=x0(W.in,$.in,X);if(Y instanceof P)return Y;let J={morphs:W.morphs};if(W.declaredIn||$.declaredIn){let G=x0(W.in,$.in,X);if(G instanceof P)return G.throw();else J.declaredIn=G}if(W.declaredOut||$.declaredOut){let G=x0(W.out,$.out,X);if(G instanceof P)return G.throw();else J.declaredOut=G}return Y.distribute((G)=>X.$.node("morph",{...J,in:G}),X.$.parseSchema)},...cW("morph",(W,$,X)=>{let Y=W.inner.in?x0(W.inner.in,$,X):$;return Y instanceof P?Y:Y.equals(W.inner.in)?W:X.$.node("morph",{...W.inner,in:Y})})}});class NU extends TW{serializedMorphs=this.morphs.map(c0);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs.at(-1);lastMorphIfNode=d(this.lastMorph,"root")?this.lastMorph:void 0;introspectableIn=this.inner.in;introspectableOut=this.lastMorphIfNode?Object.assign(this.referencesById,this.lastMorphIfNode.referencesById)&&this.lastMorphIfNode.out:void 0;get shallowMorphs(){return Array.isArray(this.inner.in?.shallowMorphs)?[...this.inner.in.shallowMorphs,...this.morphs]:this.morphs}get in(){return this.declaredIn??this.inner.in?.in??R.intrinsic.unknown.internal}get out(){return this.declaredOut??this.introspectableOut??R.intrinsic.unknown.internal}declareIn(W){return this.$.node("morph",{...this.inner,declaredIn:W})}declareOut(W){return this.$.node("morph",{...this.inner,declaredOut:W})}expression=`(In: ${this.in.expression}) => ${this.lastMorphIfNode?"To":"Out"}<${this.out.expression}>`;get defaultShortDescription(){return this.in.meta.description??this.in.defaultShortDescription}innerToJsonSchema(W){return W.fallback.morph({code:"morph",base:this.in.toJsonSchemaRecurse(W),out:this.introspectableOut?.toJsonSchemaRecurse(W)??null})}compile(W){if(W.traversalKind==="Allows"){if(!this.introspectableIn)return;W.return(W.invoke(this.introspectableIn));return}if(this.introspectableIn)W.line(W.invoke(this.introspectableIn));W.line(`ctx.queueMorphs(${this.compiledMorphs})`)}traverseAllows=(W,$)=>!this.introspectableIn||this.introspectableIn.traverseAllows(W,$);traverseApply=(W,$)=>{if(this.introspectableIn)this.introspectableIn.traverseApply(W,$);$.queueMorphs(this.morphs)};hasEqualMorphs(W){return Q2(this.morphs,W.morphs,{isEqual:($,X)=>$===X||d($,"root")&&d(X,"root")&&$.equals(X)})}}var z7={implementation:TL,Node:NU},UL=(W,$)=>`The intersection of distinct morphs at a single path is indeterminate:
112
+ Left: ${W}
113
+ Right: ${$}`;var wL=Y0({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(W)=>B6(W)??zW(W)},dateAllowsInvalid:{}},normalize:(W)=>{let $=typeof W==="string"?{proto:N8[W]}:typeof W==="function"?P0(W)?W:{proto:W}:typeof W.proto==="string"?{...W,proto:N8[W.proto]}:W;if(typeof $.proto!=="function")L(u6.writeInvalidSchemaMessage($.proto));if(K$($,"dateAllowsInvalid")&&$.proto!==Date)L(u6.writeBadInvalidDateMessage($.proto));return $},applyConfig:(W,$)=>{if(W.dateAllowsInvalid===void 0&&W.proto===Date&&$.dateAllowsInvalid)return{...W,dateAllowsInvalid:!0};return W},defaults:{description:(W)=>W.builtinName?OT[W.builtinName]:`an instance of ${W.proto.name}`,actual:(W)=>W instanceof Date&&W.toString()==="Invalid Date"?"an invalid Date":N6(W)},intersections:{proto:(W,$)=>W.proto===Date&&$.proto===Date?W.dateAllowsInvalid?$:W:j5(W.proto,$.proto)?W:j5($.proto,W.proto)?$:P.init("proto",W,$),domain:(W,$)=>$.domain==="object"?W:P.init("domain",R.intrinsic.object.internal,$)}});class BU extends Z8{builtinName=B6(this.proto);serializedConstructor=this.json.proto;requiresInvalidDateCheck=this.proto===Date&&!this.dateAllowsInvalid;traverseAllows=this.requiresInvalidDateCheck?(W)=>W instanceof Date&&W.toString()!=="Invalid Date":(W)=>W instanceof this.proto;compiledCondition=`data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck?' && data.toString() !== "Invalid Date"':""}`;compiledNegation=`!(${this.compiledCondition})`;innerToJsonSchema(W){switch(this.builtinName){case"Array":return{type:"array"};case"Date":return W.fallback.date?.({code:"date",base:{}})??W.fallback.proto({code:"proto",base:{},proto:this.proto});default:return W.fallback.proto({code:"proto",base:{},proto:this.proto})}}expression=this.dateAllowsInvalid?"Date | InvalidDate":this.proto.name;get nestableExpression(){return this.dateAllowsInvalid?`(${this.expression})`:this.expression}domain="object";get defaultShortDescription(){return this.description}}var u6={implementation:wL,Node:BU,writeBadInvalidDateMessage:(W)=>`dateAllowsInvalid may only be specified with constructor Date (was ${W.name})`,writeInvalidSchemaMessage:(W)=>`instanceOf operand must be a function (was ${Q1(W)})`};var ML=Y0({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(W,$)=>{let X=[];for(let Y of W){let J=d(Y,"root")?Y.branches:$.$.parseSchema(Y).branches;for(let G of J)if(G.hasKind("morph")){let H=X.findIndex((Q)=>Q.hasKind("morph")&&Q.hasEqualMorphs(G));if(H===-1)X.push(G);else{let Q=X[H];X[H]=$.$.node("morph",{...Q.inner,in:Q.in.rawOr(G.in)})}}else X.push(G)}if(!$.def.ordered)X.sort((Y,J)=>Y.hash<J.hash?-1:1);return X}}},normalize:(W)=>C0(W)?{branches:W}:W,reduce:(W,$)=>{let X=BL(W);if(X.length===1)return X[0];if(X.length===W.branches.length)return;return $.node("union",{...W,branches:X},{prereduced:!0})},defaults:{description:(W)=>W.distribute(($)=>$.description,I$),expected:(W)=>{let $=FT(W.errors,"propString"),X=Object.entries($).map(([Y,J])=>{let G=[];for(let z of J)pW(G,z.expected);let H=I$(G),Q=J.every((z)=>z.actual===J[0].actual)?J[0].actual:X0(J[0].data);return`${Y&&`${Y} `}must be ${H}${Q&&` (was ${Q})`}`});return I$(X)},problem:(W)=>W.expected,message:(W)=>W.problem},intersections:{union:(W,$,X)=>{if(W.isNever!==$.isNever)return P.init("presence",W,$);let Y;if(W.ordered){if($.ordered)L(ZL(W.expression,$.expression));if(Y=F7($.branches,W.branches,X),Y instanceof P)Y.invert()}else Y=F7(W.branches,$.branches,X);if(Y instanceof P)return Y;return X.$.parseSchema(W.ordered||$.ordered?{branches:Y,ordered:!0}:{branches:Y})},...cW("union",(W,$,X)=>{let Y=F7(W.branches,[$],X);if(Y instanceof P)return Y;if(Y.length===1)return Y[0];return X.$.parseSchema(W.ordered?{branches:Y,ordered:!0}:{branches:Y})})}});class SU extends TW{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){let W=[],$=-1;for(let X of this.branches){if(X.hasKind("unit")&&X.domain==="boolean"){if($===-1)$=W.length,W.push(X);else W[$]=R.intrinsic.boolean;continue}W.push(X)}return W}unitBranches=this.branches.filter((W)=>W.in.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?AL(this.discriminant):null;expression=this.distribute((W)=>W.nestableExpression,NL);createBranchedOptimisticRootApply(){return(W,$)=>{let X=this.traverseOptimistic(W);if(X!==e1)return X;let Y=new ZW(W,this.$.resolvedConfig);return this.traverseApply(W,Y),Y.finalize($)}}get shallowMorphs(){return this.branches.reduce((W,$)=>pW(W,$.shallowMorphs),[])}get defaultShortDescription(){return this.distribute((W)=>W.defaultShortDescription,I$)}innerToJsonSchema(W){if(this.branchGroups.length===1&&this.branchGroups[0].equals(R.intrinsic.boolean))return{type:"boolean"};let $=this.branchGroups.map((X)=>X.toJsonSchemaRecurse(W));if($.every((X)=>Object.keys(X).length===1&&K$(X,"const")))return{enum:$.map((X)=>X.const)};return{anyOf:$}}traverseAllows=(W,$)=>this.branches.some((X)=>X.traverseAllows(W,$));traverseApply=(W,$)=>{let X=[];for(let Y=0;Y<this.branches.length;Y++){if($.pushBranch(),this.branches[Y].traverseApply(W,$),!$.hasError()){if(this.branches[Y].includesTransform)return $.queuedMorphs.push(...$.popBranch().queuedMorphs);return $.popBranch()}X.push($.popBranch().error)}$.errorFromNodeContext({code:"union",errors:X,meta:this.meta})};traverseOptimistic=(W)=>{for(let $=0;$<this.branches.length;$++){let X=this.branches[$];if(X.traverseAllows(W)){if(X.contextFreeMorph)return X.contextFreeMorph(W);return W}}return e1};compile(W){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(W);let $=this.discriminant.optionallyChainedPropString;if(this.discriminant.kind==="domain")$=`typeof ${$} === "object" ? ${$} === null ? "null" : "object" : typeof ${$} === "function" ? "object" : typeof ${$}`;let X=this.discriminant.cases,Y=Object.keys(X),{optimistic:J}=W;if(W.optimistic=!1,W.block(`switch(${$})`,()=>{for(let F in X){let T=X[F],U=F==="default"?F:`case ${F}`;W.line(`${U}: return ${T===!0?J?W.data:T:J?`${W.invoke(T)} ? ${T.contextFreeMorph?`${c0(T.contextFreeMorph)}(${W.data})`:W.data} : "${e1}"`:W.invoke(T)}`)}return W}),W.traversalKind==="Allows"){W.return(J?`"${e1}"`:!1);return}let G=I$(this.discriminant.kind==="domain"?Y.map((F)=>{let T=F.slice(1,-1);return T==="function"?m1.object:m1[T]}):Y),H=this.discriminant.path.map((F)=>typeof F==="symbol"?c0(F):JSON.stringify(F)),Q=JSON.stringify(G),z=this.discriminant.kind==="domain"?`${KL}[${$}]`:`${LL}(${$})`;W.line(`ctx.errorFromNodeContext({
125
114
  code: "predicate",
126
- expected: ${G},
127
- actual: ${H},
128
- relativePath: [${Y}],
115
+ expected: ${Q},
116
+ actual: ${z},
117
+ relativePath: [${H}],
129
118
  meta: ${this.compiledMeta}
130
- })`)}compileIndiscriminable(T){if(T.traversalKind==="Apply"){T.const("errors","[]");for(let $ of this.branches)T.line("ctx.pushBranch()").line(T.invoke($)).if("!ctx.hasError()",()=>T.return($.includesTransform?"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)":"ctx.popBranch()")).line("errors.push(ctx.popBranch().error)");T.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`)}else{let{optimistic:$}=T;T.optimistic=!1;for(let J of this.branches)T.if(`${T.invoke(J)}`,()=>T.return($?J.contextFreeMorph?`${sT(J.contextFreeMorph)}(${T.data})`:T.data:!0));T.return($?`"${QJ}"`:!1)}}get nestableExpression(){return this.isBoolean?"boolean":`(${this.expression})`}discriminate(){if(this.branches.length<2||this.isCyclic)return null;if(this.unitBranches.length===this.branches.length){let X=YT(this.unitBranches,(F,Y)=>[`${Y.in.serializedValue}`,Y.hasKind("morph")?Y:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:X}}let T=[];for(let X=0;X<this.branches.length-1;X++){let F=this.branches[X];for(let Y=X+1;Y<this.branches.length;Y++){let G=this.branches[Y],H=WJ(F.in,G.in,F.$);if(!(H instanceof v))continue;for(let M of H){if(!M.kind||M.optional)continue;let z,A;if(M.kind==="domain"){let{l:_,r:D}=M;z=`"${typeof _==="string"?_:_.domain}"`,A=`"${typeof D==="string"?D:D.domain}"`}else if(M.kind==="unit")z=M.l.serializedValue,A=M.r.serializedValue;else continue;let w=T.find((_)=>B1(_.path,M.path)&&_.kind===M.kind);if(!w)T.push({kind:M.kind,cases:{[z]:{branchIndices:[X],condition:M.l},[A]:{branchIndices:[Y],condition:M.r}},path:M.path});else{if(w.cases[z])w.cases[z].branchIndices=eJ(w.cases[z].branchIndices,X);else w.cases[z]??={branchIndices:[X],condition:M.l};if(w.cases[A])w.cases[A].branchIndices=eJ(w.cases[A].branchIndices,Y);else w.cases[A]??={branchIndices:[Y],condition:M.r}}}}}let $=this.ordered?iV(T,this.branches):T;if(!$.length)return null;let J=lV($,this),W={};for(let X in J.best.cases){let F=nV(J,X);if(F===null){W[X]=!0;continue}if(F.length===this.branches.length)return null;if(this.ordered)F.sort((H,M)=>H.originalIndex-M.originalIndex);let Y=F.map((H)=>H.branch),G=Y.length===1?Y[0]:this.$.node("union",this.ordered?{branches:Y,ordered:!0}:Y);Object.assign(this.referencesById,G.referencesById),W[X]=G}if(J.defaultEntries.length){let X=J.defaultEntries.map((F)=>F.branch);W.default=this.$.node("union",this.ordered?{branches:X,ordered:!0}:X,{prereduced:!0}),Object.assign(this.referencesById,W.default.referencesById)}return Object.assign(J.location,{cases:W})}}var lV=(T,$)=>{let J=T.sort((F,Y)=>Object.keys(Y.cases).length-Object.keys(F.cases).length)[0],W={kind:J.kind,path:J.path,optionallyChainedPropString:$Q(J.path)},X=$.branches.map((F,Y)=>({originalIndex:Y,branch:F}));return{best:J,location:W,defaultEntries:X,node:$}},nV=(T,$)=>{let J=T.best.cases[$],W=tV(J.condition,T.location.path,T.node.$),X=[],F=[];for(let Y=0;Y<T.defaultEntries.length;Y++){let G=T.defaultEntries[Y];if(J.branchIndices.includes(G.originalIndex)){let H=sw(T.node.branches[G.originalIndex],T.location);if(H===null)X=null;else X?.push({originalIndex:G.originalIndex,branch:H})}else if(G.branch.hasKind("alias")&&W.hasKind("domain")&&W.domain==="object")X?.push(G);else{if(G.branch.in.overlaps(W)){let H=sw(G.branch,T.location);X?.push({originalIndex:G.originalIndex,branch:H})}F.push(G)}}return T.defaultEntries=F,X},iV=(T,$)=>{return T.filter((W)=>{let X=Object.values(W.cases).map((F)=>F.branchIndices);for(let F=0;F<X.length-1;F++){let Y=X[F];for(let G=F+1;G<X.length;G++){let H=X[G];for(let M of Y)for(let z of H)if(M>z){if($[M].overlaps($[z]))return!1}}}return!0})},tV=(T,$,J)=>{let W=T==="undefined"?J.node("unit",{unit:void 0}):T==="null"?J.node("unit",{unit:null}):T==="boolean"?J.units([!0,!1]):T;for(let X=$.length-1;X>=0;X--){let F=$[X];W=J.node("intersection",typeof F==="number"?{proto:"Array",sequence:[...PA(F).map((Y)=>({})),W]}:{domain:"object",required:[{key:F,value:W}]})}return W},$Q=(T)=>T.reduce(($,J)=>$+m9(J,!0),"data"),rV=sT(hA),aV=sT(GT),A5={implementation:dV,Node:TQ},sV=(T)=>({kind:T.kind,path:T.path.map(($)=>typeof $==="string"?$:C1($)),cases:YT(T.cases,($,J)=>[$,J===!0?J:J.hasKind("union")&&J.discriminantJson?J.discriminantJson:J.json])}),eV={delimiter:" | ",finalDelimiter:" | "},TE=(T)=>XX(T,eV),XX=(T,$)=>{let J=$?.delimiter??", ",W=$?.finalDelimiter??" or ";if(T.length===0)return"never";if(T.length===1)return T[0];if(T.length===2&&T[0]==="false"&&T[1]==="true"||T[0]==="true"&&T[1]==="false")return"boolean";let X={},F=T.filter((G)=>X[G]?!1:X[G]=!0),Y=F.pop();return`${F.join(J)}${F.length?W:""}${Y}`},z5=(T,$,J)=>{let W=$.map(()=>[]);for(let F=0;F<T.length;F++){let Y={};for(let G=0;G<$.length;G++){if(W[G]===null)continue;if(T[F].equals($[G])){W[G]=null,Y={};break}let H=cT(T[F],$[G],J);if(H instanceof v)continue;if(H.equals(T[F])){W[G].push(T[F]),Y={};break}if(H.equals($[G]))W[G]=null;else Y[G]=H}for(let G in Y)W[G][F]=Y[G]}let X=W.flatMap((F,Y)=>F?.flatMap((G)=>G.branches)??$[Y]);return X.length===0?v.init("union",T,$):X},$E=({branches:T,ordered:$})=>{if(T.length<2)return T;let J=T.map(()=>!0);for(let W=0;W<T.length;W++)for(let X=W+1;X<T.length&&J[W]&&J[X];X++){if(T[W].equals(T[X])){J[X]=!1;continue}let F=WJ(T[W].in,T[X].in,T[0].$);if(F instanceof v)continue;if(!$)JE(T[W],T[X]);if(F.equals(T[W].in))J[W]=!!$;else if(F.equals(T[X].in))J[X]=!1}return T.filter((W,X)=>J[X])},JE=(T,$)=>{if(!T.includesTransform&&!$.includesTransform)return;if(!B1(T.shallowMorphs,$.shallowMorphs))R(ew(T.expression,$.expression));if(!B1(T.flatMorphs,$.flatMorphs,{isEqual:(J,W)=>J.propString===W.propString&&(J.node.hasKind("morph")&&W.node.hasKind("morph")?J.node.hasEqualMorphs(W.node):J.node.hasKind("intersection")&&W.node.hasKind("intersection")?J.node.structure?.structuralMorphRef===W.node.structure?.structuralMorphRef:!1)}))R(ew(T.expression,$.expression))},sw=(T,$)=>T.transform((J,W)=>{if(J==="domain"||J==="unit")return null;return W},{shouldTransform:(J,W)=>{let X=$Q(W.path);if(!$.optionallyChainedPropString.startsWith(X))return!1;if(J.hasKind("domain")&&J.domain==="object")return!0;if((J.hasKind("domain")||$.kind==="unit")&&X===$.optionallyChainedPropString)return!0;return J.children.length!==0&&J.kind!=="index"}}),ew=(T,$)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
131
- Left: ${T}
132
- Right: ${$}`,WE=(T,$)=>`The intersection of two ordered unions is indeterminate:
133
- Left: ${T}
134
- Right: ${$}`;var XE=HT({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(T)=>T instanceof Date?T.toISOString():LJ(T)}},normalize:(T)=>T,defaults:{description:(T)=>GT(T.unit),problem:({expected:T,actual:$})=>`${T===$?`must be reference equal to ${T} (serialized to the same value)`:`must be ${T} (was ${$})`}`},intersections:{unit:(T,$)=>v.init("unit",T,$),...$1("unit",(T,$)=>{if($.allows(T.unit))return T;let J=$.hasKind("intersection")?$.basis:$;if(J){let W=J.hasKind("domain")?J:k.intrinsic.object;if(T.domain!==W.domain){let X=T.domain==="undefined"||T.domain==="null"||T.domain==="boolean"?T.domain:k.intrinsic[T.domain];return v.init("domain",X,W)}}return v.init("assignability",T,$.hasKind("intersection")?$.children.find((W)=>!W.allows(T.unit)):$)})}});class WQ extends t0{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=JQ(this.unit,this.serializedValue);compiledNegation=JQ(this.unit,this.serializedValue,"negated");expression=GT(this.unit);domain=S$(this.unit);get defaultShortDescription(){return this.domain==="object"?TJ.object:this.description}innerToJsonSchema(T){return this.unit===null?{type:"null"}:k.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:T.fallback.unit({code:"unit",base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?(T)=>T instanceof Date&&T.toISOString()===this.compiledValue:Number.isNaN(this.unit)?(T)=>Number.isNaN(T):(T)=>T===this.unit}var w5={implementation:XE,Node:WQ},JQ=(T,$,J)=>{if(T instanceof Date){let W=`data instanceof Date && data.toISOString() === ${$}`;return J?`!(${W})`:W}if(Number.isNaN(T))return`${J?"!":""}Number.isNaN(data)`;return`data ${J?"!":"="}== ${$}`};var FE=HT({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(T,$)=>{let J=$.$.parseSchema(T);if(!J.extends(k.intrinsic.key))return R(GE(J.expression));let W=J.branches.filter((X)=>X.hasKind("unit"));if(W.length)return R(YE(W.map((X)=>GT(X.unit))));return J}},value:{child:!0,parse:(T,$)=>$.$.parseSchema(T)}},normalize:(T)=>T,defaults:{description:(T)=>`[${T.signature.expression}]: ${T.value.description}`},intersections:{index:(T,$,J)=>{if(T.signature.equals($.signature)){let W=cT(T.value,$.value,J),X=W instanceof v?k.intrinsic.never.internal:W;return J.$.node("index",{signature:T.signature,value:X})}if(T.signature.extends($.signature)&&T.value.subsumes($.value))return $;if($.signature.extends(T.signature)&&$.value.subsumes(T.value))return T;return null}}});class XQ extends BJ{impliedBasis=k.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=ST(this.value.flatRefs.map((T)=>gJ([this.signature,...T.path],T.node)),gJ([this.signature],this.value));traverseAllows=(T,$)=>d0(T).every((J)=>{if(this.signature.traverseAllows(J[0],$))return JJ(J[0],()=>this.value.traverseAllows(J[1],$),$);return!0});traverseApply=(T,$)=>{for(let J of d0(T))if(this.signature.traverseAllows(J[0],$))JJ(J[0],()=>this.value.traverseApply(J[1],$),$)};_transform(T,$){$.path.push(this.signature);let J=super._transform(T,$);return $.path.pop(),J}compile(){}}var Q5={implementation:FE,Node:XQ},YE=(T)=>`Index keys ${T.join(", ")} should be specified as named props.`,GE=(T)=>`Indexed key definition '${T}' must be a string or symbol`;var HE=HT({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(T,$)=>$.$.parseSchema(T)}},normalize:(T)=>T,defaults:{description:(T)=>`${T.compiledKey}: ${T.value.description}`,expected:(T)=>T.missingValueDescription,actual:()=>"missing"},intersections:{required:z8,optional:z8}});class FQ extends A8{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=W0(this.errorContext)}var O5={implementation:HE,Node:FQ};var ME=HT({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(T,$)=>{if(T.length===0)return;return T.map((J)=>$.$.parseSchema(J))}},optionals:{child:!0,parse:(T,$)=>{if(T.length===0)return;return T.map((J)=>$.$.parseSchema(J))}},defaultables:{child:(T)=>T.map(($)=>$[0]),parse:(T,$)=>{if(T.length===0)return;return T.map((J)=>{let W=$.$.parseSchema(J[0]);return Q8(W,J[1],null),[W,J[1]]})},serialize:(T)=>T.map(($)=>[$[0].collapsibleJson,LJ($[1])])},variadic:{child:!0,parse:(T,$)=>$.$.parseSchema(T,$)},minVariadicLength:{parse:(T)=>T===0?void 0:T},postfix:{child:!0,parse:(T,$)=>{if(T.length===0)return;return T.map((J)=>$.$.parseSchema(J))}}},normalize:(T)=>{if(typeof T==="string")return{variadic:T};if("variadic"in T||"prefix"in T||"defaultables"in T||"optionals"in T||"postfix"in T||"minVariadicLength"in T){if(T.postfix?.length){if(!T.variadic)return R(QE);if(T.optionals?.length||T.defaultables?.length)return R(_5)}if(T.minVariadicLength&&!T.variadic)return R("minVariadicLength may not be specified without a variadic element");return T}return{variadic:T}},reduce:(T,$)=>{let J=T.minVariadicLength??0,W=T.prefix?.slice()??[],X=T.defaultables?.slice()??[],F=T.optionals?.slice()??[],Y=T.postfix?.slice()??[];if(T.variadic){while(F.at(-1)?.equals(T.variadic))F.pop();if(F.length===0&&X.length===0)while(W.at(-1)?.equals(T.variadic))W.pop(),J++;while(Y[0]?.equals(T.variadic))Y.shift(),J++}else if(F.length===0&&X.length===0)W.push(...Y.splice(0));if(J!==T.minVariadicLength||T.prefix&&T.prefix.length!==W.length)return $.node("sequence",{...T,prefix:W,defaultables:X,optionals:F,postfix:Y,minVariadicLength:J},{prereduced:!0})},defaults:{description:(T)=>{if(T.isVariadicOnly)return`${T.variadic.nestableExpression}[]`;return`[${T.tuple.map((J)=>J.kind==="defaultables"?`${J.node.nestableExpression} = ${GT(J.default)}`:J.kind==="optionals"?`${J.node.nestableExpression}?`:J.kind==="variadic"?`...${J.node.nestableExpression}[]`:J.node.expression).join(", ")}]`}},intersections:{sequence:(T,$,J)=>{let W=D8({l:T.tuple,r:$.tuple,disjoint:new v,result:[],fixedVariants:[],ctx:J}),X=W.disjoint.length===0?[W,...W.fixedVariants]:W.fixedVariants;return X.length===0?W.disjoint:X.length===1?J.$.node("sequence",YQ(X[0].result)):J.$.node("union",X.map((F)=>({proto:Array,sequence:YQ(F.result)})))}}});class GQ extends BJ{impliedBasis=k.intrinsic.Array.internal;tuple=wE(this.inner);prefixLength=this.prefix?.length??0;defaultablesLength=this.defaultables?.length??0;optionalsLength=this.optionals?.length??0;postfixLength=this.postfix?.length??0;defaultablesAndOptionals=[];prevariadic=this.tuple.filter((T)=>{if(T.kind==="defaultables"||T.kind==="optionals")return this.defaultablesAndOptionals.push(T.node),!0;return T.kind==="prefix"});variadicOrPostfix=L1(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return c9(this.flatRefs,this.prevariadic.flatMap((T,$)=>ST(T.node.flatRefs.map((J)=>gJ([`${$}`,...J.path],J.node)),gJ([`${$}`],T.node)))),c9(this.flatRefs,this.variadicOrPostfix.flatMap((T)=>ST(T.flatRefs.map(($)=>gJ([k.intrinsic.nonNegativeIntegerString.internal,...$.path],$.node)),gJ([k.intrinsic.nonNegativeIntegerString.internal],T)))),this.flatRefs}isVariadicOnly=this.prevariadic.length+this.postfixLength===0;minVariadicLength=this.inner.minVariadicLength??0;minLength=this.prefixLength+this.minVariadicLength+this.postfixLength;minLengthNode=this.minLength===0?null:this.$.node("minLength",this.minLength);maxLength=this.variadic?null:this.tuple.length;maxLengthNode=this.maxLength===null?null:this.$.node("maxLength",this.maxLength);impliedSiblings=this.minLengthNode?this.maxLengthNode?[this.minLengthNode,this.maxLengthNode]:[this.minLengthNode]:this.maxLengthNode?[this.maxLengthNode]:[];defaultValueMorphs=AE(this);defaultValueMorphsReference=this.defaultValueMorphs.length?sT(this.defaultValueMorphs):void 0;elementAtIndex(T,$){if($<this.prevariadic.length)return this.tuple[$];let J=T.length-this.postfixLength;if($>=J)return{kind:"postfix",node:this.postfix[$-J]};return{kind:"variadic",node:this.variadic??RT(`Unexpected attempt to access index ${$} on ${this}`)}}traverseAllows=(T,$)=>{for(let J=0;J<T.length;J++)if(!this.elementAtIndex(T,J).node.traverseAllows(T[J],$))return!1;return!0};traverseApply=(T,$)=>{let J=0;for(;J<T.length;J++)JJ(J,()=>this.elementAtIndex(T,J).node.traverseApply(T[J],$),$)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(T){if(this.prefix)for(let[$,J]of this.prefix.entries())T.traverseKey(`${$}`,`data[${$}]`,J);for(let[$,J]of this.defaultablesAndOptionals.entries()){let W=`${$+this.prefixLength}`;T.if(`${W} >= ${T.data}.length`,()=>T.traversalKind==="Allows"?T.return(!0):T.return()),T.traverseKey(W,`data[${W}]`,J)}if(this.variadic){if(this.postfix)T.const("firstPostfixIndex",`${T.data}.length${this.postfix?`- ${this.postfix.length}`:""}`);if(T.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>T.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix)for(let[$,J]of this.postfix.entries()){let W=`firstPostfixIndex + ${$}`;T.traverseKey(W,`data[${W}]`,J)}}if(T.traversalKind==="Allows")T.return(!0)}_transform(T,$){$.path.push(k.intrinsic.nonNegativeIntegerString.internal);let J=super._transform(T,$);return $.path.pop(),J}expression=this.description;reduceJsonSchema(T,$){if(this.prevariadic.length)T.prefixItems=this.prevariadic.map((J)=>{let W=J.node.toJsonSchemaRecurse($);if(J.kind==="defaultables"){let X=typeof J.default==="function"?J.default():J.default;W.default=k.intrinsic.jsonData.allows(X)?X:$.fallback.defaultValue({code:"defaultValue",base:W,value:X})}return W});if(this.minLength)T.minItems=this.minLength;if(this.variadic){let J=Object.assign(T,{items:this.variadic.toJsonSchemaRecurse($)});if(this.maxLength)J.maxItems=this.maxLength;if(this.postfix){let W=this.postfix.map((X)=>X.toJsonSchemaRecurse($));T=$.fallback.arrayPostfix({code:"arrayPostfix",base:J,elements:W})}}else T.items=!1,delete T.maxItems;return T}}var zE={},AE=(T)=>{if(!T.defaultables)return[];let $=[],J="[",W=T.prefixLength+T.defaultablesLength-1;for(let X=T.prefixLength;X<=W;X++){let[F,Y]=T.defaultables[X-T.prefixLength];$.push(G5(X,F,Y)),J+=`${X}: ${F.id} = ${LJ(Y)}, `}return J+="]",zE[J]??=$},U5={implementation:ME,Node:GQ},wE=(T)=>{let $=[];if(T.prefix)for(let J of T.prefix)$.push({kind:"prefix",node:J});if(T.defaultables)for(let[J,W]of T.defaultables)$.push({kind:"defaultables",node:J,default:W});if(T.optionals)for(let J of T.optionals)$.push({kind:"optionals",node:J});if(T.variadic)$.push({kind:"variadic",node:T.variadic});if(T.postfix)for(let J of T.postfix)$.push({kind:"postfix",node:J});return $},YQ=(T)=>T.reduce(($,J)=>{if(J.kind==="variadic")$.variadic=J.node;else if(J.kind==="defaultables")$.defaultables=ST($.defaultables,[[J.node,J.default]]);else $[J.kind]=ST($[J.kind],J.node);return $},{}),_5="A postfix required element cannot follow an optional or defaultable element",QE="A postfix element requires a variadic element",D8=(T)=>{let[$,...J]=T.l,[W,...X]=T.r;if(!$||!W)return T;let F=J.at(-1)?.kind==="postfix",Y=X.at(-1)?.kind==="postfix",G=$.kind==="prefix"||W.kind==="prefix"?"prefix":$.kind==="postfix"||W.kind==="postfix"?"postfix":$.kind==="variadic"&&W.kind==="variadic"?"variadic":F||Y?"prefix":$.kind==="defaultables"||W.kind==="defaultables"?"defaultables":"optionals";if($.kind==="prefix"&&W.kind==="variadic"&&Y){let A=D8({...T,fixedVariants:[],r:X.map((w)=>({...w,kind:"prefix"}))});if(A.disjoint.length===0)T.fixedVariants.push(A)}else if(W.kind==="prefix"&&$.kind==="variadic"&&F){let A=D8({...T,fixedVariants:[],l:J.map((w)=>({...w,kind:"prefix"}))});if(A.disjoint.length===0)T.fixedVariants.push(A)}let H=cT($.node,W.node,T.ctx);if(H instanceof v)if(G==="prefix"||G==="postfix")T.disjoint.push(...H.withPrefixKey(G==="prefix"?T.result.length:`-${J.length+1}`,"required")),T.result=[...T.result,{kind:G,node:k.intrinsic.never.internal}];else if(G==="optionals"||G==="defaultables")return T;else return D8({...T,fixedVariants:[],l:J.map((A)=>({...A,kind:"prefix"})),r:J.map((A)=>({...A,kind:"prefix"}))});else if(G==="defaultables"){if($.kind==="defaultables"&&W.kind==="defaultables"&&$.default!==W.default)R(Y5($.default,W.default));T.result=[...T.result,{kind:G,node:H,default:$.kind==="defaultables"?$.default:W.kind==="defaultables"?W.default:RT(`Unexpected defaultable intersection from ${$.kind} and ${W.kind} elements.`)}]}else T.result=[...T.result,{kind:G,node:H}];let M=T.l.length,z=T.r.length;if($.kind!=="variadic"||M>=z&&(W.kind==="variadic"||z===1))T.l=J;if(W.kind!=="variadic"||z>=M&&($.kind==="variadic"||M===1))T.r=X;return D8(T)};var zQ=(T)=>($)=>{if($.props.length||$.index){let J=$.index?.map((X)=>X[T])??[];for(let X of $.props)J.push(X[T]);if($.undeclared)J.push(`+ (undeclared): ${$.undeclared}`);let W=`{ ${J.join(", ")} }`;return $.sequence?`${W} & ${$.sequence.description}`:W}return $.sequence?.description??"{}"},OE=zQ("description"),UE=zQ("expression"),HQ=(T,$,J)=>{let W=T.required?"required":"optional";if(!$.signature.allows(T.key))return null;let X=WJ(T.value,$.value,J);if(X instanceof v)return W==="optional"?J.node("optional",{key:T.key,value:k.intrinsic.never.internal}):X.withPrefixKey(T.key,T.kind);return null},_E=HT({kind:"structure",hasAssociatedError:!1,normalize:(T)=>T,applyConfig:(T,$)=>{if(!T.undeclared&&$.onUndeclaredKey!=="ignore")return{...T,undeclared:$.onUndeclaredKey};return T},keys:{required:{child:!0,parse:h$("required"),reduceIo:(T,$,J)=>{$.required=ST($.required,J.map((W)=>W[T]));return}},optional:{child:!0,parse:h$("optional"),reduceIo:(T,$,J)=>{if(T==="in"){$.optional=J.map((W)=>W.in);return}for(let W of J)$[W.outProp.kind]=ST($[W.outProp.kind],W.outProp.out)}},index:{child:!0,parse:h$("index")},sequence:{child:!0,parse:h$("sequence")},undeclared:{parse:(T)=>T==="ignore"?void 0:T,reduceIo:(T,$,J)=>{if(J!=="delete")return;if(T==="in")delete $.undeclared;else $.undeclared="reject"}}},defaults:{description:OE},intersections:{structure:(T,$,J)=>{let W={...T.inner},X={...$.inner},F=new v;if(T.undeclared){let H=T.keyof();for(let M of $.requiredKeys)if(!H.allows(M))F.add("presence",k.intrinsic.never.internal,$.propsByKey[M].value,{path:[M]});if(X.optional)X.optional=X.optional.filter((M)=>H.allows(M.key));if(X.index)X.index=X.index.flatMap((M)=>{if(M.signature.extends(H))return M;let z=WJ(H,M.signature,J.$);if(z instanceof v)return[];let A=x6(z,M.value,J.$);if(A.required)X.required=L1(X.required,A.required);if(A.optional)X.optional=L1(X.optional,A.optional);return A.index??[]})}if($.undeclared){let H=$.keyof();for(let M of T.requiredKeys)if(!H.allows(M))F.add("presence",T.propsByKey[M].value,k.intrinsic.never.internal,{path:[M]});if(W.optional)W.optional=W.optional.filter((M)=>H.allows(M.key));if(W.index)W.index=W.index.flatMap((M)=>{if(M.signature.extends(H))return M;let z=WJ(H,M.signature,J.$);if(z instanceof v)return[];let A=x6(z,M.value,J.$);if(A.required)W.required=L1(W.required,A.required);if(A.optional)W.optional=L1(W.optional,A.optional);return A.index??[]})}let Y={};if(T.undeclared||$.undeclared)Y.undeclared=T.undeclared==="reject"||$.undeclared==="reject"?"reject":"delete";let G=eW({kind:"structure",baseInner:Y,l:TX(W),r:TX(X),roots:[],ctx:J});if(G instanceof v)F.push(...G);if(F.length)return F;return G}},reduce:(T,$)=>{if(T.index){if(!(T.required||T.optional))return;let J=!1,W=T.required??[],X=T.optional??[],F=[...X];for(let Y of T.index){for(let G of W){let H=HQ(G,Y,$);if(H instanceof v)return H}for(let[G,H]of X.entries()){let M=HQ(H,Y,$);if(M instanceof v)return M;if(M===null)continue;F[G]=M,J=!0}}if(J)return $.node("structure",{...T,optional:F},{prereduced:!0})}}});class AQ extends BJ{impliedBasis=k.intrinsic.object.internal;impliedSiblings=this.children.flatMap((T)=>T.impliedSiblings??[]);props=L1(this.required,this.optional);propsByKey=YT(this.props,(T,$)=>[$.key,$]);propsByKeyReference=sT(this.propsByKey);expression=UE(this);requiredKeys=this.required?.map((T)=>T.key)??[];optionalKeys=this.optional?.map((T)=>T.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let T=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:$}of this.index)T=T.concat($.branches);return this._keyof=this.$.node("union",T)}map(T){return this.$.node("structure",this.props.flatMap(T).reduce(($,J)=>{let W=this.propsByKey[J.key];if(uT(J)){if(J.kind!=="required"&&J.kind!=="optional")return R(`Map result must have kind "required" or "optional" (was ${J.kind})`);return $[J.kind]=ST($[J.kind],J),$}let X=J.kind??W?.kind??"required",F=YT(J,(Y,G)=>(Y in w8.implementation.keys)?[Y,G]:[]);return $[X]=ST($[X],this.$.node(X,F)),$},{}))}assertHasKeys(T){let $=T.filter((J)=>!O8(J,this.keyof()));if($.length)return R(MQ(this.expression,$))}get(T,...$){let J,W=!1,X=VE(T);if((typeof X==="string"||typeof X==="symbol")&&this.propsByKey[X])J=this.propsByKey[X].value,W=this.propsByKey[X].required;if(this.index){for(let Y of this.index)if(O8(X,Y.signature))J=J?.and(Y.value)??Y.value}if(this.sequence&&O8(X,k.intrinsic.nonNegativeIntegerString))if(l(X,"root")){if(this.sequence.variadic)J=J?.and(this.sequence.element)??this.sequence.element}else{let Y=Number.parseInt(X);if(Y<this.sequence.prevariadic.length){let G=this.sequence.prevariadic[Y].node;J=J?.and(G)??G,W||=Y<this.sequence.prefixLength}else if(this.sequence.variadic){let G=this.$.node("union",this.sequence.variadicOrPostfix);J=J?.and(G)??G}}if(!J){if(this.sequence?.variadic&&l(X,"root")&&X.extends(k.intrinsic.number))return R(EE(X.expression,this.sequence.expression));return R(MQ(this.expression,[X]))}let F=J.get(...$);return W?F:F.or(k.intrinsic.undefined)}pick(...T){return this.assertHasKeys(T),this.$.node("structure",this.filterKeys("pick",T))}omit(...T){return this.assertHasKeys(T),this.$.node("structure",this.filterKeys("omit",T))}optionalize(){let{required:T,...$}=this.inner;return this.$.node("structure",{...$,optional:this.props.map((J)=>J.hasKind("required")?this.$.node("optional",J.inner):J)})}require(){let{optional:T,...$}=this.inner;return this.$.node("structure",{...$,required:this.props.map((J)=>J.hasKind("optional")?{key:J.key,value:J.value}:J)})}merge(T){let $=this.filterKeys("omit",[T.keyof()]);if(T.required)$.required=ST($.required,T.required);if(T.optional)$.optional=ST($.optional,T.optional);if(T.index)$.index=ST($.index,T.index);if(T.sequence)$.sequence=T.sequence;if(T.undeclared)$.undeclared=T.undeclared;else delete $.undeclared;return this.$.node("structure",$)}filterKeys(T,$){let J=L6(this.inner),W=(X)=>{let F=$.some((Y)=>O8(X,Y));return T==="pick"?F:!F};if(J.required)J.required=J.required.filter((X)=>W(X.key));if(J.optional)J.optional=J.optional.filter((X)=>W(X.key));if(J.index)J.index=J.index.filter((X)=>W(X.signature));return J}traverseAllows=(T,$)=>this._traverse("Allows",T,$);traverseApply=(T,$)=>this._traverse("Apply",T,$);_traverse=(T,$,J)=>{let W=J?.currentErrorCount??0;for(let X=0;X<this.props.length;X++)if(T==="Allows"){if(!this.props[X].traverseAllows($,J))return!1}else if(this.props[X].traverseApply($,J),J.failFast&&J.currentErrorCount>W)return!1;if(this.sequence){if(T==="Allows"){if(!this.sequence.traverseAllows($,J))return!1}else if(this.sequence.traverseApply($,J),J.failFast&&J.currentErrorCount>W)return!1}if(this.index||this.undeclared==="reject"){let X=Object.keys($);X.push(...Object.getOwnPropertySymbols($));for(let F=0;F<X.length;F++){let Y=X[F];if(this.index){for(let G of this.index)if(G.signature.traverseAllows(Y,J)){if(T==="Allows"){if(!JJ(Y,()=>G.value.traverseAllows($[Y],J),J))return!1}else if(JJ(Y,()=>G.value.traverseApply($[Y],J),J),J.failFast&&J.currentErrorCount>W)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(Y)){if(T==="Allows")return!1;if(J.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[Y],meta:this.meta}),J.failFast)return!1}}}if(this.structuralMorph&&J&&!J.hasError())J.queueMorphs([this.structuralMorph]);return!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter((T)=>T.hasDefault())??[])}declaresKey=(T)=>(T in this.propsByKey)||this.index?.some(($)=>$.signature.allows(T))||this.sequence!==void 0&&k.intrinsic.nonNegativeIntegerString.allows(T);_compileDeclaresKey(T){let $=[];if(this.props.length)$.push(`k in ${this.propsByKeyReference}`);if(this.index)for(let J of this.index)$.push(T.invoke(J.signature,{kind:"Allows",arg:"k"}));if(this.sequence)$.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return $.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",KE(this))}structuralMorphRef=this.structuralMorph&&sT(this.structuralMorph);compile(T){if(T.traversalKind==="Apply")T.initializeErrorCount();for(let $ of this.props)if(T.check($),T.traversalKind==="Apply")T.returnIfFailFast();if(this.sequence){if(T.check(this.sequence),T.traversalKind==="Apply")T.returnIfFailFast()}if(this.index||this.undeclared==="reject")T.const("keys","Object.keys(data)"),T.line("keys.push(...Object.getOwnPropertySymbols(data))"),T.for("i < keys.length",()=>this.compileExhaustiveEntry(T));if(T.traversalKind==="Allows")return T.return(!0);if(this.structuralMorphRef)T.if("ctx && !ctx.hasError()",()=>{return T.line("ctx.queueMorphs(["),SE(T,this),T.line("])")})}compileExhaustiveEntry(T){if(T.const("k","keys[i]"),this.index)for(let $ of this.index)T.if(`${T.invoke($.signature,{arg:"k",kind:"Allows"})}`,()=>T.traverseKey("k","data[k]",$.value));if(this.undeclared==="reject")T.if(`!(${this._compileDeclaresKey(T)})`,()=>{if(T.traversalKind==="Allows")return T.return(!1);return T.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>T.return())});return T}reduceJsonSchema(T,$){switch(T.type){case"object":return this.reduceObjectJsonSchema(T,$);case"array":let J=this.sequence?.reduceJsonSchema(T,$)??T;if(this.props.length||this.index)return $.fallback.arrayObject({code:"arrayObject",base:J,object:this.reduceObjectJsonSchema({type:"object"},$)});return J;default:return nT.throwInternalOperandError("structure",T)}}reduceObjectJsonSchema(T,$){if(this.props.length){T.properties={};for(let J of this.props){let W=J.value.toJsonSchemaRecurse($);if(typeof J.key==="symbol"){$.fallback.symbolKey({code:"symbolKey",base:T,key:J.key,value:W,optional:J.optional});continue}if(J.hasDefault()){let X=typeof J.default==="function"?J.default():J.default;W.default=k.intrinsic.jsonData.allows(X)?X:$.fallback.defaultValue({code:"defaultValue",base:W,value:X})}T.properties[J.key]=W}if(this.requiredKeys.length&&T.properties)T.required=this.requiredKeys.filter((J)=>typeof J==="string"&&(J in T.properties))}if(this.index)for(let J of this.index){let W=J.value.toJsonSchemaRecurse($);if(J.signature.equals(k.intrinsic.string)){T.additionalProperties=W;continue}for(let X of J.signature.branches){if(!X.extends(k.intrinsic.string)){T=$.fallback.symbolKey({code:"symbolKey",base:T,key:null,value:W,optional:!1});continue}let F={type:"string"};if(X.hasKind("morph"))F=$.fallback.morph({code:"morph",base:X.in.toJsonSchemaRecurse($),out:X.out.toJsonSchemaRecurse($)});if(!X.hasKind("intersection"))return RT(`Unexpected index branch kind ${X.kind}.`);let{pattern:Y}=X.inner;if(Y){let G=Object.assign(F,{pattern:Y[0].rule});for(let H=1;H<Y.length;H++)F=$.fallback.patternIntersection({code:"patternIntersection",base:G,pattern:Y[H].rule});T.patternProperties??={},T.patternProperties[G.pattern]=W}}}if(this.undeclared&&!T.additionalProperties)T.additionalProperties=!1;return T}}var D5={},DE=(T)=>{let $="";for(let J=0;J<T.defaultable.length;J++)$+=T.defaultable[J].defaultValueMorphRef;if(T.sequence?.defaultValueMorphsReference)$+=T.sequence?.defaultValueMorphsReference;if(T.undeclared==="delete"){if($+="delete !(",T.required)for(let J of T.required)$+=J.compiledKey+" | ";if(T.optional)for(let J of T.optional)$+=J.compiledKey+" | ";if(T.index)for(let J of T.index)$+=J.signature.id+" | ";if(T.sequence)if(T.sequence.maxLength===null)$+=e.nonNegativeIntegerString.id;else for(let J=0;J<T.sequence.tuple.length;J++)$+=J+" | ";$+=")"}return $},KE=(T)=>{let $=DE(T);if(!$)return;if(D5[$])return D5[$];let J=(W,X)=>{for(let F=0;F<T.defaultable.length;F++)if(!(T.defaultable[F].key in W))T.defaultable[F].defaultValueMorph(W,X);if(T.sequence?.defaultables)for(let F=W.length-T.sequence.prefixLength;F<T.sequence.defaultables.length;F++)T.sequence.defaultValueMorphs[F](W,X);if(T.undeclared==="delete"){for(let F in W)if(!T.declaresKey(F))delete W[F]}return W};return D5[$]=J},SE=(T,$)=>{let W=`(data${$.defaultable.some((X)=>X.defaultValueMorph.length===2)||$.sequence?.defaultValueMorphs.some((X)=>X.length===2)?", ctx":""})`;return T.block(`${W} => `,(X)=>{for(let F=0;F<$.defaultable.length;F++){let{serializedKey:Y,defaultValueMorphRef:G}=$.defaultable[F];X.if(`!(${Y} in data)`,(H)=>H.line(`${G}${W}`))}if($.sequence?.defaultables)X.for(`i < ${$.sequence.defaultables.length}`,(F)=>F.set("data[i]",5),`data.length - ${$.sequence.prefixLength}`);if($.undeclared==="delete")X.forIn("data",(F)=>F.if(`!(${$._compileDeclaresKey(F)})`,(Y)=>Y.line("delete data[k]")));return X.return("data")})},K5={implementation:_E,Node:AQ},VE=(T)=>{if(l(T,"root")&&T.hasKind("unit"))T=T.unit;if(typeof T==="number")T=`${T}`;return T},EE=(T,$)=>`${T} is not allowed as an array index on ${$}. Use the 'nonNegativeIntegerString' keyword instead.`,x6=(T,$,J)=>{let[W,X]=xA(T.branches,(Y)=>Y.hasKind("unit"));if(!W.length)return{index:J.node("index",{signature:T,value:$})};let F={};for(let Y of W){let G=J.node("required",{key:Y.unit,value:$});F[G.kind]=ST(F[G.kind],G)}if(X.length)F.index=J.node("index",{signature:X,value:$});return F},RE=(T)=>l(T,"root")?T.expression:GT(T),MQ=(T,$)=>`Key${$.length===1?"":"s"} ${$.map(RE).join(", ")} ${$.length===1?"does":"do"} not exist on ${T}`;var JX={...Pw,alias:U8.implementation,domain:j6.implementation,unit:w5.implementation,proto:_8.implementation,union:A5.implementation,morph:M5.implementation,intersection:H5.implementation,divisor:i9.implementation,pattern:J5.implementation,predicate:n9.implementation,required:O5.implementation,optional:w8.implementation,index:Q5.implementation,sequence:U5.implementation,structure:K5.implementation};k.defaultConfig=cA(Object.assign(YT(JX,(T,$)=>[T,$.defaults]),{jitless:tA(),clone:lA,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:nT.defaultConfig}));k.resolvedConfig=F8(k.defaultConfig,k.config);var pw={...bw,alias:U8.Node,domain:j6.Node,unit:w5.Node,proto:_8.Node,union:A5.Node,morph:M5.Node,intersection:H5.Node,divisor:i9.Node,pattern:J5.Node,predicate:n9.Node,required:O5.Node,optional:w8.Node,index:Q5.Node,sequence:U5.Node,structure:K5.Node};class FX extends Z9{get[o$](){return"module"}}var S5=(T,$)=>new FX(YT(T,(J,W)=>[J,l(W,"module")?S5(W,$):$.bindReference(W)]));var LE=(T)=>hT(T)?T:("branches"in T)&&hT(T.branches)?T.branches:void 0,BE=(T,$)=>R(`Node of kind ${$} is not valid as a ${T} definition`),wQ=(T)=>`#${T} duplicates public alias ${T}`,V5={};k.ambient??={};var QQ,UQ="function $",fE=(T)=>_Q(T,DQ(T)),_Q=(T,$)=>{let J=$.write(UQ,4),W=$.compile()();for(let X of T){if(X.precompilation)continue;if(X.traverseAllows=W[`${X.id}Allows`].bind(W),X.isRoot()&&!X.allowsRequiresContext)X.allows=X.traverseAllows;if(X.traverseApply=W[`${X.id}Apply`].bind(W),W[`${X.id}Optimistic`])X.traverseOptimistic=W[`${X.id}Optimistic`].bind(W);X.precompilation=J}},DQ=(T)=>new R6().return(T.reduce(($,J)=>{let W=new X8({kind:"Allows"}).indent();J.compile(W);let X=W.write(`${J.id}Allows`),F=new X8({kind:"Apply"}).indent();J.compile(F);let Y=F.write(`${J.id}Apply`),G=`${$}${X},
135
- ${Y},
136
- `;if(!J.hasKind("union"))return G;let H=new X8({kind:"Allows",optimistic:!0}).indent();J.compile(H);let M=H.write(`${J.id}Optimistic`);return`${G}${M},
119
+ })`)}compileIndiscriminable(W){if(W.traversalKind==="Apply"){W.const("errors","[]");for(let $ of this.branches)W.line("ctx.pushBranch()").line(W.invoke($)).if("!ctx.hasError()",()=>W.return($.includesTransform?"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)":"ctx.popBranch()")).line("errors.push(ctx.popBranch().error)");W.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`)}else{let{optimistic:$}=W;W.optimistic=!1;for(let X of this.branches)W.if(`${W.invoke(X)}`,()=>W.return($?X.contextFreeMorph?`${c0(X.contextFreeMorph)}(${W.data})`:W.data:!0));W.return($?`"${e1}"`:!1)}}get nestableExpression(){return this.isBoolean?"boolean":`(${this.expression})`}discriminate(){if(this.branches.length<2||this.isCyclic)return null;if(this.unitBranches.length===this.branches.length){let J=$0(this.unitBranches,(G,H)=>[`${H.in.serializedValue}`,H.hasKind("morph")?H:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:J}}let W=[];for(let J=0;J<this.branches.length-1;J++){let G=this.branches[J];for(let H=J+1;H<this.branches.length;H++){let Q=this.branches[H],z=c1(G.in,Q.in,G.$);if(!(z instanceof P))continue;for(let F of z){if(!F.kind||F.optional)continue;let T,U;if(F.kind==="domain"){let{l:V,r:K}=F;T=`"${typeof V==="string"?V:V.domain}"`,U=`"${typeof K==="string"?K:K.domain}"`}else if(F.kind==="unit")T=F.l.serializedValue,U=F.r.serializedValue;else continue;let M=W.find((V)=>Q2(V.path,F.path)&&V.kind===F.kind);if(!M)W.push({kind:F.kind,cases:{[T]:{branchIndices:[J],condition:F.l},[U]:{branchIndices:[H],condition:F.r}},path:F.path});else{if(M.cases[T])M.cases[T].branchIndices=pW(M.cases[T].branchIndices,J);else M.cases[T]??={branchIndices:[J],condition:F.l};if(M.cases[U])M.cases[U].branchIndices=pW(M.cases[U].branchIndices,H);else M.cases[U]??={branchIndices:[H],condition:F.r}}}}}let $=this.ordered?VL(W,this.branches):W;if(!$.length)return null;let X=_L($,this),Y={};for(let J in X.best.cases){let G=DL(X,J);if(G===null){Y[J]=!0;continue}if(G.length===this.branches.length)return null;if(this.ordered)G.sort((z,F)=>z.originalIndex-F.originalIndex);let H=G.map((z)=>z.branch),Q=H.length===1?H[0]:this.$.node("union",this.ordered?{branches:H,ordered:!0}:H);Object.assign(this.referencesById,Q.referencesById),Y[J]=Q}if(X.defaultEntries.length){let J=X.defaultEntries.map((G)=>G.branch);Y.default=this.$.node("union",this.ordered?{branches:J,ordered:!0}:J,{prereduced:!0}),Object.assign(this.referencesById,Y.default.referencesById)}return Object.assign(X.location,{cases:Y})}}var _L=(W,$)=>{let X=W.sort((G,H)=>Object.keys(H.cases).length-Object.keys(G.cases).length)[0],Y={kind:X.kind,path:X.path,optionallyChainedPropString:qU(X.path)},J=$.branches.map((G,H)=>({originalIndex:H,branch:G}));return{best:X,location:Y,defaultEntries:J,node:$}},DL=(W,$)=>{let X=W.best.cases[$],Y=OL(X.condition,W.location.path,W.node.$),J=[],G=[];for(let H=0;H<W.defaultEntries.length;H++){let Q=W.defaultEntries[H];if(X.branchIndices.includes(Q.originalIndex)){let z=RU(W.node.branches[Q.originalIndex],W.location);if(z===null)J=null;else J?.push({originalIndex:Q.originalIndex,branch:z})}else if(Q.branch.hasKind("alias")&&Y.hasKind("domain")&&Y.domain==="object")J?.push(Q);else{if(Q.branch.in.overlaps(Y)){let z=RU(Q.branch,W.location);J?.push({originalIndex:Q.originalIndex,branch:z})}G.push(Q)}}return W.defaultEntries=G,J},VL=(W,$)=>{return W.filter((Y)=>{let J=Object.values(Y.cases).map((G)=>G.branchIndices);for(let G=0;G<J.length-1;G++){let H=J[G];for(let Q=G+1;Q<J.length;Q++){let z=J[Q];for(let F of H)for(let T of z)if(F>T){if($[F].overlaps($[T]))return!1}}}return!0})},OL=(W,$,X)=>{let Y=W==="undefined"?X.node("unit",{unit:void 0}):W==="null"?X.node("unit",{unit:null}):W==="boolean"?X.units([!0,!1]):W;for(let J=$.length-1;J>=0;J--){let G=$[J];Y=X.node("intersection",typeof G==="number"?{proto:"Array",sequence:[...QT(G).map((H)=>({})),Y]}:{domain:"object",required:[{key:G,value:Y}]})}return Y},qU=(W)=>W.reduce(($,X)=>$+h5(X,!0),"data"),KL=c0(TT),LL=c0(X0),T7={implementation:ML,Node:SU},AL=(W)=>({kind:W.kind,path:W.path.map(($)=>typeof $==="string"?$:T2($)),cases:$0(W.cases,($,X)=>[$,X===!0?X:X.hasKind("union")&&X.discriminantJson?X.discriminantJson:X.json])}),EL={delimiter:" | ",finalDelimiter:" | "},NL=(W)=>I$(W,EL),I$=(W,$)=>{let X=$?.delimiter??", ",Y=$?.finalDelimiter??" or ";if(W.length===0)return"never";if(W.length===1)return W[0];if(W.length===2&&W[0]==="false"&&W[1]==="true"||W[0]==="true"&&W[1]==="false")return"boolean";let J={},G=W.filter((Q)=>J[Q]?!1:J[Q]=!0),H=G.pop();return`${G.join(X)}${G.length?Y:""}${H}`},F7=(W,$,X)=>{let Y=$.map(()=>[]);for(let G=0;G<W.length;G++){let H={};for(let Q=0;Q<$.length;Q++){if(Y[Q]===null)continue;if(W[G].equals($[Q])){Y[Q]=null,H={};break}let z=x0(W[G],$[Q],X);if(z instanceof P)continue;if(z.equals(W[G])){Y[Q].push(W[G]),H={};break}if(z.equals($[Q]))Y[Q]=null;else H[Q]=z}for(let Q in H)Y[Q][G]=H[Q]}let J=Y.flatMap((G,H)=>G?.flatMap((Q)=>Q.branches)??$[H]);return J.length===0?P.init("union",W,$):J},BL=({branches:W,ordered:$})=>{if(W.length<2)return W;let X=W.map(()=>!0);for(let Y=0;Y<W.length;Y++)for(let J=Y+1;J<W.length&&X[Y]&&X[J];J++){if(W[Y].equals(W[J])){X[J]=!1;continue}let G=c1(W[Y].in,W[J].in,W[0].$);if(G instanceof P)continue;if(!$)RL(W[Y],W[J]);if(G.equals(W[Y].in))X[Y]=!!$;else if(G.equals(W[J].in))X[J]=!1}return W.filter((Y,J)=>X[J])},RL=(W,$)=>{if(!W.includesTransform&&!$.includesTransform)return;if(!Q2(W.shallowMorphs,$.shallowMorphs))L(ZU(W.expression,$.expression));if(!Q2(W.flatMorphs,$.flatMorphs,{isEqual:(X,Y)=>X.propString===Y.propString&&(X.node.hasKind("morph")&&Y.node.hasKind("morph")?X.node.hasEqualMorphs(Y.node):X.node.hasKind("intersection")&&Y.node.hasKind("intersection")?X.node.structure?.structuralMorphRef===Y.node.structure?.structuralMorphRef:!1)}))L(ZU(W.expression,$.expression))},RU=(W,$)=>W.transform((X,Y)=>{if(X==="domain"||X==="unit")return null;return Y},{shouldTransform:(X,Y)=>{let J=qU(Y.path);if(!$.optionallyChainedPropString.startsWith(J))return!1;if(X.hasKind("domain")&&X.domain==="object")return!0;if((X.hasKind("domain")||$.kind==="unit")&&J===$.optionallyChainedPropString)return!0;return X.children.length!==0&&X.kind!=="index"}}),ZU=(W,$)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
120
+ Left: ${W}
121
+ Right: ${$}`,ZL=(W,$)=>`The intersection of two ordered unions is indeterminate:
122
+ Left: ${W}
123
+ Right: ${$}`;var SL=Y0({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(W)=>W instanceof Date?W.toISOString():zW(W)}},normalize:(W)=>W,defaults:{description:(W)=>X0(W.unit),problem:({expected:W,actual:$})=>`${W===$?`must be reference equal to ${W} (serialized to the same value)`:`must be ${W} (was ${$})`}`},intersections:{unit:(W,$)=>P.init("unit",W,$),...cW("unit",(W,$)=>{if($.allows(W.unit))return W;let X=$.hasKind("intersection")?$.basis:$;if(X){let Y=X.hasKind("domain")?X:R.intrinsic.object;if(W.domain!==Y.domain){let J=W.domain==="undefined"||W.domain==="null"||W.domain==="boolean"?W.domain:R.intrinsic[W.domain];return P.init("domain",J,Y)}}return P.init("assignability",W,$.hasKind("intersection")?$.children.find((Y)=>!Y.allows(W.unit)):$)})}});class kU extends Z8{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=CU(this.unit,this.serializedValue);compiledNegation=CU(this.unit,this.serializedValue,"negated");expression=X0(this.unit);domain=Q1(this.unit);get defaultShortDescription(){return this.domain==="object"?m1.object:this.description}innerToJsonSchema(W){return this.unit===null?{type:"null"}:R.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:W.fallback.unit({code:"unit",base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?(W)=>W instanceof Date&&W.toISOString()===this.compiledValue:Number.isNaN(this.unit)?(W)=>Number.isNaN(W):(W)=>W===this.unit}var U7={implementation:SL,Node:kU},CU=(W,$,X)=>{if(W instanceof Date){let Y=`data instanceof Date && data.toISOString() === ${$}`;return X?`!(${Y})`:Y}if(Number.isNaN(W))return`${X?"!":""}Number.isNaN(data)`;return`data ${X?"!":"="}== ${$}`};var qL=Y0({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(W,$)=>{let X=$.$.parseSchema(W);if(!X.extends(R.intrinsic.key))return L(kL(X.expression));let Y=X.branches.filter((J)=>J.hasKind("unit"));if(Y.length)return L(CL(Y.map((J)=>X0(J.unit))));return X}},value:{child:!0,parse:(W,$)=>$.$.parseSchema(W)}},normalize:(W)=>W,defaults:{description:(W)=>`[${W.signature.expression}]: ${W.value.description}`},intersections:{index:(W,$,X)=>{if(W.signature.equals($.signature)){let Y=x0(W.value,$.value,X),J=Y instanceof P?R.intrinsic.never.internal:Y;return X.$.node("index",{signature:W.signature,value:J})}if(W.signature.extends($.signature)&&W.value.subsumes($.value))return $;if($.signature.extends(W.signature)&&$.value.subsumes(W.value))return W;return null}}});class IU extends FW{impliedBasis=R.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=M0(this.value.flatRefs.map((W)=>SW([this.signature,...W.path],W.node)),SW([this.signature],this.value));traverseAllows=(W,$)=>E8(W).every((X)=>{if(this.signature.traverseAllows(X[0],$))return u1(X[0],()=>this.value.traverseAllows(X[1],$),$);return!0});traverseApply=(W,$)=>{for(let X of E8(W))if(this.signature.traverseAllows(X[0],$))u1(X[0],()=>this.value.traverseApply(X[1],$),$)};_transform(W,$){$.path.push(this.signature);let X=super._transform(W,$);return $.path.pop(),X}compile(){}}var w7={implementation:qL,Node:IU},CL=(W)=>`Index keys ${W.join(", ")} should be specified as named props.`,kL=(W)=>`Indexed key definition '${W}' must be a string or symbol`;var IL=Y0({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(W,$)=>$.$.parseSchema(W)}},normalize:(W)=>W,defaults:{description:(W)=>`${W.compiledKey}: ${W.value.description}`,expected:(W)=>W.missingValueDescription,actual:()=>"missing"},intersections:{required:b6,optional:b6}});class jU extends y6{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=g2(this.errorContext)}var M7={implementation:IL,Node:jU};var jL=Y0({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(W,$)=>{if(W.length===0)return;return W.map((X)=>$.$.parseSchema(X))}},optionals:{child:!0,parse:(W,$)=>{if(W.length===0)return;return W.map((X)=>$.$.parseSchema(X))}},defaultables:{child:(W)=>W.map(($)=>$[0]),parse:(W,$)=>{if(W.length===0)return;return W.map((X)=>{let Y=$.$.parseSchema(X[0]);return g6(Y,X[1],null),[Y,X[1]]})},serialize:(W)=>W.map(($)=>[$[0].collapsibleJson,zW($[1])])},variadic:{child:!0,parse:(W,$)=>$.$.parseSchema(W,$)},minVariadicLength:{parse:(W)=>W===0?void 0:W},postfix:{child:!0,parse:(W,$)=>{if(W.length===0)return;return W.map((X)=>$.$.parseSchema(X))}}},normalize:(W)=>{if(typeof W==="string")return{variadic:W};if("variadic"in W||"prefix"in W||"defaultables"in W||"optionals"in W||"postfix"in W||"minVariadicLength"in W){if(W.postfix?.length){if(!W.variadic)return L(vL);if(W.optionals?.length||W.defaultables?.length)return L(D7)}if(W.minVariadicLength&&!W.variadic)return L("minVariadicLength may not be specified without a variadic element");return W}return{variadic:W}},reduce:(W,$)=>{let X=W.minVariadicLength??0,Y=W.prefix?.slice()??[],J=W.defaultables?.slice()??[],G=W.optionals?.slice()??[],H=W.postfix?.slice()??[];if(W.variadic){while(G.at(-1)?.equals(W.variadic))G.pop();if(G.length===0&&J.length===0)while(Y.at(-1)?.equals(W.variadic))Y.pop(),X++;while(H[0]?.equals(W.variadic))H.shift(),X++}else if(G.length===0&&J.length===0)Y.push(...H.splice(0));if(X!==W.minVariadicLength||W.prefix&&W.prefix.length!==Y.length)return $.node("sequence",{...W,prefix:Y,defaultables:J,optionals:G,postfix:H,minVariadicLength:X},{prereduced:!0})},defaults:{description:(W)=>{if(W.isVariadicOnly)return`${W.variadic.nestableExpression}[]`;return`[${W.tuple.map((X)=>X.kind==="defaultables"?`${X.node.nestableExpression} = ${X0(X.default)}`:X.kind==="optionals"?`${X.node.nestableExpression}?`:X.kind==="variadic"?`...${X.node.nestableExpression}[]`:X.node.expression).join(", ")}]`}},intersections:{sequence:(W,$,X)=>{let Y=c6({l:W.tuple,r:$.tuple,disjoint:new P,result:[],fixedVariants:[],ctx:X}),J=Y.disjoint.length===0?[Y,...Y.fixedVariants]:Y.fixedVariants;return J.length===0?Y.disjoint:J.length===1?X.$.node("sequence",fU(J[0].result)):X.$.node("union",J.map((G)=>({proto:Array,sequence:fU(G.result)})))}}});class PU extends FW{impliedBasis=R.intrinsic.Array.internal;tuple=xL(this.inner);prefixLength=this.prefix?.length??0;defaultablesLength=this.defaultables?.length??0;optionalsLength=this.optionals?.length??0;postfixLength=this.postfix?.length??0;defaultablesAndOptionals=[];prevariadic=this.tuple.filter((W)=>{if(W.kind==="defaultables"||W.kind==="optionals")return this.defaultablesAndOptionals.push(W.node),!0;return W.kind==="prefix"});variadicOrPostfix=H2(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return u5(this.flatRefs,this.prevariadic.flatMap((W,$)=>M0(W.node.flatRefs.map((X)=>SW([`${$}`,...X.path],X.node)),SW([`${$}`],W.node)))),u5(this.flatRefs,this.variadicOrPostfix.flatMap((W)=>M0(W.flatRefs.map(($)=>SW([R.intrinsic.nonNegativeIntegerString.internal,...$.path],$.node)),SW([R.intrinsic.nonNegativeIntegerString.internal],W)))),this.flatRefs}isVariadicOnly=this.prevariadic.length+this.postfixLength===0;minVariadicLength=this.inner.minVariadicLength??0;minLength=this.prefixLength+this.minVariadicLength+this.postfixLength;minLengthNode=this.minLength===0?null:this.$.node("minLength",this.minLength);maxLength=this.variadic?null:this.tuple.length;maxLengthNode=this.maxLength===null?null:this.$.node("maxLength",this.maxLength);impliedSiblings=this.minLengthNode?this.maxLengthNode?[this.minLengthNode,this.maxLengthNode]:[this.minLengthNode]:this.maxLengthNode?[this.maxLengthNode]:[];defaultValueMorphs=PL(this);defaultValueMorphsReference=this.defaultValueMorphs.length?c0(this.defaultValueMorphs):void 0;elementAtIndex(W,$){if($<this.prevariadic.length)return this.tuple[$];let X=W.length-this.postfixLength;if($>=X)return{kind:"postfix",node:this.postfix[$-X]};return{kind:"variadic",node:this.variadic??O0(`Unexpected attempt to access index ${$} on ${this}`)}}traverseAllows=(W,$)=>{for(let X=0;X<W.length;X++)if(!this.elementAtIndex(W,X).node.traverseAllows(W[X],$))return!1;return!0};traverseApply=(W,$)=>{let X=0;for(;X<W.length;X++)u1(X,()=>this.elementAtIndex(W,X).node.traverseApply(W[X],$),$)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(W){if(this.prefix)for(let[$,X]of this.prefix.entries())W.traverseKey(`${$}`,`data[${$}]`,X);for(let[$,X]of this.defaultablesAndOptionals.entries()){let Y=`${$+this.prefixLength}`;W.if(`${Y} >= ${W.data}.length`,()=>W.traversalKind==="Allows"?W.return(!0):W.return()),W.traverseKey(Y,`data[${Y}]`,X)}if(this.variadic){if(this.postfix)W.const("firstPostfixIndex",`${W.data}.length${this.postfix?`- ${this.postfix.length}`:""}`);if(W.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>W.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix)for(let[$,X]of this.postfix.entries()){let Y=`firstPostfixIndex + ${$}`;W.traverseKey(Y,`data[${Y}]`,X)}}if(W.traversalKind==="Allows")W.return(!0)}_transform(W,$){$.path.push(R.intrinsic.nonNegativeIntegerString.internal);let X=super._transform(W,$);return $.path.pop(),X}expression=this.description;reduceJsonSchema(W,$){if(this.prevariadic.length)W.prefixItems=this.prevariadic.map((X)=>{let Y=X.node.toJsonSchemaRecurse($);if(X.kind==="defaultables"){let J=typeof X.default==="function"?X.default():X.default;Y.default=R.intrinsic.jsonData.allows(J)?J:$.fallback.defaultValue({code:"defaultValue",base:Y,value:J})}return Y});if(this.minLength)W.minItems=this.minLength;if(this.variadic){let X=Object.assign(W,{items:this.variadic.toJsonSchemaRecurse($)});if(this.maxLength)X.maxItems=this.maxLength;if(this.postfix){let Y=this.postfix.map((J)=>J.toJsonSchemaRecurse($));W=$.fallback.arrayPostfix({code:"arrayPostfix",base:X,elements:Y})}}else W.items=!1,delete W.maxItems;return W}}var fL={},PL=(W)=>{if(!W.defaultables)return[];let $=[],X="[",Y=W.prefixLength+W.defaultablesLength-1;for(let J=W.prefixLength;J<=Y;J++){let[G,H]=W.defaultables[J-W.prefixLength];$.push(H7(J,G,H)),X+=`${J}: ${G.id} = ${zW(H)}, `}return X+="]",fL[X]??=$},_7={implementation:jL,Node:PU},xL=(W)=>{let $=[];if(W.prefix)for(let X of W.prefix)$.push({kind:"prefix",node:X});if(W.defaultables)for(let[X,Y]of W.defaultables)$.push({kind:"defaultables",node:X,default:Y});if(W.optionals)for(let X of W.optionals)$.push({kind:"optionals",node:X});if(W.variadic)$.push({kind:"variadic",node:W.variadic});if(W.postfix)for(let X of W.postfix)$.push({kind:"postfix",node:X});return $},fU=(W)=>W.reduce(($,X)=>{if(X.kind==="variadic")$.variadic=X.node;else if(X.kind==="defaultables")$.defaultables=M0($.defaultables,[[X.node,X.default]]);else $[X.kind]=M0($[X.kind],X.node);return $},{}),D7="A postfix required element cannot follow an optional or defaultable element",vL="A postfix element requires a variadic element",c6=(W)=>{let[$,...X]=W.l,[Y,...J]=W.r;if(!$||!Y)return W;let G=X.at(-1)?.kind==="postfix",H=J.at(-1)?.kind==="postfix",Q=$.kind==="prefix"||Y.kind==="prefix"?"prefix":$.kind==="postfix"||Y.kind==="postfix"?"postfix":$.kind==="variadic"&&Y.kind==="variadic"?"variadic":G||H?"prefix":$.kind==="defaultables"||Y.kind==="defaultables"?"defaultables":"optionals";if($.kind==="prefix"&&Y.kind==="variadic"&&H){let U=c6({...W,fixedVariants:[],r:J.map((M)=>({...M,kind:"prefix"}))});if(U.disjoint.length===0)W.fixedVariants.push(U)}else if(Y.kind==="prefix"&&$.kind==="variadic"&&G){let U=c6({...W,fixedVariants:[],l:X.map((M)=>({...M,kind:"prefix"}))});if(U.disjoint.length===0)W.fixedVariants.push(U)}let z=x0($.node,Y.node,W.ctx);if(z instanceof P)if(Q==="prefix"||Q==="postfix")W.disjoint.push(...z.withPrefixKey(Q==="prefix"?W.result.length:`-${X.length+1}`,"required")),W.result=[...W.result,{kind:Q,node:R.intrinsic.never.internal}];else if(Q==="optionals"||Q==="defaultables")return W;else return c6({...W,fixedVariants:[],l:X.map((U)=>({...U,kind:"prefix"})),r:X.map((U)=>({...U,kind:"prefix"}))});else if(Q==="defaultables"){if($.kind==="defaultables"&&Y.kind==="defaultables"&&$.default!==Y.default)L(G7($.default,Y.default));W.result=[...W.result,{kind:Q,node:z,default:$.kind==="defaultables"?$.default:Y.kind==="defaultables"?Y.default:O0(`Unexpected defaultable intersection from ${$.kind} and ${Y.kind} elements.`)}]}else W.result=[...W.result,{kind:Q,node:z}];let F=W.l.length,T=W.r.length;if($.kind!=="variadic"||F>=T&&(Y.kind==="variadic"||T===1))W.l=X;if(Y.kind!=="variadic"||T>=F&&($.kind==="variadic"||F===1))W.r=J;return c6(W)};var bU=(W)=>($)=>{if($.props.length||$.index){let X=$.index?.map((J)=>J[W])??[];for(let J of $.props)X.push(J[W]);if($.undeclared)X.push(`+ (undeclared): ${$.undeclared}`);let Y=`{ ${X.join(", ")} }`;return $.sequence?`${Y} & ${$.sequence.description}`:Y}return $.sequence?.description??"{}"},bL=bU("description"),yL=bU("expression"),xU=(W,$,X)=>{let Y=W.required?"required":"optional";if(!$.signature.allows(W.key))return null;let J=c1(W.value,$.value,X);if(J instanceof P)return Y==="optional"?X.node("optional",{key:W.key,value:R.intrinsic.never.internal}):J.withPrefixKey(W.key,W.kind);return null},hL=Y0({kind:"structure",hasAssociatedError:!1,normalize:(W)=>W,applyConfig:(W,$)=>{if(!W.undeclared&&$.onUndeclaredKey!=="ignore")return{...W,undeclared:$.onUndeclaredKey};return W},keys:{required:{child:!0,parse:B1("required"),reduceIo:(W,$,X)=>{$.required=M0($.required,X.map((Y)=>Y[W]));return}},optional:{child:!0,parse:B1("optional"),reduceIo:(W,$,X)=>{if(W==="in"){$.optional=X.map((Y)=>Y.in);return}for(let Y of X)$[Y.outProp.kind]=M0($[Y.outProp.kind],Y.outProp.out)}},index:{child:!0,parse:B1("index")},sequence:{child:!0,parse:B1("sequence")},undeclared:{parse:(W)=>W==="ignore"?void 0:W,reduceIo:(W,$,X)=>{if(X!=="delete")return;if(W==="in")delete $.undeclared;else $.undeclared="reject"}}},defaults:{description:bL},intersections:{structure:(W,$,X)=>{let Y={...W.inner},J={...$.inner},G=new P;if(W.undeclared){let z=W.keyof();for(let F of $.requiredKeys)if(!z.allows(F))G.add("presence",R.intrinsic.never.internal,$.propsByKey[F].value,{path:[F]});if(J.optional)J.optional=J.optional.filter((F)=>z.allows(F.key));if(J.index)J.index=J.index.flatMap((F)=>{if(F.signature.extends(z))return F;let T=c1(z,F.signature,X.$);if(T instanceof P)return[];let U=aY(T,F.value,X.$);if(U.required)J.required=H2(J.required,U.required);if(U.optional)J.optional=H2(J.optional,U.optional);return U.index??[]})}if($.undeclared){let z=$.keyof();for(let F of W.requiredKeys)if(!z.allows(F))G.add("presence",W.propsByKey[F].value,R.intrinsic.never.internal,{path:[F]});if(Y.optional)Y.optional=Y.optional.filter((F)=>z.allows(F.key));if(Y.index)Y.index=Y.index.flatMap((F)=>{if(F.signature.extends(z))return F;let T=c1(z,F.signature,X.$);if(T instanceof P)return[];let U=aY(T,F.value,X.$);if(U.required)Y.required=H2(Y.required,U.required);if(U.optional)Y.optional=H2(Y.optional,U.optional);return U.index??[]})}let H={};if(W.undeclared||$.undeclared)H.undeclared=W.undeclared==="reject"||$.undeclared==="reject"?"reject":"delete";let Q=Z$({kind:"structure",baseInner:H,l:S$(Y),r:S$(J),roots:[],ctx:X});if(Q instanceof P)G.push(...Q);if(G.length)return G;return Q}},reduce:(W,$)=>{if(W.index){if(!(W.required||W.optional))return;let X=!1,Y=W.required??[],J=W.optional??[],G=[...J];for(let H of W.index){for(let Q of Y){let z=xU(Q,H,$);if(z instanceof P)return z}for(let[Q,z]of J.entries()){let F=xU(z,H,$);if(F instanceof P)return F;if(F===null)continue;G[Q]=F,X=!0}}if(X)return $.node("structure",{...W,optional:G},{prereduced:!0})}}});class yU extends FW{impliedBasis=R.intrinsic.object.internal;impliedSiblings=this.children.flatMap((W)=>W.impliedSiblings??[]);props=H2(this.required,this.optional);propsByKey=$0(this.props,(W,$)=>[$.key,$]);propsByKeyReference=c0(this.propsByKey);expression=yL(this);requiredKeys=this.required?.map((W)=>W.key)??[];optionalKeys=this.optional?.map((W)=>W.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let W=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:$}of this.index)W=W.concat($.branches);return this._keyof=this.$.node("union",W)}map(W){return this.$.node("structure",this.props.flatMap(W).reduce(($,X)=>{let Y=this.propsByKey[X.key];if(P0(X)){if(X.kind!=="required"&&X.kind!=="optional")return L(`Map result must have kind "required" or "optional" (was ${X.kind})`);return $[X.kind]=M0($[X.kind],X),$}let J=X.kind??Y?.kind??"required",G=$0(X,(H,Q)=>(H in h6.implementation.keys)?[H,Q]:[]);return $[J]=M0($[J],this.$.node(J,G)),$},{}))}assertHasKeys(W){let $=W.filter((X)=>!m6(X,this.keyof()));if($.length)return L(vU(this.expression,$))}get(W,...$){let X,Y=!1,J=uL(W);if((typeof J==="string"||typeof J==="symbol")&&this.propsByKey[J])X=this.propsByKey[J].value,Y=this.propsByKey[J].required;if(this.index){for(let H of this.index)if(m6(J,H.signature))X=X?.and(H.value)??H.value}if(this.sequence&&m6(J,R.intrinsic.nonNegativeIntegerString))if(d(J,"root")){if(this.sequence.variadic)X=X?.and(this.sequence.element)??this.sequence.element}else{let H=Number.parseInt(J);if(H<this.sequence.prevariadic.length){let Q=this.sequence.prevariadic[H].node;X=X?.and(Q)??Q,Y||=H<this.sequence.prefixLength}else if(this.sequence.variadic){let Q=this.$.node("union",this.sequence.variadicOrPostfix);X=X?.and(Q)??Q}}if(!X){if(this.sequence?.variadic&&d(J,"root")&&J.extends(R.intrinsic.number))return L(cL(J.expression,this.sequence.expression));return L(vU(this.expression,[J]))}let G=X.get(...$);return Y?G:G.or(R.intrinsic.undefined)}pick(...W){return this.assertHasKeys(W),this.$.node("structure",this.filterKeys("pick",W))}omit(...W){return this.assertHasKeys(W),this.$.node("structure",this.filterKeys("omit",W))}optionalize(){let{required:W,...$}=this.inner;return this.$.node("structure",{...$,optional:this.props.map((X)=>X.hasKind("required")?this.$.node("optional",X.inner):X)})}require(){let{optional:W,...$}=this.inner;return this.$.node("structure",{...$,required:this.props.map((X)=>X.hasKind("optional")?{key:X.key,value:X.value}:X)})}merge(W){let $=this.filterKeys("omit",[W.keyof()]);if(W.required)$.required=M0($.required,W.required);if(W.optional)$.optional=M0($.optional,W.optional);if(W.index)$.index=M0($.index,W.index);if(W.sequence)$.sequence=W.sequence;if(W.undeclared)$.undeclared=W.undeclared;else delete $.undeclared;return this.$.node("structure",$)}filterKeys(W,$){let X=mY(this.inner),Y=(J)=>{let G=$.some((H)=>m6(J,H));return W==="pick"?G:!G};if(X.required)X.required=X.required.filter((J)=>Y(J.key));if(X.optional)X.optional=X.optional.filter((J)=>Y(J.key));if(X.index)X.index=X.index.filter((J)=>Y(J.signature));return X}traverseAllows=(W,$)=>this._traverse("Allows",W,$);traverseApply=(W,$)=>this._traverse("Apply",W,$);_traverse=(W,$,X)=>{let Y=X?.currentErrorCount??0;for(let J=0;J<this.props.length;J++)if(W==="Allows"){if(!this.props[J].traverseAllows($,X))return!1}else if(this.props[J].traverseApply($,X),X.failFast&&X.currentErrorCount>Y)return!1;if(this.sequence){if(W==="Allows"){if(!this.sequence.traverseAllows($,X))return!1}else if(this.sequence.traverseApply($,X),X.failFast&&X.currentErrorCount>Y)return!1}if(this.index||this.undeclared==="reject"){let J=Object.keys($);J.push(...Object.getOwnPropertySymbols($));for(let G=0;G<J.length;G++){let H=J[G];if(this.index){for(let Q of this.index)if(Q.signature.traverseAllows(H,X)){if(W==="Allows"){if(!u1(H,()=>Q.value.traverseAllows($[H],X),X))return!1}else if(u1(H,()=>Q.value.traverseApply($[H],X),X),X.failFast&&X.currentErrorCount>Y)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(H)){if(W==="Allows")return!1;if(X.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[H],meta:this.meta}),X.failFast)return!1}}}if(this.structuralMorph&&X&&!X.hasError())X.queueMorphs([this.structuralMorph]);return!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter((W)=>W.hasDefault())??[])}declaresKey=(W)=>(W in this.propsByKey)||this.index?.some(($)=>$.signature.allows(W))||this.sequence!==void 0&&R.intrinsic.nonNegativeIntegerString.allows(W);_compileDeclaresKey(W){let $=[];if(this.props.length)$.push(`k in ${this.propsByKeyReference}`);if(this.index)for(let X of this.index)$.push(W.invoke(X.signature,{kind:"Allows",arg:"k"}));if(this.sequence)$.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return $.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",mL(this))}structuralMorphRef=this.structuralMorph&&c0(this.structuralMorph);compile(W){if(W.traversalKind==="Apply")W.initializeErrorCount();for(let $ of this.props)if(W.check($),W.traversalKind==="Apply")W.returnIfFailFast();if(this.sequence){if(W.check(this.sequence),W.traversalKind==="Apply")W.returnIfFailFast()}if(this.index||this.undeclared==="reject")W.const("keys","Object.keys(data)"),W.line("keys.push(...Object.getOwnPropertySymbols(data))"),W.for("i < keys.length",()=>this.compileExhaustiveEntry(W));if(W.traversalKind==="Allows")return W.return(!0);if(this.structuralMorphRef)W.if("ctx && !ctx.hasError()",()=>{return W.line("ctx.queueMorphs(["),pL(W,this),W.line("])")})}compileExhaustiveEntry(W){if(W.const("k","keys[i]"),this.index)for(let $ of this.index)W.if(`${W.invoke($.signature,{arg:"k",kind:"Allows"})}`,()=>W.traverseKey("k","data[k]",$.value));if(this.undeclared==="reject")W.if(`!(${this._compileDeclaresKey(W)})`,()=>{if(W.traversalKind==="Allows")return W.return(!1);return W.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>W.return())});return W}reduceJsonSchema(W,$){switch(W.type){case"object":return this.reduceObjectJsonSchema(W,$);case"array":let X=this.sequence?.reduceJsonSchema(W,$)??W;if(this.props.length||this.index)return $.fallback.arrayObject({code:"arrayObject",base:X,object:this.reduceObjectJsonSchema({type:"object"},$)});return X;default:return y0.throwInternalOperandError("structure",W)}}reduceObjectJsonSchema(W,$){if(this.props.length){W.properties={};for(let X of this.props){let Y=X.value.toJsonSchemaRecurse($);if(typeof X.key==="symbol"){$.fallback.symbolKey({code:"symbolKey",base:W,key:X.key,value:Y,optional:X.optional});continue}if(X.hasDefault()){let J=typeof X.default==="function"?X.default():X.default;Y.default=R.intrinsic.jsonData.allows(J)?J:$.fallback.defaultValue({code:"defaultValue",base:Y,value:J})}W.properties[X.key]=Y}if(this.requiredKeys.length&&W.properties)W.required=this.requiredKeys.filter((X)=>typeof X==="string"&&(X in W.properties))}if(this.index)for(let X of this.index){let Y=X.value.toJsonSchemaRecurse($);if(X.signature.equals(R.intrinsic.string)){W.additionalProperties=Y;continue}for(let J of X.signature.branches){if(!J.extends(R.intrinsic.string)){W=$.fallback.symbolKey({code:"symbolKey",base:W,key:null,value:Y,optional:!1});continue}let G={type:"string"};if(J.hasKind("morph"))G=$.fallback.morph({code:"morph",base:J.in.toJsonSchemaRecurse($),out:J.out.toJsonSchemaRecurse($)});if(!J.hasKind("intersection"))return O0(`Unexpected index branch kind ${J.kind}.`);let{pattern:H}=J.inner;if(H){let Q=Object.assign(G,{pattern:H[0].rule});for(let z=1;z<H.length;z++)G=$.fallback.patternIntersection({code:"patternIntersection",base:Q,pattern:H[z].rule});W.patternProperties??={},W.patternProperties[Q.pattern]=Y}}}if(this.undeclared&&!W.additionalProperties)W.additionalProperties=!1;return W}}var V7={},gL=(W)=>{let $="";for(let X=0;X<W.defaultable.length;X++)$+=W.defaultable[X].defaultValueMorphRef;if(W.sequence?.defaultValueMorphsReference)$+=W.sequence?.defaultValueMorphsReference;if(W.undeclared==="delete"){if($+="delete !(",W.required)for(let X of W.required)$+=X.compiledKey+" | ";if(W.optional)for(let X of W.optional)$+=X.compiledKey+" | ";if(W.index)for(let X of W.index)$+=X.signature.id+" | ";if(W.sequence)if(W.sequence.maxLength===null)$+=r.nonNegativeIntegerString.id;else for(let X=0;X<W.sequence.tuple.length;X++)$+=X+" | ";$+=")"}return $},mL=(W)=>{let $=gL(W);if(!$)return;if(V7[$])return V7[$];let X=(Y,J)=>{for(let G=0;G<W.defaultable.length;G++)if(!(W.defaultable[G].key in Y))W.defaultable[G].defaultValueMorph(Y,J);if(W.sequence?.defaultables)for(let G=Y.length-W.sequence.prefixLength;G<W.sequence.defaultables.length;G++)W.sequence.defaultValueMorphs[G](Y,J);if(W.undeclared==="delete"){for(let G in Y)if(!W.declaresKey(G))delete Y[G]}return Y};return V7[$]=X},pL=(W,$)=>{let Y=`(data${$.defaultable.some((J)=>J.defaultValueMorph.length===2)||$.sequence?.defaultValueMorphs.some((J)=>J.length===2)?", ctx":""})`;return W.block(`${Y} => `,(J)=>{for(let G=0;G<$.defaultable.length;G++){let{serializedKey:H,defaultValueMorphRef:Q}=$.defaultable[G];J.if(`!(${H} in data)`,(z)=>z.line(`${Q}${Y}`))}if($.sequence?.defaultables)J.for(`i < ${$.sequence.defaultables.length}`,(G)=>G.set("data[i]",5),`data.length - ${$.sequence.prefixLength}`);if($.undeclared==="delete")J.forIn("data",(G)=>G.if(`!(${$._compileDeclaresKey(G)})`,(H)=>H.line("delete data[k]")));return J.return("data")})},O7={implementation:hL,Node:yU},uL=(W)=>{if(d(W,"root")&&W.hasKind("unit"))W=W.unit;if(typeof W==="number")W=`${W}`;return W},cL=(W,$)=>`${W} is not allowed as an array index on ${$}. Use the 'nonNegativeIntegerString' keyword instead.`,aY=(W,$,X)=>{let[Y,J]=HT(W.branches,(H)=>H.hasKind("unit"));if(!Y.length)return{index:X.node("index",{signature:W,value:$})};let G={};for(let H of Y){let Q=X.node("required",{key:H.unit,value:$});G[Q.kind]=M0(G[Q.kind],Q)}if(J.length)G.index=X.node("index",{signature:J,value:$});return G},dL=(W)=>d(W,"root")?W.expression:X0(W),vU=(W,$)=>`Key${$.length===1?"":"s"} ${$.map(dL).join(", ")} ${$.length===1?"does":"do"} not exist on ${W}`;var C$={...QU,alias:p6.implementation,domain:tY.implementation,unit:U7.implementation,proto:u6.implementation,union:T7.implementation,morph:z7.implementation,intersection:Q7.implementation,divisor:i5.implementation,pattern:$7.implementation,predicate:o5.implementation,required:M7.implementation,optional:h6.implementation,index:w7.implementation,sequence:_7.implementation,structure:O7.implementation};R.defaultConfig=DT(Object.assign($0(C$,(W,$)=>[W,$.defaults]),{jitless:ET(),clone:KT,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:y0.defaultConfig}));R.resolvedConfig=j6(R.defaultConfig,R.config);var MU={...zU,alias:p6.Node,domain:tY.Node,unit:U7.Node,proto:u6.Node,union:T7.Node,morph:z7.Node,intersection:Q7.Node,divisor:i5.Node,pattern:$7.Node,predicate:o5.Node,required:M7.Node,optional:h6.Node,index:w7.Node,sequence:_7.Node,structure:O7.Node};class j$ extends q5{get[j1](){return"module"}}var K7=(W,$)=>new j$($0(W,(X,Y)=>[X,d(Y,"module")?K7(Y,$):$.bindReference(Y)]));var lL=(W)=>C0(W)?W:("branches"in W)&&C0(W.branches)?W.branches:void 0,oL=(W,$)=>L(`Node of kind ${$} is not valid as a ${W} definition`),hU=(W)=>`#${W} duplicates public alias ${W}`,L7={};R.ambient??={};var gU,pU="function $",iL=(W)=>uU(W,cU(W)),uU=(W,$)=>{let X=$.write(pU,4),Y=$.compile()();for(let J of W){if(J.precompilation)continue;if(J.traverseAllows=Y[`${J.id}Allows`].bind(Y),J.isRoot()&&!J.allowsRequiresContext)J.allows=J.traverseAllows;if(J.traverseApply=Y[`${J.id}Apply`].bind(Y),Y[`${J.id}Optimistic`])J.traverseOptimistic=Y[`${J.id}Optimistic`].bind(Y);J.precompilation=X}},cU=(W)=>new gY().return(W.reduce(($,X)=>{let Y=new I6({kind:"Allows"}).indent();X.compile(Y);let J=Y.write(`${X.id}Allows`),G=new I6({kind:"Apply"}).indent();X.compile(G);let H=G.write(`${X.id}Apply`),Q=`${$}${J},
124
+ ${H},
125
+ `;if(!X.hasKind("union"))return Q;let z=new I6({kind:"Allows",optimistic:!0}).indent();X.compile(z);let F=z.write(`${X.id}Optimistic`);return`${Q}${F},
137
126
  `},`{
138
- `)+"}");class P6{config;resolvedConfig;name;get[o$](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(T,$){if(this.config=F8(k.config,$),this.resolvedConfig=F8(k.resolvedConfig,$),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(V5).length}`,this.name in V5)R(`A Scope already named ${this.name} already exists`);V5[this.name]=this;let J=Object.entries(T).map((W)=>this.preparseOwnAliasEntry(...W));for(let[W,X]of J){let F=W;if(W[0]==="#"){if(F=W.slice(1),F in this.aliases)R(wQ(F));this.aliases[F]=X}else{if(F in this.aliases)R(wQ(W));this.aliases[F]=X,this.exportedNames.push(F)}if(!l(X,"module")&&!l(X,"generic")&&!T0(X)){let Y=this.preparseOwnDefinitionFormat(X,{alias:F});this.resolutions[F]=l(Y,"root")?this.bindReference(Y):this.createParseContext(Y).id}}QQ??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[QQ.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=k.intrinsic?YT(k.intrinsic,(W,X)=>W.startsWith("json")?[]:[W,this.bindReference(X)]):{}}cacheGetter(T,$){return Object.defineProperty(this,T,{value:$}),$}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema(T){return T}generic=(...T)=>{let $=this;return(J,W)=>new F0(T,W?new C6(J):J,$,$,W??null)};units=(T,$)=>{let J=[];for(let X of T)if(!J.includes(X))J.push(X);let W=J.map((X)=>this.node("unit",{unit:X},$));return this.node("union",W,{...$,prereduced:!0})};lazyResolutions=[];lazilyResolve(T,$){let J=this.node("alias",{reference:$??"synthetic",resolve:T},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(J);return J}schema=(T,$)=>this.finalize(this.parseSchema(T,$));parseSchema=(T,$)=>this.node(M8(T),T,$);preparseNode(T,$,J){let W=typeof T==="string"?T:M8($,T);if(uT($)&&$.kind===W)return $;if(W==="alias"&&!J?.prereduced){let{reference:Y}=U8.implementation.normalize($,this);if(Y.startsWith("$")){let G=this.resolveRoot(Y.slice(1));$=G,W=G.kind}}else if(W==="union"&&e$($,"object")){let Y=LE($);if(Y?.length===1)$=Y[0],W=M8($)}if(uT($)&&$.kind===W)return $;let F=JX[W].normalize?.($,this)??$;if(uT(F))return F.kind===W?F:BE(W,F.kind);return{...J,$:this,kind:W,def:F,prefix:J.alias??W}}bindReference(T){let $;if(uT(T))$=T.$===this?T:new T.constructor(T.attachments,this);else $=T.$===this?T:new F0(T.params,T.bodyDef,T.$,this,T.hkt);if(!this.resolved)Object.assign(this.referencesById,$.referencesById);return $}resolveRoot(T){return this.maybeResolveRoot(T)??R(L5(T))}maybeResolveRoot(T){let $=this.maybeResolve(T);if(l($,"generic"))return;return $}maybeResolveSubalias(T){return E5(this.aliases,T)??E5(this.ambient,T)}get ambient(){return k.ambient}maybeResolve(T){let $=this.resolutions[T];if($){if(typeof $!=="string")return this.bindReference($);let W=d$[$];if(l(W,"root"))return this.resolutions[T]=W;if(l(W,"context")){if(W.phase==="resolving")return this.node("alias",{reference:`$${T}`},{prereduced:!0});if(W.phase==="resolved")return RT(`Unexpected resolved context for was uncached by its scope: ${GT(W)}`);W.phase="resolving";let X=this.bindReference(this.parseOwnDefinitionFormat(W.def,W));return W.phase="resolved",d$[X.id]=X,d$[W.id]=X,this.resolutions[T]=X}return RT(`Unexpected nodesById entry for ${$}: ${GT(W)}`)}let J=this.aliases[T]??this.ambient?.[T];if(!J)return this.maybeResolveSubalias(T);if(J=this.normalizeRootScopeValue(J),l(J,"generic"))return this.resolutions[T]=this.bindReference(J);if(l(J,"module")){if(!J.root)R(VQ(T));return this.resolutions[T]=this.bindReference(J.root)}return this.resolutions[T]=this.parse(J,{alias:T})}createParseContext(T){let $=T.id??W5(T.prefix);return d$[$]=Object.assign(T,{[o$]:"context",$:this,id:$,phase:"unresolved"})}traversal(T){return new mJ(T,this.resolvedConfig)}import(...T){return new FX(YT(this.export(...T),($,J)=>[`#${$}`,J]))}precompilation;_exportedResolutions;_exports;export(...T){if(!this._exports){this._exports={};for(let J of this.exportedNames){let W=this.aliases[J];this._exports[J]=l(W,"module")?S5(W,this):OQ(this.maybeResolve(J))}for(let J of this.lazyResolutions)J.resolution;if(this._exportedResolutions=SQ(this,this._exports),this._json=KQ(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let J=DQ(this.references);this.precompilation=J.write(UQ,4),_Q(this.references,J)}this.resolved=!0}let $=T.length?T:this.exportedNames;return new FX(YT($,(J,W)=>[W,this._exports[W]]))}resolve(T){return this.export()[T]}node=(T,$,J={})=>{let W=this.preparseNode(T,$,J);if(uT(W))return this.bindReference(W);let X=this.createParseContext(W),F=X5(X),Y=this.bindReference(F);return d$[X.id]=Y};parse=(T,$={})=>this.finalize(this.parseDefinition(T,$));parseDefinition(T,$={}){if(l(T,"root"))return this.bindReference(T);let J=this.preparseOwnDefinitionFormat(T,$);if(l(J,"root"))return this.bindReference(J);let W=this.createParseContext(J);d$[W.id]=W;let X=this.bindReference(this.parseOwnDefinitionFormat(T,W));if(X.isCyclic)X=gw(X,W.id);return d$[W.id]=X,X}finalize(T){if(OQ(T),!T.precompilation&&!this.resolvedConfig.jitless)fE(T.references);return T}}class R5 extends P6{parseOwnDefinitionFormat(T,$){return X5($)}preparseOwnDefinitionFormat(T,$){return this.preparseNode(M8(T),T,$)}preparseOwnAliasEntry(T,$){return[T,$]}normalizeRootScopeValue(T){return T}}var OQ=(T)=>{let $=T.references.filter((J)=>J.hasKind("alias"));for(let J of $){Object.assign(J.referencesById,J.resolution.referencesById);for(let W of T.references)if(J.id in W.referencesById)Object.assign(W.referencesById,J.referencesById)}return T},KQ=(T)=>YT(T,($,J)=>[$,l(J,"root")||l(J,"generic")?J.json:l(J,"module")?KQ(J):RT(`Unexpected resolution ${GT(J)}`)]),E5=(T,$)=>{let J=$.indexOf(".");if(J===-1)return;let W=$.slice(0,J),X=T[W];if(X===void 0)return;if(!l(X,"module"))return R(NE(W));let F=$.slice(J+1),Y=X[F];if(Y===void 0)return E5(X,F);if(l(Y,"root")||l(Y,"generic"))return Y;if(l(Y,"module"))return Y.root??R(VQ($));RT(`Unexpected resolution for alias '${$}': ${GT(Y)}`)},b6=(T,$)=>new R5(T,$),K8=new R5({});var SQ=(T,$)=>{let J={};for(let W in $){let X=$[W];if(l(X,"module")){let F=SQ(T,X),Y=YT(F,(G,H)=>[`${W}.${G}`,H]);Object.assign(J,Y)}else if(l(X,"root")||l(X,"generic"))J[W]=X;else RT(`Unexpected scope resolution ${GT(X)}`)}return J},L5=(T)=>`'${T}' is unresolvable`,NE=(T)=>`'${T}' must reference a module to be accessed using dot syntax`,VQ=(T)=>`Reference to submodule '${T}' must specify an alias`;K8.export();var{schema:qT,node:YX,defineSchema:sJT,generic:NJ}=K8;var B5="^(?:0|[1-9]\\d*)$",CE=new RegExp(B5),$1T=sT(CE);var EQ=b6({bigint:"bigint",boolean:[{unit:!1},{unit:!0}],false:{unit:!1},never:[],null:{unit:null},number:"number",object:"object",string:"string",symbol:"symbol",true:{unit:!0},unknown:{},undefined:{unit:void 0},Array,Date},{prereducedAliases:!0}).export();k.intrinsic={...EQ};var RQ=b6({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:B5}},{prereducedAliases:!0}).export();Object.assign(k.intrinsic,RQ);var ZE=b6({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),e={...EQ,...RQ,...ZE,emptyStructure:YX("structure",{},{prereduced:!0})};k.intrinsic={...e};var BQ=(T)=>typeof T==="string"&&T[0]==="d"&&(T[1]==="'"||T[1]==='"')&&T.at(-1)===T[1],LQ=(T)=>T.toString()!=="Invalid Date",fQ=(T)=>T.slice(2,-1),f5=(T)=>`'${T}' could not be parsed by the Date constructor`,NQ=(T,$)=>qE(T,$),qE=(T,$)=>{let J=new Date(T);if(LQ(J))return J;let W=Xw(T);if(W!==void 0){let X=new Date(W);if(LQ(X))return X}return $?R($===!0?f5(T):$):void 0};var N5=(T,$)=>{let J=T.scanner.shiftUntil(kE[ZQ[$]]);if(T.scanner.lookahead==="")return T.error(IE(J,$));if(T.scanner.shift(),$==="/"){try{new RegExp(J)}catch(W){R(String(W))}T.root=T.ctx.$.node("intersection",{domain:"string",pattern:J},{prereduced:!0})}else if(V$($,C5))T.root=T.ctx.$.node("unit",{unit:J});else{let W=NQ(J,f5(J));T.root=T.ctx.$.node("unit",{meta:J,unit:W})}},C5={"'":1,'"':1},CQ={"/":1,"'":1,'"':1},ZQ={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},kE={"'":(T)=>T.lookahead==="'",'"':(T)=>T.lookahead==='"',"/":(T)=>T.lookahead==="/"},yE={'"':"double-quote","'":"single-quote","/":"forward slash"},IE=(T,$)=>`${$}${T} requires a closing ${yE[ZQ[$]]}`;var qQ=(T)=>`Private type references should not include '#'. Use '${T}' instead.`,v6="Optional definitions like 'string?' are only valid as properties in an object or tuple",h6="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var kQ={">":!0,">=":!0},yQ={"<":!0,"<=":!0};var GX={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},IQ=(T)=>`Unmatched )${T===""?"":` before ${T}`}`,m6=(T)=>`Missing ${T}`,jQ=(T,$)=>`Left bounds are only valid when paired with right bounds (try ...${$}${T})`,g6=(T)=>`Left-bounded expressions must specify their limits using < or <= (was ${T})`,xQ=(T,$,J,W)=>`An expression may have at most one left bound (parsed ${T}${GX[$]}, ${J}${GX[W]})`;var PQ=(T,$,J)=>bQ(T,$,J,[]),bQ=(T,$,J,W)=>{let X=J.parseUntilFinalizer();if(W.push(X.root),X.finalizer===">"){if(W.length!==$.params.length)return J.error(Z5(T,$.names,W.map((F)=>F.expression)));return W}if(X.finalizer===",")return bQ(T,$,J,W);return X.error(m6(">"))},Z5=(T,$,J)=>`${T}<${$.join(", ")}> requires exactly ${$.length} args (got ${J.length}${J.length===0?"":`: ${J.join(", ")}`})`;var q5=(T)=>{let $=T.scanner.shiftUntilNextTerminator();if($==="keyof")T.addPrefix("keyof");else T.root=xE(T,$)},jE=(T,$,J)=>{if(J.scanner.shiftUntilNonWhitespace(),J.scanner.shift()!=="<")return J.error(Z5(T,$.names,[]));let X=PQ(T,$,J);return $(...X)},xE=(T,$)=>PE(T,$)??bE(T,$)??T.error($===""?T.scanner.lookahead==="#"?qQ(T.shiftedByOne().scanner.shiftUntilNextTerminator()):k5(T):L5($)),PE=(T,$)=>{if(T.ctx.args?.[$]){let W=T.ctx.args[$];if(typeof W!=="string")return W;return T.ctx.$.node("alias",{reference:W},{prereduced:!0})}let J=T.ctx.$.maybeResolve($);if(l(J,"root"))return J;if(J===void 0)return;if(l(J,"generic"))return jE($,J,T);return R(`Unexpected resolution ${GT(J)}`)},bE=(T,$)=>{let J=Fw($);if(J!==void 0)return T.ctx.$.node("unit",{unit:J});let W=Gw($);if(W!==void 0)return T.ctx.$.node("unit",{unit:W})},k5=(T)=>{let $=T.previousOperator();return $?y5($,T.scanner.unscanned):vE(T.scanner.unscanned)},y5=(T,$="")=>`Token '${T}' requires a right operand${$?` before '${$}'`:""}`,vE=(T)=>`Expected an expression${T?` before '${T}'`:""}`;var I5=(T)=>T.scanner.lookahead===""?T.error(k5(T)):T.scanner.lookahead==="("?T.shiftedByOne().reduceGroupOpen():T.scanner.lookaheadIsIn(CQ)?N5(T,T.scanner.shift()):T.scanner.lookaheadIsIn($0)?I5(T.shiftedByOne()):T.scanner.lookahead==="d"?T.scanner.nextLookahead in C5?N5(T,`${T.scanner.shift()}${T.scanner.shift()}`):q5(T):q5(T);class q1 extends v9{shiftUntilNextTerminator(){return this.shiftUntilNonWhitespace(),this.shiftUntil(()=>(this.lookahead in q1.terminatingChars))}static terminatingChars={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...$0};static finalizingLookaheads={">":1,",":1,"":1,"=":1,"?":1};static lookaheadIsFinalizing=(T,$)=>T===">"?$[0]==="="?$[1]==="=":$.trimStart()===""||V$($.trimStart()[0],q1.terminatingChars):T==="="?$[0]!=="=":T===","||T==="?"}var hQ=(T,$)=>{let J=hE(T,$);if(T.root.hasKind("unit")){if(typeof T.root.unit==="number"){T.reduceLeftBound(T.root.unit,J),T.unsetRoot();return}if(T.root.unit instanceof Date){let W=`d'${T.root.description??T.root.unit.toISOString()}'`;T.unsetRoot(),T.reduceLeftBound(W,J);return}}return gE(T,J)},mQ={"<":1,">":1,"=":1},hE=(T,$)=>T.scanner.lookaheadIs("=")?`${$}${T.scanner.shift()}`:$;var vQ=(T,$,J,W)=>{if(J.extends(k.intrinsic.number)){if(typeof $!=="number")return R(j5(T,$,W));return T==="=="?["min","max"]:T[0]===">"?["min"]:["max"]}if(J.extends(k.intrinsic.lengthBoundable)){if(typeof $!=="number")return R(j5(T,$,W));return T==="=="?["exactLength"]:T[0]===">"?["minLength"]:["maxLength"]}if(J.extends(k.intrinsic.Date))return T==="=="?["after","before"]:T[0]===">"?["after"]:["before"];return R(Cw(J.expression))},mE=(T)=>({rule:BQ(T.limit)?fQ(T.limit):T.limit,exclusive:T.comparator.length===1}),gE=(T,$)=>{let J=T.unsetRoot(),W=T.scanner.location;T.parseOperand();let X=T.unsetRoot(),F=T.scanner.sliceChars(W,T.scanner.location);if(T.root=J,!X.hasKind("unit")||typeof X.unit!=="number"&&!(X.unit instanceof Date))return T.error(j5($,F,"right"));let Y=X.unit,G=$.length===1,H=vQ($,typeof Y==="number"?Y:F,J,"right");for(let z of H)T.constrainRoot(z,$==="=="?{rule:Y}:{rule:Y,exclusive:G});if(!T.branches.leftBound)return;if(!V$($,yQ))return T.error(g6($));let M=vQ(T.branches.leftBound.comparator,T.branches.leftBound.limit,J,"left");T.constrainRoot(M[0],mE(T.branches.leftBound)),T.branches.leftBound=null},j5=(T,$,J)=>`Comparator ${J==="left"?GX[T]:T} must be ${J==="left"?"preceded":"followed"} by a corresponding literal (was ${$})`;var gQ=(T)=>{T.scanner.shiftUntilNonWhitespace();let $=T.scanner.shiftUntilNextTerminator();T.root=T.root.brand($)};var uQ=(T)=>{let $=T.scanner.shiftUntilNextTerminator(),J=Yw($,{errorOnFail:pQ($)});if(J===0)T.error(pQ(0));T.root=T.root.constrain("divisor",J)},pQ=(T)=>`% operator must be followed by a non-zero integer literal (was ${T})`;var x5=(T)=>{let $=T.scanner.shift();return $===""?T.finalize(""):$==="["?T.scanner.shift()==="]"?T.setRoot(T.root.array()):T.error(pE):$==="|"?T.scanner.lookahead===">"?T.shiftedByOne().pushRootToBranch("|>"):T.pushRootToBranch($):$==="&"?T.pushRootToBranch($):$===")"?T.finalizeGroup():q1.lookaheadIsFinalizing($,T.scanner.unscanned)?T.finalize($):V$($,mQ)?hQ(T,$):$==="%"?uQ(T):$==="#"?gQ(T):($ in $0)?x5(T):T.error(p6($))},p6=(T,$="")=>`'${T}' is not allowed here${$&&` (should be ${$})`}`,pE="Missing expected ']'";var cQ=(T)=>{let $=T.unsetRoot();T.parseOperand();let J=T.unsetRoot();if(!J.hasKind("unit"))return T.error(uE(J.expression));let W=J.unit instanceof Date?()=>new Date(J.unit):J.unit;return[$,"=",W]},uE=(T)=>`Default value '${T}' must a literal value`;var P5=(T,$)=>{let J=$.$.maybeResolveRoot(T);if(J)return J;if(T.endsWith("[]")){let F=$.$.maybeResolveRoot(T.slice(0,-2));if(F)return F.array()}let W=new HX(new q1(T),$),X=cE(W);if(W.finalizer===">")R(p6(">"));return X},cE=(T)=>{T.parseOperand();let $=S8(T).root;if(!$)return RT(`Root was unexpectedly unset after parsing string '${T.scanner.scanned}'`);if(T.finalizer==="=")$=cQ(T);else if(T.finalizer==="?")$=[$,"?"];if(T.scanner.shiftUntilNonWhitespace(),T.scanner.lookahead)R(p6(T.scanner.lookahead));return $},S8=(T)=>{while(T.finalizer===void 0)oE(T);return T},oE=(T)=>T.hasRoot()?T.parseOperator():T.parseOperand();class HX{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(T,$){this.scanner=T,this.ctx=$}error(T){return R(T)}hasRoot(){return this.root!==void 0}setRoot(T){this.root=T}unsetRoot(){let T=this.root;return this.root=void 0,T}constrainRoot(...T){this.root=this.root.constrain(T[0],T[1])}finalize(T){if(this.groups.length)return this.error(m6(")"));this.finalizeBranches(),this.finalizer=T}reduceLeftBound(T,$){let J=GX[$];if(!V$(J,kQ))return this.error(g6($));if(this.branches.leftBound)return this.error(xQ(this.branches.leftBound.limit,this.branches.leftBound.comparator,T,J));this.branches.leftBound={comparator:J,limit:T}}finalizeBranches(){if(this.assertRangeUnset(),this.branches.pipe){this.pushRootToBranch("|>"),this.root=this.branches.pipe;return}if(this.branches.union){this.pushRootToBranch("|"),this.root=this.branches.union;return}if(this.branches.intersection){this.pushRootToBranch("&"),this.root=this.branches.intersection;return}this.applyPrefixes()}finalizeGroup(){this.finalizeBranches();let T=this.groups.pop();if(!T)return this.error(IQ(this.scanner.unscanned));this.branches=T}addPrefix(T){this.branches.prefixes.push(T)}applyPrefixes(){while(this.branches.prefixes.length){let T=this.branches.prefixes.pop();this.root=T==="keyof"?this.root.keyof():RT(`Unexpected prefix '${T}'`)}}pushRootToBranch(T){this.assertRangeUnset(),this.applyPrefixes();let $=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd($)??$,T==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,T==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return S8(new HX(this.scanner,this.ctx))}parseOperator(){return x5(this)}parseOperand(){return I5(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(jQ(this.branches.leftBound.limit,this.branches.leftBound.comparator))}reduceGroupOpen(){this.groups.push(this.branches),this.branches={prefixes:[],leftBound:null,union:null,intersection:null,pipe:null}}previousOperator(){return this.branches.leftBound?.comparator??this.branches.prefixes.at(-1)??(this.branches.intersection?"&":this.branches.union?"|":this.branches.pipe?"|>":void 0)}shiftedByOne(){return this.scanner.shift(),this}}var dE="An empty string is not a valid generic parameter name",u6=(T,$,J)=>{T.shiftUntilNonWhitespace();let W=T.shiftUntilNextTerminator();if(W===""){if(T.lookahead===""&&$.length)return $;return R(dE)}return T.shiftUntilNonWhitespace(),lE(T,W,$,J)},oQ="extends ",lE=(T,$,J,W)=>{if(T.shiftUntilNonWhitespace(),T.unscanned.startsWith(oQ))T.jumpForward(oQ.length);else{if(T.lookahead===",")T.shift();return J.push($),u6(T,J,W)}let X=S8(new HX(T,W));return J.push([$,X.root]),u6(T,J,W)};class b5 extends hJ{$;constructor(T){super((...$)=>new V8(T)(...$),{bind:T});this.$=T}in(T){return new V8(this.$,T===void 0?void 0:this.$.parse(T))}at(T,$){return new V8(this.$).at(T,$)}case(T,$){return new V8(this.$).case(T,$)}}class V8 extends hJ{$;in;key;branches=[];constructor(T,$){super((J)=>this.caseEntries(Object.entries(J).map(([W,X])=>W==="default"?[W,X]:[this.$.parse(W),X])));this.$=T,this.in=$}at(T,$){if(this.key)R(iE);if(this.branches.length)R(nE);return this.key=T,$?this.match($):this}case(T,$){return this.caseEntry(this.$.parse(T),$)}caseEntry(T,$){let W=(this.key?this.$.parse({[this.key]:T}):T).pipe($);return this.branches.push(W),this}match(T){return this(T)}strings(T){return this.caseEntries(Object.entries(T).map(([$,J])=>$==="default"?[$,J]:[this.$.node("unit",{unit:$}),J]))}caseEntries(T){for(let $=0;$<T.length;$++){let[J,W]=T[$];if(J==="default"){if($!==T.length-1)R("default may only be specified as the last key of a switch definition");return this.default(W)}if(typeof W!=="function")return R(`Value for case "${J}" must be a function (was ${S$(W)})`);this.caseEntry(J,W)}return this}default(T){if(typeof T==="function")this.case(e.unknown,T);let $={branches:this.branches,ordered:!0};if(T==="never"||T==="assert")$.meta={onFail:dQ};let J=this.$.node("union",$);if(!this.in)return this.$.finalize(J);let W=this.in.pipe(J);if(T==="never"||T==="assert")W=W.configureReferences({onFail:dQ},"self");return this.$.finalize(W)}}var dQ=(T)=>T.throw(),nE="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",iE="At most one key matcher may be specified per expression";var c6=(T,$)=>{if(hT(T)){if(T[1]==="=")return[$.$.parseOwnDefinitionFormat(T[0],$),"=",T[2]];if(T[1]==="?")return[$.$.parseOwnDefinitionFormat(T[0],$),"?"]}return o6(T,$)},lQ="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",nQ="Only required keys may specify default values, e.g. { value: 'number = 0' }";var iQ=(T,$)=>{let J,W={},X=d0(T);for(let[Y,G]of X){let H=aE(Y);if(H.kind==="spread"){if(!T1(W))return R(rE);let _=$.$.parseOwnDefinitionFormat(G,$);if(_.equals(e.object))continue;if(!_.hasKind("intersection")||!_.basis?.equals(e.object))return R(sE(_.expression));J=_.structure;continue}if(H.kind==="undeclared"){if(G!=="reject"&&G!=="delete"&&G!=="ignore")R(tE(G));W.undeclared=G;continue}let M=c6(G,$),z=H;if(H.kind==="required"){if(!hT(M))v5(W,"required",{key:H.normalized,value:M},$);else v5(W,"optional",M[1]==="="?{key:H.normalized,value:M[0],default:M[2]}:{key:H.normalized,value:M[0]},$);continue}if(hT(M)){if(M[1]==="?")R(lQ);if(M[1]==="=")R(nQ)}if(H.kind==="optional"){v5(W,"optional",{key:H.normalized,value:M},$);continue}let A=$.$.parseOwnDefinitionFormat(z.normalized,$),w=x6(A,M,$.$);if(w.index)W.index=ST(W.index,w.index);if(w.required)W.required=ST(W.required,w.required)}let F=$.$.node("structure",W);return $.$.parseSchema({domain:"object",structure:J?.merge(F)??F})},v5=(T,$,J,W)=>{T[$]=ST(T[$],W.$.node($,J))},tE=(T)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${GT(T)})`,rE="Spread operator may only be used as the first key in an object",aE=(T)=>typeof T==="symbol"?{kind:"required",normalized:T}:T.at(-1)==="?"?T.at(-2)===s2?{kind:"required",normalized:`${T.slice(0,-2)}?`}:{kind:"optional",normalized:T.slice(0,-1)}:T[0]==="["&&T.at(-1)==="]"?{kind:"index",normalized:T.slice(1,-1)}:T[0]===s2&&T[1]==="["&&T.at(-1)==="]"?{kind:"required",normalized:T.slice(1)}:T==="..."?{kind:"spread"}:T==="+"?{kind:"undeclared"}:{kind:"required",normalized:T==="\\..."?"...":T==="\\+"?"+":T},sE=(T)=>`Spread operand must resolve to an object literal type (was ${T})`;var rQ=(T,$)=>HR(T)?TO[T[0]](T,$):YR(T)?eQ[T[1]](T,$):null,eE=(T,$)=>$.$.parseOwnDefinitionFormat(T[1],$).keyof(),h5=(T,$)=>{if(T[2]===void 0)return R(y5(T[1],""));let J=$.$.parseOwnDefinitionFormat(T[0],$),W=$.$.parseOwnDefinitionFormat(T[2],$);if(T[1]==="|")return $.$.node("union",{branches:[J,W]});let X=T[1]==="&"?WJ(J,W,$.$):H8(J,W,$.$);if(X instanceof v)return X.throw();return X},TR=(T,$)=>$.$.parseOwnDefinitionFormat(T[0],$).array(),$R=(T,$)=>{if(typeof T[2]!=="function")return R(aQ("=>",T[2]));return $.$.parseOwnDefinitionFormat(T[0],$).pipe(T[2])},aQ=(T,$)=>`${T===":"?"Narrow":"Morph"} expression requires a function following '${T}' (was ${typeof $})`,JR=(T,$)=>{if(typeof T[2]!=="function")return R(aQ(":",T[2]));return $.$.parseOwnDefinitionFormat(T[0],$).constrain("predicate",T[2])},WR=(T,$)=>$.$.parseOwnDefinitionFormat(T[0],$).configureReferences(T[2],"shallow"),sQ=(T)=>T,XR=sQ({"[]":TR,"?":()=>R(v6)}),FR=sQ({"|":h5,"&":h5,":":JR,"=>":$R,"|>":h5,"@":WR,"=":()=>R(h6)}),eQ={...XR,...FR},YR=(T)=>eQ[T[1]]!==void 0,GR=(T)=>T,TO=GR({keyof:eE,instanceof:(T,$)=>{if(typeof T[1]!=="function")return R(tQ(r2(T[1])));let J=T.slice(1).map((W)=>typeof W==="function"?$.$.node("proto",{proto:W}):R(tQ(r2(W))));return J.length===1?J[0]:$.$.node("union",{branches:J})},"===":(T,$)=>$.$.units(T.slice(1))}),HR=(T)=>TO[T[0]]!==void 0,tQ=(T)=>`Expected a constructor following 'instanceof' operator (was ${T})`;var WO=(T,$)=>{let J=[{}],W=0;while(W<T.length){let X=!1;if(T[W]==="..."&&W<T.length-1)X=!0,W++;let F=c6(T[W],$),[Y,G,H]=!hT(F)?[F]:F;if(W++,X){if(!Y.extends(k.intrinsic.Array))return R(AR(Y.expression));J=J.flatMap((M)=>Y.distribute((z)=>zR(L6(M),z)))}else J=J.map((M)=>{if(G==="?")return XO(M,Y);if(G==="=")return MR(M,Y,H);return m5(M,Y)})}return $.$.parseSchema(J.map((X)=>T1(X)?{proto:Array,exactLength:0}:{proto:Array,sequence:X}))},m5=(T,$)=>{if(T.defaultables||T.optionals)return R(T.variadic?_5:wR);if(T.variadic)T.postfix=ST(T.postfix,$);else T.prefix=ST(T.prefix,$);return T},XO=(T,$)=>{if(T.variadic)return R(FO);return T.optionals=ST(T.optionals,$),T},MR=(T,$,J)=>{if(T.variadic)return R(FO);if(T.optionals)return R(QR);return T.defaultables=ST(T.defaultables,[[$,J]]),T},$O=(T,$)=>{if(T.postfix)R(JO);if(T.variadic){if(!T.variadic.equals($))R(JO)}else T.variadic=$.internal;return T},zR=(T,$)=>{let J=$.select({method:"find",kind:"sequence"});if(!J)return $O(T,k.intrinsic.unknown);if(J.prefix)for(let W of J.prefix)m5(T,W);if(J.optionals)for(let W of J.optionals)XO(T,W);if(J.variadic)$O(T,J.variadic);if(J.postfix)for(let W of J.postfix)m5(T,W);return T},AR=(T)=>`Spread element must be an array (was ${T})`,JO="A tuple may have at most one variadic element",wR="A required element may not follow an optional element",FO="An optional element may not follow a variadic element";var QR="A defaultable element may not follow an optional element without a default";var OR={},o6=(T,$)=>{if(typeof T==="string"){if($.args&&Object.keys($.args).some((W)=>T.includes(W)))return P5(T,$);let J=OR[$.$.name]??={};return J[T]??=P5(T,$)}return e$(T,"object")?UR(T,$):R(g5(S$(T)))},UR=(T,$)=>{let J=t2(T);switch(J){case void 0:if(l(T,"root"))return T;return iQ(T,$);case"Array":return _R(T,$);case"RegExp":return $.$.node("intersection",{domain:"string",pattern:T},{prereduced:!0});case"Function":{let W=T0(T)?T():T;if(l(W,"root"))return W;return R(g5("Function"))}default:return R(g5(J??GT(T)))}},_R=(T,$)=>rQ(T,$)??WO(T,$),g5=(T)=>`Type definitions must be strings or objects (was ${T})`;class p5 extends hJ{constructor(T){let $=Object.assign({errors:$J,hkt:v$,$:T,raw:T.parse,module:T.constructor.module,scope:T.constructor.scope,define:T.define,match:T.match,generic:T.generic,schema:T.schema,keywords:T.ambient,unit:T.unit,enumerated:T.enumerated,instanceOf:T.instanceOf,valueOf:T.valueOf,or:T.or,and:T.and,merge:T.merge,pipe:T.pipe},T.ambientAttachments);super((...J)=>{if(J.length===1)return T.parse(J[0]);if(J.length===2&&typeof J[0]==="string"&&J[0][0]==="<"&&J[0].at(-1)===">"){let W=J[0].slice(1,-1),X=T.parseGenericParams(W,{});return new F0(X,J[1],T,T,null)}return T.parse(J)},{bind:T,attach:$})}}var MX=k;class d6 extends P6{get ambientAttachments(){if(!MX.typeAttachments)return;return this.cacheGetter("ambientAttachments",YT(MX.typeAttachments,(T,$)=>[T,this.bindReference($)]))}preparseOwnAliasEntry(T,$){let J=T.indexOf("<");if(J===-1){if(l($,"module")||l($,"generic"))return[T,$];let F=this.name==="ark"?T:T==="root"?this.name:`${this.name}.${T}`,Y=this.resolvedConfig.keywords?.[F];if(Y)$=[$,"@",Y];return[T,$]}if(T.at(-1)!==">")R("'>' must be the last character of a generic declaration in a scope");let W=T.slice(0,J),X=T.slice(J+1,-1);return[W,()=>{let F=this.parseGenericParams(X,{alias:W});return Bw(F,$,this)}]}parseGenericParams(T,$){return u6(new q1(T),[],this.createParseContext({...$,def:T,prefix:"generic"}))}normalizeRootScopeValue(T){if(T0(T)&&!l(T,"generic"))return T();return T}preparseOwnDefinitionFormat(T,$){return{...$,def:T,prefix:$.alias??"type"}}parseOwnDefinitionFormat(T,$){if(!($.alias&&($.alias in this.aliases))&&!$.args)$.args={this:$.id};let W=o6(T,$);if(hT(W)){if(W[1]==="=")return R(h6);if(W[1]==="?")return R(v6)}return W}unit=(T)=>this.units([T]);valueOf=(T)=>this.units(oA(T));enumerated=(...T)=>this.units(T);instanceOf=(T)=>this.node("proto",{proto:T},{prereduced:!0});or=(...T)=>this.schema(T.map(($)=>this.parse($)));and=(...T)=>T.reduce(($,J)=>$.and(this.parse(J)),this.intrinsic.unknown);merge=(...T)=>T.reduce(($,J)=>$.merge(this.parse(J)),this.intrinsic.object);pipe=(...T)=>this.intrinsic.unknown.pipe(...T);match=new b5(this);declare=()=>({type:this.type});define(T){return T}type=new p5(this);static scope=(T,$={})=>new d6(T,$);static module=(T,$={})=>this.scope(T,$).export()}var u5=Object.assign(d6.scope,{define:(T)=>T}),OT=d6;class YO extends v${description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var DR=NJ(["base",e.object],["props",e.object])((T)=>T.base.merge(T.props),YO),GO=OT.module({Key:e.key,Merge:DR});class HO extends v${}var KR=NJ("element")((T)=>{let $=T.element.exclude(e.Array),J=$.array();return $.rawOr(J).pipe(e1).distribute((W)=>W.assertHasKind("morph").declareOut(J),qT)},HO),MO=OT.module({root:e.Array,readonly:"root",index:e.nonNegativeIntegerString,liftFrom:KR},{name:"Array"});var c5=qT(["string",n0.FileConstructor]),SR=c5.rawOr(c5.array()),zO=qT({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:SR}}),AO=OT.module({root:["instanceof",FormData],value:c5,parsed:zO,parse:qT({in:FormData,morphs:(T)=>{let $={};for(let[J,W]of T)if(J in $){let X=$[J];if(typeof X==="string"||X instanceof n0.FileConstructor)$[J]=[X,W];else X.push(W)}else $[J]=W;return $},declaredOut:zO})},{name:"FormData"});var wO=OT.module({Int8:["instanceof",Int8Array],Uint8:["instanceof",Uint8Array],Uint8Clamped:["instanceof",Uint8ClampedArray],Int16:["instanceof",Int16Array],Uint16:["instanceof",Uint16Array],Int32:["instanceof",Int32Array],Uint32:["instanceof",Uint32Array],Float32:["instanceof",Float32Array],Float64:["instanceof",Float64Array],BigInt64:["instanceof",BigInt64Array],BigUint64:["instanceof",BigUint64Array]},{name:"TypedArray"});var VR={Boolean:1,Number:1,String:1},QO=OT.module({...YT({...q9,...y9},(T,$)=>(T in VR)?[]:[T,["instanceof",$]]),Array:MO,TypedArray:wO,FormData:AO});var ER=qT({domain:{domain:"number",meta:"a number representing a Unix timestamp"},divisor:{rule:1,meta:"an integer representing a Unix timestamp"},min:{rule:-8640000000000000,meta:"a Unix timestamp after -8640000000000000"},max:{rule:8640000000000000,meta:"a Unix timestamp before 8640000000000000"},meta:"an integer representing a safe Unix timestamp"}),RR=qT({domain:"number",divisor:1}),l6=OT.module({root:e.number,integer:RR,epoch:ER,safe:qT({domain:{domain:"number",numberAllowsNaN:!1},min:Number.MIN_SAFE_INTEGER,max:Number.MAX_SAFE_INTEGER}),NaN:["===",Number.NaN],Infinity:["===",Number.POSITIVE_INFINITY],NegativeInfinity:["===",Number.NEGATIVE_INFINITY]},{name:"number"});var iT=(T,$,J)=>{let W={domain:"string",pattern:{rule:T.source,flags:T.flags,meta:$}};if(J)W.meta={format:J};return YX("intersection",W)},OO=iT(e2,"a well-formed integer string"),NO=OT.module({root:OO,parse:qT({in:OO,morphs:(T,$)=>{let J=Number.parseInt(T);return Number.isSafeInteger(J)?J:$.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:e.integer})},{name:"string.integer"}),LR=iT(/^[\dA-Fa-f]+$/,"hex characters only"),BR=OT.module({root:iT(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:iT(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),UO=iT(/^[A-Z].*$/,"capitalized"),fR=OT.module({root:qT({in:"string",morphs:(T)=>T.charAt(0).toUpperCase()+T.slice(1),declaredOut:UO}),preformatted:UO},{name:"string.capitalize"}),NR=(T)=>{let $=T.replaceAll(/[ -]+/g,""),J=0,W,X,F=!1;for(let Y=$.length-1;Y>=0;Y--){if(W=$.substring(Y,Y+1),X=Number.parseInt(W,10),F)X*=2,J+=X>=10?X%10+1:X;else J+=X;F=!F}return!!(J%10===0?$:!1)},CR=/^(?:4\d{12}(?:\d{3,6})?|5[1-5]\d{14}|(222[1-9]|22[3-9]\d|2[3-6]\d{2}|27[01]\d|2720)\d{12}|6(?:011|5\d\d)\d{12,15}|3[47]\d{13}|3(?:0[0-5]|[68]\d)\d{11}|(?:2131|1800|35\d{3})\d{11}|6[27]\d{14}|^(81\d{14,17}))$/,ZR=qT({domain:"string",pattern:{meta:"a credit card number",rule:CR.source},predicate:{meta:"a credit card number",predicate:NR}});var qR=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))(T((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([,.]\d+(?!:))?)?(\17[0-5]\d([,.]\d+)?)?([Zz]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;var kR=(T)=>!Number.isNaN(new Date(T).valueOf()),_O=qT({domain:"string",predicate:{meta:"a parsable date",predicate:kR}}).assertHasKind("intersection"),DO=NO.root.internal.narrow((T,$)=>{let J=Number.parseInt(T),W=l6.epoch(J);if(W instanceof $J)return $.errors.merge(W),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),yR=OT.module({root:DO,parse:qT({in:DO,morphs:(T)=>new Date(T),declaredOut:e.Date})},{name:"string.date.epoch"}),KO=iT(qR,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),IR=OT.module({root:KO,parse:qT({in:KO,morphs:(T)=>new Date(T),declaredOut:e.Date})},{name:"string.date.iso"}),jR=OT.module({root:_O,parse:qT({declaredIn:_O,in:"string",morphs:(T,$)=>{let J=new Date(T);if(Number.isNaN(J.valueOf()))return $.error("a parsable date");return J},declaredOut:e.Date}),iso:IR,epoch:yR},{name:"string.date"}),xR=iT(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),SO="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",Y0=`(${SO}[.]){3}${SO}`,PR=new RegExp(`^${Y0}$`),H$="(?:[0-9a-fA-F]{1,4})",bR=new RegExp(`^((?:${H$}:){7}(?:${H$}|:)|(?:${H$}:){6}(?:${Y0}|:${H$}|:)|(?:${H$}:){5}(?::${Y0}|(:${H$}){1,2}|:)|(?:${H$}:){4}(?:(:${H$}){0,1}:${Y0}|(:${H$}){1,3}|:)|(?:${H$}:){3}(?:(:${H$}){0,2}:${Y0}|(:${H$}){1,4}|:)|(?:${H$}:){2}(?:(:${H$}){0,3}:${Y0}|(:${H$}){1,5}|:)|(?:${H$}:){1}(?:(:${H$}){0,4}:${Y0}|(:${H$}){1,6}|:)|(?::((?::${H$}){0,5}:${Y0}|(?::${H$}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),vR=OT.module({root:["v4 | v6","@","an IP address"],v4:iT(PR,"an IPv4 address","ipv4"),v6:iT(bR,"an IPv6 address","ipv6")},{name:"string.ip"}),zX="a JSON string",CO=(T)=>{if(!(T instanceof SyntaxError))throw T;return`must be ${zX} (${T})`},hR=qT({meta:zX,domain:"string",predicate:{meta:zX,predicate:(T,$)=>{try{return JSON.parse(T),!0}catch(J){return $.reject({code:"predicate",expected:zX,problem:CO(J)})}}}}),mR=(T,$)=>{if(T.length===0)return $.error({code:"predicate",expected:zX,actual:"empty"});try{return JSON.parse(T)}catch(J){return $.error({code:"predicate",expected:zX,problem:CO(J)})}},gR=OT.module({root:hR,parse:qT({meta:"safe JSON string parser",in:"string",morphs:mR,declaredOut:e.jsonObject})},{name:"string.json"}),VO=iT(/^[a-z]*$/,"only lowercase letters"),pR=OT.module({root:qT({in:"string",morphs:(T)=>T.toLowerCase(),declaredOut:VO}),preformatted:VO},{name:"string.lower"}),ZO=["NFC","NFD","NFKC","NFKD"],E8=YT(ZO,(T,$)=>[$,qT({domain:"string",predicate:(J)=>J.normalize($)===J,meta:`${$}-normalized unicode`})]),n6=YT(ZO,(T,$)=>[$,qT({in:"string",morphs:(J)=>J.normalize($),declaredOut:E8[$]})]),uR=OT.module({root:n6.NFC,preformatted:E8.NFC},{name:"string.normalize.NFC"}),cR=OT.module({root:n6.NFD,preformatted:E8.NFD},{name:"string.normalize.NFD"}),oR=OT.module({root:n6.NFKC,preformatted:E8.NFKC},{name:"string.normalize.NFKC"}),dR=OT.module({root:n6.NFKD,preformatted:E8.NFKD},{name:"string.normalize.NFKD"}),lR=OT.module({root:"NFC",NFC:uR,NFD:cR,NFKC:oR,NFKD:dR},{name:"string.normalize"}),EO=iT(V6,"a well-formed numeric string"),nR=OT.module({root:EO,parse:qT({in:EO,morphs:(T)=>Number.parseFloat(T),declaredOut:e.number})},{name:"string.numeric"}),RO="a regex pattern",iR=qT({domain:"string",predicate:{meta:RO,predicate:(T,$)=>{try{return new RegExp(T),!0}catch(J){return $.reject({code:"predicate",expected:RO,problem:String(J)})}}},meta:{format:"regex"}}),tR=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*))*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?$/,rR=iT(tR,"a semantic version (see https://semver.org/)"),LO=iT(/^\S.*\S$|^\S?$/,"trimmed"),aR=OT.module({root:qT({in:"string",morphs:(T)=>T.trim(),declaredOut:LO}),preformatted:LO},{name:"string.trim"}),BO=iT(/^[A-Z]*$/,"only uppercase letters"),sR=OT.module({root:qT({in:"string",morphs:(T)=>T.toUpperCase(),declaredOut:BO}),preformatted:BO},{name:"string.upper"}),eR=(T)=>{if(URL.canParse)return URL.canParse(T);try{return new URL(T),!0}catch{return!1}},fO=qT({domain:"string",predicate:{meta:"a URL string",predicate:eR},meta:{format:"uri"}}),TL=OT.module({root:fO,parse:qT({declaredIn:fO,in:"string",morphs:(T,$)=>{try{return new URL(T)}catch{return $.error("a URL string")}},declaredOut:qT(URL)})},{name:"string.url"}),$L=OT.module({root:["versioned | nil | max","@",{description:"a UUID",format:"uuid"}],"#nil":"'00000000-0000-0000-0000-000000000000'","#max":"'ffffffff-ffff-ffff-ffff-ffffffffffff'","#versioned":/[\da-f]{8}-[\da-f]{4}-[1-8][\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}/i,v1:iT(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:iT(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:iT(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:iT(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:iT(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:iT(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:iT(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:iT(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),qO=OT.module({root:e.string,alpha:iT(/^[A-Za-z]*$/,"only letters"),alphanumeric:iT(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:LR,base64:BR,capitalize:fR,creditCard:ZR,date:jR,digits:iT(/^\d*$/,"only digits 0-9"),email:xR,integer:NO,ip:vR,json:gR,lower:pR,normalize:lR,numeric:nR,regex:iR,semver:rR,trim:aR,upper:sR,url:TL,uuid:$L},{name:"string"});var kO=OT.module({bigint:e.bigint,boolean:e.boolean,false:e.false,never:e.never,null:e.null,number:e.number,object:e.object,string:e.string,symbol:e.symbol,true:e.true,unknown:e.unknown,undefined:e.undefined}),yO=OT.module({root:e.unknown,any:e.unknown},{name:"unknown"}),JL=OT.module({root:e.jsonObject,stringify:YX("morph",{in:e.jsonObject,morphs:(T)=>JSON.stringify(T),declaredOut:e.string})},{name:"object.json"}),IO=OT.module({root:e.object,json:JL},{name:"object"});class jO extends v${description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var WL=NJ(["K",e.key],"V")((T)=>({domain:"object",index:{signature:T.K,value:T.V}}),jO);class xO extends v${description='pick a set of properties from an object like `Pick(User, "name | age")`'}var XL=NJ(["T",e.object],["K",e.key])((T)=>T.T.pick(T.K),xO);class PO extends v${description='omit a set of properties from an object like `Omit(User, "age")`'}var FL=NJ(["T",e.object],["K",e.key])((T)=>T.T.omit(T.K),PO);class bO extends v${description="make all named properties of an object optional like `Partial(User)`"}var YL=NJ(["T",e.object])((T)=>T.T.partial(),bO);class vO extends v${description="make all named properties of an object required like `Required(User)`"}var GL=NJ(["T",e.object])((T)=>T.T.required(),vO);class hO extends v${description='exclude branches of a union like `Exclude("boolean", "true")`'}var HL=NJ("T","U")((T)=>T.T.exclude(T.U),hO);class mO extends v${description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var ML=NJ("T","U")((T)=>T.T.extract(T.U),mO),gO=OT.module({Exclude:HL,Extract:ML,Omit:FL,Partial:YL,Pick:XL,Record:WL,Required:GL});var G0=u5({...kO,...gO,...QO,...GO,string:qO,number:l6,object:IO,unknown:yO},{prereducedAliases:!0,name:"ark"}),E$=G0.export();Object.assign(MX.ambient,E$);MX.typeAttachments={string:E$.string.root,number:E$.number.root,bigint:E$.bigint,boolean:E$.boolean,symbol:E$.symbol,undefined:E$.undefined,null:E$.null,object:E$.object.root,unknown:E$.unknown.root,false:E$.false,true:E$.true,never:E$.never,arrayIndex:E$.Array.index,Key:E$.Key,Record:E$.Record,Array:E$.Array.root,Date:E$.Date};var k1=Object.assign(G0.type,MX.typeAttachments),zL=G0.match,AL=G0.generic,LXT=G0.schema,wL=G0.define,QL=G0.declare;var OL="__vite_start_time"in globalThis,UL=typeof window!=="undefined",pXT="vitest"in globalThis,y1=k1("string"),pO=k1('"true" | "false" | undefined'),I1=jA({isServer:!OL&&!UL,server:{CI:k1("string | undefined").pipe(Boolean),POSTGRES_USER:y1,POSTGRES_PASSWORD:y1,POSTGRES_DATABASE:y1,POSTGRES_HOST:y1,POSTGRES_PORT:y1.pipe((T)=>Number.parseInt(T,10)),BACKEND_PORT:y1.pipe((T)=>Number.parseInt(T,10)),RUN_WORKERS_FROM_SOURCE:pO.pipe((T)=>T==="true"),FRONTEND_PORT:y1.pipe((T)=>Number.parseInt(T,10)),FRONTEND_ORIGINS:y1.pipe.try((T)=>JSON.parse(T),k1("string[]")),OPENAI_API_KEY:k1("string | undefined")},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:y1,VITE_USE_SELF_SIGNED_CERTIFICATE:pO.pipe((T)=>T==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var d5={};J_(d5,{users:()=>r0,userChanges:()=>DL,untrackedUserColumnNames:()=>_L,twoFactorMethod:()=>lO,trackedUserColumnName:()=>dO,trackableUserColumnNames:()=>oO,role:()=>cO,players:()=>o5,passwordResetAttempts:()=>SL,loginHistory:()=>KL,games:()=>i6,banishedIps:()=>t6});function uO(T){return U`lower(${T})`}var cO=v4("role",["admin","user"]),r0=r1("users",{id:AJ().primaryKey().defaultRandom(),username:P$({length:16}).notNull(),email:P$({length:254}).notNull(),password:P$({length:254}).notNull(),createdAt:bJ({withTimezone:!0}).notNull().defaultNow(),createdIp:P$({length:45}).notNull(),isActive:j2().notNull().default(!1),verifiedAt:bJ({withTimezone:!0}),userRole:cO().default("user")},(T)=>[R9("usernameUniqueIndex").on(uO(T.username)),R9("emailUniqueIndex").on(uO(T.email))]),_L=["id","createdAt","createdIp","isActive","verifiedAt"],oO=["username","email","password","userRole"],dO=v4("trackedUserColumnName",oO),DL=r1("userChanges",{id:AJ().primaryKey().defaultRandom(),userId:AJ().notNull().references(()=>r0.id,{onDelete:"cascade"}),changedAt:bJ({withTimezone:!0}).notNull().defaultNow(),changedIp:P$({length:45}).notNull(),changedColumn:dO().notNull(),oldValue:P$({length:255}),newValue:P$({length:255})}),i6=r1("games",{id:AJ().primaryKey().defaultRandom()}),o5=r1("players",{userId:AJ().notNull().references(()=>r0.id,{onDelete:"cascade"}),gameId:AJ().notNull().references(()=>i6.id,{onDelete:"cascade"}),score:l4().notNull()},(T)=>[Iz({name:"players_userId_gameId_pk",columns:[T.userId,T.gameId]})]),KL=r1("loginHistory",{id:AJ().primaryKey().defaultRandom(),userId:AJ().references(()=>r0.id,{onDelete:"cascade"}),loginTime:bJ({withTimezone:!0}).notNull().defaultNow(),ipAddress:P$({length:45}).notNull(),userAgent:P$({length:1024}),successful:j2().notNull().default(!1)}),lO=v4("twoFactorMethod",["email","phone"]),SL=r1("passwordResetAttempts",{id:AJ().primaryKey().defaultRandom(),userId:AJ().notNull().references(()=>r0.id,{onDelete:"cascade"}),requestedIp:P$({length:45}).notNull(),requestedAt:bJ({withTimezone:!0}).notNull().defaultNow(),succeededIp:P$({length:45}),succeededAt:bJ({withTimezone:!0}),verificationMethod:lO().notNull()}),t6=r1("banishedIps",{ip:P$({length:45}).primaryKey(),reason:P$({length:2048}).notNull(),banishedAt:bJ({withTimezone:!0}).notNull().defaultNow(),banishedUntil:bJ({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class l5{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(VL.resolve(__dirname,"notify_update.sql"));let T=[B$(r0),B$(i6),B$(o5)];await this.sql`SELECT create_notify_triggers(${this.sql.array(T)})`,await this.sql.listen("table_update",($)=>{let J=$.split(","),W=J[0],X=J[1],F=`${W}("${X}")`;if(this.observers.has(F))this.observers.get(F).next(F)})}constructor(T=!1,$={host:I1.POSTGRES_HOST,port:I1.POSTGRES_PORT,user:I1.POSTGRES_USER,password:I1.POSTGRES_PASSWORD,database:I1.POSTGRES_DATABASE}){this.options=$,this.sql=cW($),this.drizzle=K6(this.sql,{schema:d5,logger:T})}observe(T,$){if(!this.observers.has(T))this.observers.set(T,new QT);this.observers.get(T).subscribe("SINGLETON",$)}}import{resolve as LL}from"path";import{existsSync as n5,mkdirSync as nO,readFileSync as EL,readdirSync as iO,rmSync as tO,statSync as rO,writeFileSync as RL}from"fs";import{resolve as i5}from"path";var aO=class{rootDir;get initialized(){return n5(this.rootDir)}initialize(){if(!this.initialized)nO(this.rootDir,{recursive:!0})}constructor(T){if(this.rootDir=T.path,T.eagerInit)this.initialize()}getItem(T){let $=i5(this.rootDir,T);if(n5($))return EL($,"utf-8");return null}setItem(T,$){this.initialize();let J=i5(this.rootDir,T);RL(J,$)}removeItem(T){let $=i5(this.rootDir,T);if(n5($))this.initialize(),tO($)}key(T){return iO(this.rootDir).sort((W,X)=>{let F=rO(W);return rO(X).ctimeMs-F.ctimeMs})[T]??null}clear(){tO(this.rootDir,{recursive:!0}),nO(this.rootDir,{recursive:!0})}get length(){return iO(this.rootDir).length}};var t5=new aO({path:LL(process.cwd(),"storage")});import*as r6 from"fs";import*as sO from"readline";function BL(T){let J=T.replace(":","T").replace(" ","").replace(/(\d{2})\/(\w{3})\/(\d{4})T(.+)/,(W,X,F,Y,G)=>{let M={Jan:"01",Feb:"02",Mar:"03",Apr:"04",May:"05",Jun:"06",Jul:"07",Aug:"08",Sep:"09",Oct:"10",Nov:"11",Dec:"12"}[F];return`${Y}-${M}-${X}T${G}`});return new Date(J)}async function eO(T,$="/var/log/nginx/access.log",J=new Date){let W=new Map;if(!r6.existsSync($))return T.error(`Log file not found: ${$}`),W;let X=r6.createReadStream($),F=sO.createInterface({input:X,crlfDelay:Number.POSITIVE_INFINITY}),Y=new Date(J.getTime()-3600000);return F.on("line",(G)=>{let H=/^(?<ip>\S+) \S+ \S+ \[(?<dateTime>.*?)\]/,M=G.match(H);if(M?.groups){let z=M.groups.ip,A=M.groups.dateTime,w=BL(A);if(!Number.isNaN(w.getTime())){if(w>=Y&&w<=J){let _=W.get(z);if(!_)_=[],W.set(z,_);_.push(G)}}else T.error(`Failed to parse date: ${A}`)}}),new Promise((G,H)=>{F.on("error",(M)=>{H(M)}),F.on("close",()=>{G(W)})})}function TU(T){return T.toJsonSchema()}var fL=["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(`
139
- `);function $U(T){return fL+T.join(`
127
+ `)+"}");class sY{config;resolvedConfig;name;get[j1](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(W,$){if(this.config=j6(R.config,$),this.resolvedConfig=j6(R.resolvedConfig,$),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(L7).length}`,this.name in L7)L(`A Scope already named ${this.name} already exists`);L7[this.name]=this;let X=Object.entries(W).map((Y)=>this.preparseOwnAliasEntry(...Y));for(let[Y,J]of X){let G=Y;if(Y[0]==="#"){if(G=Y.slice(1),G in this.aliases)L(hU(G));this.aliases[G]=J}else{if(G in this.aliases)L(hU(Y));this.aliases[G]=J,this.exportedNames.push(G)}if(!d(J,"module")&&!d(J,"generic")&&!b2(J)){let H=this.preparseOwnDefinitionFormat(J,{alias:G});this.resolutions[G]=d(H,"root")?this.bindReference(H):this.createParseContext(H).id}}gU??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[gU.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=R.intrinsic?$0(R.intrinsic,(Y,J)=>Y.startsWith("json")?[]:[Y,this.bindReference(J)]):{}}cacheGetter(W,$){return Object.defineProperty(this,W,{value:$}),$}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema(W){return W}generic=(...W)=>{let $=this;return(X,Y)=>new p2(W,Y?new dY(X):X,$,$,Y??null)};units=(W,$)=>{let X=[];for(let J of W)if(!X.includes(J))X.push(J);let Y=X.map((J)=>this.node("unit",{unit:J},$));return this.node("union",Y,{...$,prereduced:!0})};lazyResolutions=[];lazilyResolve(W,$){let X=this.node("alias",{reference:$??"synthetic",resolve:W},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(X);return X}schema=(W,$)=>this.finalize(this.parseSchema(W,$));parseSchema=(W,$)=>this.node(v6(W),W,$);preparseNode(W,$,X){let Y=typeof W==="string"?W:v6($,W);if(P0($)&&$.kind===Y)return $;if(Y==="alias"&&!X?.prereduced){let{reference:H}=p6.implementation.normalize($,this);if(H.startsWith("$")){let Q=this.resolveRoot(H.slice(1));$=Q,Y=Q.kind}}else if(Y==="union"&&g1($,"object")){let H=lL($);if(H?.length===1)$=H[0],Y=v6($)}if(P0($)&&$.kind===Y)return $;let G=C$[Y].normalize?.($,this)??$;if(P0(G))return G.kind===Y?G:oL(Y,G.kind);return{...X,$:this,kind:Y,def:G,prefix:X.alias??Y}}bindReference(W){let $;if(P0(W))$=W.$===this?W:new W.constructor(W.attachments,this);else $=W.$===this?W:new p2(W.params,W.bodyDef,W.$,this,W.hkt);if(!this.resolved)Object.assign(this.referencesById,$.referencesById);return $}resolveRoot(W){return this.maybeResolveRoot(W)??L(N7(W))}maybeResolveRoot(W){let $=this.maybeResolve(W);if(d($,"generic"))return;return $}maybeResolveSubalias(W){return A7(this.aliases,W)??A7(this.ambient,W)}get ambient(){return R.ambient}maybeResolve(W){let $=this.resolutions[W];if($){if(typeof $!=="string")return this.bindReference($);let Y=f1[$];if(d(Y,"root"))return this.resolutions[W]=Y;if(d(Y,"context")){if(Y.phase==="resolving")return this.node("alias",{reference:`$${W}`},{prereduced:!0});if(Y.phase==="resolved")return O0(`Unexpected resolved context for was uncached by its scope: ${X0(Y)}`);Y.phase="resolving";let J=this.bindReference(this.parseOwnDefinitionFormat(Y.def,Y));return Y.phase="resolved",f1[J.id]=J,f1[Y.id]=J,this.resolutions[W]=J}return O0(`Unexpected nodesById entry for ${$}: ${X0(Y)}`)}let X=this.aliases[W]??this.ambient?.[W];if(!X)return this.maybeResolveSubalias(W);if(X=this.normalizeRootScopeValue(X),d(X,"generic"))return this.resolutions[W]=this.bindReference(X);if(d(X,"module")){if(!X.root)L(oU(W));return this.resolutions[W]=this.bindReference(X.root)}return this.resolutions[W]=this.parse(X,{alias:W})}createParseContext(W){let $=W.id??X7(W.prefix);return f1[$]=Object.assign(W,{[j1]:"context",$:this,id:$,phase:"unresolved"})}traversal(W){return new ZW(W,this.resolvedConfig)}import(...W){return new j$($0(this.export(...W),($,X)=>[`#${$}`,X]))}precompilation;_exportedResolutions;_exports;export(...W){if(!this._exports){this._exports={};for(let X of this.exportedNames){let Y=this.aliases[X];this._exports[X]=d(Y,"module")?K7(Y,this):mU(this.maybeResolve(X))}for(let X of this.lazyResolutions)X.resolution;if(this._exportedResolutions=lU(this,this._exports),this._json=dU(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let X=cU(this.references);this.precompilation=X.write(pU,4),uU(this.references,X)}this.resolved=!0}let $=W.length?W:this.exportedNames;return new j$($0($,(X,Y)=>[Y,this._exports[Y]]))}resolve(W){return this.export()[W]}node=(W,$,X={})=>{let Y=this.preparseNode(W,$,X);if(P0(Y))return this.bindReference(Y);let J=this.createParseContext(Y),G=Y7(J),H=this.bindReference(G);return f1[J.id]=H};parse=(W,$={})=>this.finalize(this.parseDefinition(W,$));parseDefinition(W,$={}){if(d(W,"root"))return this.bindReference(W);let X=this.preparseOwnDefinitionFormat(W,$);if(d(X,"root"))return this.bindReference(X);let Y=this.createParseContext(X);f1[Y.id]=Y;let J=this.bindReference(this.parseOwnDefinitionFormat(W,Y));if(J.isCyclic)J=wU(J,Y.id);return f1[Y.id]=J,J}finalize(W){if(mU(W),!W.precompilation&&!this.resolvedConfig.jitless)iL(W.references);return W}}class E7 extends sY{parseOwnDefinitionFormat(W,$){return Y7($)}preparseOwnDefinitionFormat(W,$){return this.preparseNode(v6(W),W,$)}preparseOwnAliasEntry(W,$){return[W,$]}normalizeRootScopeValue(W){return W}}var mU=(W)=>{let $=W.references.filter((X)=>X.hasKind("alias"));for(let X of $){Object.assign(X.referencesById,X.resolution.referencesById);for(let Y of W.references)if(X.id in Y.referencesById)Object.assign(Y.referencesById,X.referencesById)}return W},dU=(W)=>$0(W,($,X)=>[$,d(X,"root")||d(X,"generic")?X.json:d(X,"module")?dU(X):O0(`Unexpected resolution ${X0(X)}`)]),A7=(W,$)=>{let X=$.indexOf(".");if(X===-1)return;let Y=$.slice(0,X),J=W[Y];if(J===void 0)return;if(!d(J,"module"))return L(nL(Y));let G=$.slice(X+1),H=J[G];if(H===void 0)return A7(J,G);if(d(H,"root")||d(H,"generic"))return H;if(d(H,"module"))return H.root??L(oU($));O0(`Unexpected resolution for alias '${$}': ${X0(H)}`)},eY=(W,$)=>new E7(W,$),d6=new E7({});var lU=(W,$)=>{let X={};for(let Y in $){let J=$[Y];if(d(J,"module")){let G=lU(W,J),H=$0(G,(Q,z)=>[`${Y}.${Q}`,z]);Object.assign(X,H)}else if(d(J,"root")||d(J,"generic"))X[Y]=J;else O0(`Unexpected scope resolution ${X0(J)}`)}return X},N7=(W)=>`'${W}' is unresolvable`,nL=(W)=>`'${W}' must reference a module to be accessed using dot syntax`,oU=(W)=>`Reference to submodule '${W}' must specify an alias`;d6.export();var{schema:E0,node:f$,defineSchema:ni,generic:UW}=d6;var B7="^(?:0|[1-9]\\d*)$",rL=new RegExp(B7),ai=c0(rL);var iU=eY({bigint:"bigint",boolean:[{unit:!1},{unit:!0}],false:{unit:!1},never:[],null:{unit:null},number:"number",object:"object",string:"string",symbol:"symbol",true:{unit:!0},unknown:{},undefined:{unit:void 0},Array,Date},{prereducedAliases:!0}).export();R.intrinsic={...iU};var nU=eY({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:B7}},{prereducedAliases:!0}).export();Object.assign(R.intrinsic,nU);var tL=eY({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),r={...iU,...nU,...tL,emptyStructure:f$("structure",{},{prereduced:!0})};R.intrinsic={...r};var tU=(W)=>typeof W==="string"&&W[0]==="d"&&(W[1]==="'"||W[1]==='"')&&W.at(-1)===W[1],rU=(W)=>W.toString()!=="Invalid Date",aU=(W)=>W.slice(2,-1),R7=(W)=>`'${W}' could not be parsed by the Date constructor`,sU=(W,$)=>aL(W,$),aL=(W,$)=>{let X=new Date(W);if(rU(X))return X;let Y=IT(W);if(Y!==void 0){let J=new Date(Y);if(rU(J))return J}return $?L($===!0?R7(W):$):void 0};var Z7=(W,$)=>{let X=W.scanner.shiftUntil(sL[Ww[$]]);if(W.scanner.lookahead==="")return W.error(WA(X,$));if(W.scanner.shift(),$==="/"){try{new RegExp(X)}catch(Y){L(String(Y))}W.root=W.ctx.$.node("intersection",{domain:"string",pattern:X},{prereduced:!0})}else if(z1($,S7))W.root=W.ctx.$.node("unit",{unit:X});else{let Y=sU(X,R7(X));W.root=W.ctx.$.node("unit",{meta:X,unit:Y})}},S7={"'":1,'"':1},eU={"/":1,"'":1,'"':1},Ww={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},sL={"'":(W)=>W.lookahead==="'",'"':(W)=>W.lookahead==='"',"/":(W)=>W.lookahead==="/"},eL={'"':"double-quote","'":"single-quote","/":"forward slash"},WA=(W,$)=>`${$}${W} requires a closing ${eL[Ww[$]]}`;var $w=(W)=>`Private type references should not include '#'. Use '${W}' instead.`,W9="Optional definitions like 'string?' are only valid as properties in an object or tuple",$9="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var Xw={">":!0,">=":!0},Yw={"<":!0,"<=":!0};var P$={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},Jw=(W)=>`Unmatched )${W===""?"":` before ${W}`}`,X9=(W)=>`Missing ${W}`,Gw=(W,$)=>`Left bounds are only valid when paired with right bounds (try ...${$}${W})`,Y9=(W)=>`Left-bounded expressions must specify their limits using < or <= (was ${W})`,Hw=(W,$,X,Y)=>`An expression may have at most one left bound (parsed ${W}${P$[$]}, ${X}${P$[Y]})`;var Qw=(W,$,X)=>zw(W,$,X,[]),zw=(W,$,X,Y)=>{let J=X.parseUntilFinalizer();if(Y.push(J.root),J.finalizer===">"){if(Y.length!==$.params.length)return X.error(q7(W,$.names,Y.map((G)=>G.expression)));return Y}if(J.finalizer===",")return zw(W,$,X,Y);return J.error(X9(">"))},q7=(W,$,X)=>`${W}<${$.join(", ")}> requires exactly ${$.length} args (got ${X.length}${X.length===0?"":`: ${X.join(", ")}`})`;var C7=(W)=>{let $=W.scanner.shiftUntilNextTerminator();if($==="keyof")W.addPrefix("keyof");else W.root=XA(W,$)},$A=(W,$,X)=>{if(X.scanner.shiftUntilNonWhitespace(),X.scanner.shift()!=="<")return X.error(q7(W,$.names,[]));let J=Qw(W,$,X);return $(...J)},XA=(W,$)=>YA(W,$)??JA(W,$)??W.error($===""?W.scanner.lookahead==="#"?$w(W.shiftedByOne().scanner.shiftUntilNextTerminator()):k7(W):N7($)),YA=(W,$)=>{if(W.ctx.args?.[$]){let Y=W.ctx.args[$];if(typeof Y!=="string")return Y;return W.ctx.$.node("alias",{reference:Y},{prereduced:!0})}let X=W.ctx.$.maybeResolve($);if(d(X,"root"))return X;if(X===void 0)return;if(d(X,"generic"))return $A($,X,W);return L(`Unexpected resolution ${X0(X)}`)},JA=(W,$)=>{let X=jT($);if(X!==void 0)return W.ctx.$.node("unit",{unit:X});let Y=PT($);if(Y!==void 0)return W.ctx.$.node("unit",{unit:Y})},k7=(W)=>{let $=W.previousOperator();return $?I7($,W.scanner.unscanned):GA(W.scanner.unscanned)},I7=(W,$="")=>`Token '${W}' requires a right operand${$?` before '${$}'`:""}`,GA=(W)=>`Expected an expression${W?` before '${W}'`:""}`;var j7=(W)=>W.scanner.lookahead===""?W.error(k7(W)):W.scanner.lookahead==="("?W.shiftedByOne().reduceGroupOpen():W.scanner.lookaheadIsIn(eU)?Z7(W,W.scanner.shift()):W.scanner.lookaheadIsIn(y2)?j7(W.shiftedByOne()):W.scanner.lookahead==="d"?W.scanner.nextLookahead in S7?Z7(W,`${W.scanner.shift()}${W.scanner.shift()}`):C7(W):C7(W);class w2 extends b5{shiftUntilNextTerminator(){return this.shiftUntilNonWhitespace(),this.shiftUntil(()=>(this.lookahead in w2.terminatingChars))}static terminatingChars={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...y2};static finalizingLookaheads={">":1,",":1,"":1,"=":1,"?":1};static lookaheadIsFinalizing=(W,$)=>W===">"?$[0]==="="?$[1]==="=":$.trimStart()===""||z1($.trimStart()[0],w2.terminatingChars):W==="="?$[0]!=="=":W===","||W==="?"}var Tw=(W,$)=>{let X=HA(W,$);if(W.root.hasKind("unit")){if(typeof W.root.unit==="number"){W.reduceLeftBound(W.root.unit,X),W.unsetRoot();return}if(W.root.unit instanceof Date){let Y=`d'${W.root.description??W.root.unit.toISOString()}'`;W.unsetRoot(),W.reduceLeftBound(Y,X);return}}return zA(W,X)},Uw={"<":1,">":1,"=":1},HA=(W,$)=>W.scanner.lookaheadIs("=")?`${$}${W.scanner.shift()}`:$;var Fw=(W,$,X,Y)=>{if(X.extends(R.intrinsic.number)){if(typeof $!=="number")return L(f7(W,$,Y));return W==="=="?["min","max"]:W[0]===">"?["min"]:["max"]}if(X.extends(R.intrinsic.lengthBoundable)){if(typeof $!=="number")return L(f7(W,$,Y));return W==="=="?["exactLength"]:W[0]===">"?["minLength"]:["maxLength"]}if(X.extends(R.intrinsic.Date))return W==="=="?["after","before"]:W[0]===">"?["after"]:["before"];return L(eT(X.expression))},QA=(W)=>({rule:tU(W.limit)?aU(W.limit):W.limit,exclusive:W.comparator.length===1}),zA=(W,$)=>{let X=W.unsetRoot(),Y=W.scanner.location;W.parseOperand();let J=W.unsetRoot(),G=W.scanner.sliceChars(Y,W.scanner.location);if(W.root=X,!J.hasKind("unit")||typeof J.unit!=="number"&&!(J.unit instanceof Date))return W.error(f7($,G,"right"));let H=J.unit,Q=$.length===1,z=Fw($,typeof H==="number"?H:G,X,"right");for(let T of z)W.constrainRoot(T,$==="=="?{rule:H}:{rule:H,exclusive:Q});if(!W.branches.leftBound)return;if(!z1($,Yw))return W.error(Y9($));let F=Fw(W.branches.leftBound.comparator,W.branches.leftBound.limit,X,"left");W.constrainRoot(F[0],QA(W.branches.leftBound)),W.branches.leftBound=null},f7=(W,$,X)=>`Comparator ${X==="left"?P$[W]:W} must be ${X==="left"?"preceded":"followed"} by a corresponding literal (was ${$})`;var ww=(W)=>{W.scanner.shiftUntilNonWhitespace();let $=W.scanner.shiftUntilNextTerminator();W.root=W.root.brand($)};var _w=(W)=>{let $=W.scanner.shiftUntilNextTerminator(),X=fT($,{errorOnFail:Mw($)});if(X===0)W.error(Mw(0));W.root=W.root.constrain("divisor",X)},Mw=(W)=>`% operator must be followed by a non-zero integer literal (was ${W})`;var P7=(W)=>{let $=W.scanner.shift();return $===""?W.finalize(""):$==="["?W.scanner.shift()==="]"?W.setRoot(W.root.array()):W.error(FA):$==="|"?W.scanner.lookahead===">"?W.shiftedByOne().pushRootToBranch("|>"):W.pushRootToBranch($):$==="&"?W.pushRootToBranch($):$===")"?W.finalizeGroup():w2.lookaheadIsFinalizing($,W.scanner.unscanned)?W.finalize($):z1($,Uw)?Tw(W,$):$==="%"?_w(W):$==="#"?ww(W):($ in y2)?P7(W):W.error(J9($))},J9=(W,$="")=>`'${W}' is not allowed here${$&&` (should be ${$})`}`,FA="Missing expected ']'";var Dw=(W)=>{let $=W.unsetRoot();W.parseOperand();let X=W.unsetRoot();if(!X.hasKind("unit"))return W.error(TA(X.expression));let Y=X.unit instanceof Date?()=>new Date(X.unit):X.unit;return[$,"=",Y]},TA=(W)=>`Default value '${W}' must a literal value`;var x7=(W,$)=>{let X=$.$.maybeResolveRoot(W);if(X)return X;if(W.endsWith("[]")){let G=$.$.maybeResolveRoot(W.slice(0,-2));if(G)return G.array()}let Y=new x$(new w2(W),$),J=UA(Y);if(Y.finalizer===">")L(J9(">"));return J},UA=(W)=>{W.parseOperand();let $=l6(W).root;if(!$)return O0(`Root was unexpectedly unset after parsing string '${W.scanner.scanned}'`);if(W.finalizer==="=")$=Dw(W);else if(W.finalizer==="?")$=[$,"?"];if(W.scanner.shiftUntilNonWhitespace(),W.scanner.lookahead)L(J9(W.scanner.lookahead));return $},l6=(W)=>{while(W.finalizer===void 0)wA(W);return W},wA=(W)=>W.hasRoot()?W.parseOperator():W.parseOperand();class x${root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(W,$){this.scanner=W,this.ctx=$}error(W){return L(W)}hasRoot(){return this.root!==void 0}setRoot(W){this.root=W}unsetRoot(){let W=this.root;return this.root=void 0,W}constrainRoot(...W){this.root=this.root.constrain(W[0],W[1])}finalize(W){if(this.groups.length)return this.error(X9(")"));this.finalizeBranches(),this.finalizer=W}reduceLeftBound(W,$){let X=P$[$];if(!z1(X,Xw))return this.error(Y9($));if(this.branches.leftBound)return this.error(Hw(this.branches.leftBound.limit,this.branches.leftBound.comparator,W,X));this.branches.leftBound={comparator:X,limit:W}}finalizeBranches(){if(this.assertRangeUnset(),this.branches.pipe){this.pushRootToBranch("|>"),this.root=this.branches.pipe;return}if(this.branches.union){this.pushRootToBranch("|"),this.root=this.branches.union;return}if(this.branches.intersection){this.pushRootToBranch("&"),this.root=this.branches.intersection;return}this.applyPrefixes()}finalizeGroup(){this.finalizeBranches();let W=this.groups.pop();if(!W)return this.error(Jw(this.scanner.unscanned));this.branches=W}addPrefix(W){this.branches.prefixes.push(W)}applyPrefixes(){while(this.branches.prefixes.length){let W=this.branches.prefixes.pop();this.root=W==="keyof"?this.root.keyof():O0(`Unexpected prefix '${W}'`)}}pushRootToBranch(W){this.assertRangeUnset(),this.applyPrefixes();let $=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd($)??$,W==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,W==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return l6(new x$(this.scanner,this.ctx))}parseOperator(){return P7(this)}parseOperand(){return j7(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(Gw(this.branches.leftBound.limit,this.branches.leftBound.comparator))}reduceGroupOpen(){this.groups.push(this.branches),this.branches={prefixes:[],leftBound:null,union:null,intersection:null,pipe:null}}previousOperator(){return this.branches.leftBound?.comparator??this.branches.prefixes.at(-1)??(this.branches.intersection?"&":this.branches.union?"|":this.branches.pipe?"|>":void 0)}shiftedByOne(){return this.scanner.shift(),this}}var MA="An empty string is not a valid generic parameter name",G9=(W,$,X)=>{W.shiftUntilNonWhitespace();let Y=W.shiftUntilNextTerminator();if(Y===""){if(W.lookahead===""&&$.length)return $;return L(MA)}return W.shiftUntilNonWhitespace(),_A(W,Y,$,X)},Vw="extends ",_A=(W,$,X,Y)=>{if(W.shiftUntilNonWhitespace(),W.unscanned.startsWith(Vw))W.jumpForward(Vw.length);else{if(W.lookahead===",")W.shift();return X.push($),G9(W,X,Y)}let J=l6(new x$(W,Y));return X.push([$,J.root]),G9(W,X,Y)};class v7 extends RW{$;constructor(W){super((...$)=>new o6(W)(...$),{bind:W});this.$=W}in(W){return new o6(this.$,W===void 0?void 0:this.$.parse(W))}at(W,$){return new o6(this.$).at(W,$)}case(W,$){return new o6(this.$).case(W,$)}}class o6 extends RW{$;in;key;branches=[];constructor(W,$){super((X)=>this.caseEntries(Object.entries(X).map(([Y,J])=>Y==="default"?[Y,J]:[this.$.parse(Y),J])));this.$=W,this.in=$}at(W,$){if(this.key)L(VA);if(this.branches.length)L(DA);return this.key=W,$?this.match($):this}case(W,$){return this.caseEntry(this.$.parse(W),$)}caseEntry(W,$){let Y=(this.key?this.$.parse({[this.key]:W}):W).pipe($);return this.branches.push(Y),this}match(W){return this(W)}strings(W){return this.caseEntries(Object.entries(W).map(([$,X])=>$==="default"?[$,X]:[this.$.node("unit",{unit:$}),X]))}caseEntries(W){for(let $=0;$<W.length;$++){let[X,Y]=W[$];if(X==="default"){if($!==W.length-1)L("default may only be specified as the last key of a switch definition");return this.default(Y)}if(typeof Y!=="function")return L(`Value for case "${X}" must be a function (was ${Q1(Y)})`);this.caseEntry(X,Y)}return this}default(W){if(typeof W==="function")this.case(r.unknown,W);let $={branches:this.branches,ordered:!0};if(W==="never"||W==="assert")$.meta={onFail:Ow};let X=this.$.node("union",$);if(!this.in)return this.$.finalize(X);let Y=this.in.pipe(X);if(W==="never"||W==="assert")Y=Y.configureReferences({onFail:Ow},"self");return this.$.finalize(Y)}}var Ow=(W)=>W.throw(),DA="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",VA="At most one key matcher may be specified per expression";var H9=(W,$)=>{if(C0(W)){if(W[1]==="=")return[$.$.parseOwnDefinitionFormat(W[0],$),"=",W[2]];if(W[1]==="?")return[$.$.parseOwnDefinitionFormat(W[0],$),"?"]}return Q9(W,$)},Kw="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",Lw="Only required keys may specify default values, e.g. { value: 'number = 0' }";var Aw=(W,$)=>{let X,Y={},J=E8(W);for(let[H,Q]of J){let z=LA(H);if(z.kind==="spread"){if(!uW(Y))return L(KA);let V=$.$.parseOwnDefinitionFormat(Q,$);if(V.equals(r.object))continue;if(!V.hasKind("intersection")||!V.basis?.equals(r.object))return L(AA(V.expression));X=V.structure;continue}if(z.kind==="undeclared"){if(Q!=="reject"&&Q!=="delete"&&Q!=="ignore")L(OA(Q));Y.undeclared=Q;continue}let F=H9(Q,$),T=z;if(z.kind==="required"){if(!C0(F))b7(Y,"required",{key:z.normalized,value:F},$);else b7(Y,"optional",F[1]==="="?{key:z.normalized,value:F[0],default:F[2]}:{key:z.normalized,value:F[0]},$);continue}if(C0(F)){if(F[1]==="?")L(Kw);if(F[1]==="=")L(Lw)}if(z.kind==="optional"){b7(Y,"optional",{key:z.normalized,value:F},$);continue}let U=$.$.parseOwnDefinitionFormat(T.normalized,$),M=aY(U,F,$.$);if(M.index)Y.index=M0(Y.index,M.index);if(M.required)Y.required=M0(Y.required,M.required)}let G=$.$.node("structure",Y);return $.$.parseSchema({domain:"object",structure:X?.merge(G)??G})},b7=(W,$,X,Y)=>{W[$]=M0(W[$],Y.$.node($,X))},OA=(W)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${X0(W)})`,KA="Spread operator may only be used as the first key in an object",LA=(W)=>typeof W==="symbol"?{kind:"required",normalized:W}:W.at(-1)==="?"?W.at(-2)===R6?{kind:"required",normalized:`${W.slice(0,-2)}?`}:{kind:"optional",normalized:W.slice(0,-1)}:W[0]==="["&&W.at(-1)==="]"?{kind:"index",normalized:W.slice(1,-1)}:W[0]===R6&&W[1]==="["&&W.at(-1)==="]"?{kind:"required",normalized:W.slice(1)}:W==="..."?{kind:"spread"}:W==="+"?{kind:"undeclared"}:{kind:"required",normalized:W==="\\..."?"...":W==="\\+"?"+":W},AA=(W)=>`Spread operand must resolve to an object literal type (was ${W})`;var Nw=(W,$)=>IA(W)?Sw[W[0]](W,$):CA(W)?Zw[W[1]](W,$):null,EA=(W,$)=>$.$.parseOwnDefinitionFormat(W[1],$).keyof(),y7=(W,$)=>{if(W[2]===void 0)return L(I7(W[1],""));let X=$.$.parseOwnDefinitionFormat(W[0],$),Y=$.$.parseOwnDefinitionFormat(W[2],$);if(W[1]==="|")return $.$.node("union",{branches:[X,Y]});let J=W[1]==="&"?c1(X,Y,$.$):x6(X,Y,$.$);if(J instanceof P)return J.throw();return J},NA=(W,$)=>$.$.parseOwnDefinitionFormat(W[0],$).array(),BA=(W,$)=>{if(typeof W[2]!=="function")return L(Bw("=>",W[2]));return $.$.parseOwnDefinitionFormat(W[0],$).pipe(W[2])},Bw=(W,$)=>`${W===":"?"Narrow":"Morph"} expression requires a function following '${W}' (was ${typeof $})`,RA=(W,$)=>{if(typeof W[2]!=="function")return L(Bw(":",W[2]));return $.$.parseOwnDefinitionFormat(W[0],$).constrain("predicate",W[2])},ZA=(W,$)=>$.$.parseOwnDefinitionFormat(W[0],$).configureReferences(W[2],"shallow"),Rw=(W)=>W,SA=Rw({"[]":NA,"?":()=>L(W9)}),qA=Rw({"|":y7,"&":y7,":":RA,"=>":BA,"|>":y7,"@":ZA,"=":()=>L($9)}),Zw={...SA,...qA},CA=(W)=>Zw[W[1]]!==void 0,kA=(W)=>W,Sw=kA({keyof:EA,instanceof:(W,$)=>{if(typeof W[1]!=="function")return L(Ew(N6(W[1])));let X=W.slice(1).map((Y)=>typeof Y==="function"?$.$.node("proto",{proto:Y}):L(Ew(N6(Y))));return X.length===1?X[0]:$.$.node("union",{branches:X})},"===":(W,$)=>$.$.units(W.slice(1))}),IA=(W)=>Sw[W[0]]!==void 0,Ew=(W)=>`Expected a constructor following 'instanceof' operator (was ${W})`;var kw=(W,$)=>{let X=[{}],Y=0;while(Y<W.length){let J=!1;if(W[Y]==="..."&&Y<W.length-1)J=!0,Y++;let G=H9(W[Y],$),[H,Q,z]=!C0(G)?[G]:G;if(Y++,J){if(!H.extends(R.intrinsic.Array))return L(PA(H.expression));X=X.flatMap((F)=>H.distribute((T)=>fA(mY(F),T)))}else X=X.map((F)=>{if(Q==="?")return Iw(F,H);if(Q==="=")return jA(F,H,z);return h7(F,H)})}return $.$.parseSchema(X.map((J)=>uW(J)?{proto:Array,exactLength:0}:{proto:Array,sequence:J}))},h7=(W,$)=>{if(W.defaultables||W.optionals)return L(W.variadic?D7:xA);if(W.variadic)W.postfix=M0(W.postfix,$);else W.prefix=M0(W.prefix,$);return W},Iw=(W,$)=>{if(W.variadic)return L(jw);return W.optionals=M0(W.optionals,$),W},jA=(W,$,X)=>{if(W.variadic)return L(jw);if(W.optionals)return L(vA);return W.defaultables=M0(W.defaultables,[[$,X]]),W},qw=(W,$)=>{if(W.postfix)L(Cw);if(W.variadic){if(!W.variadic.equals($))L(Cw)}else W.variadic=$.internal;return W},fA=(W,$)=>{let X=$.select({method:"find",kind:"sequence"});if(!X)return qw(W,R.intrinsic.unknown);if(X.prefix)for(let Y of X.prefix)h7(W,Y);if(X.optionals)for(let Y of X.optionals)Iw(W,Y);if(X.variadic)qw(W,X.variadic);if(X.postfix)for(let Y of X.postfix)h7(W,Y);return W},PA=(W)=>`Spread element must be an array (was ${W})`,Cw="A tuple may have at most one variadic element",xA="A required element may not follow an optional element",jw="An optional element may not follow a variadic element";var vA="A defaultable element may not follow an optional element without a default";var bA={},Q9=(W,$)=>{if(typeof W==="string"){if($.args&&Object.keys($.args).some((Y)=>W.includes(Y)))return x7(W,$);let X=bA[$.$.name]??={};return X[W]??=x7(W,$)}return g1(W,"object")?yA(W,$):L(g7(Q1(W)))},yA=(W,$)=>{let X=E6(W);switch(X){case void 0:if(d(W,"root"))return W;return Aw(W,$);case"Array":return hA(W,$);case"RegExp":return $.$.node("intersection",{domain:"string",pattern:W},{prereduced:!0});case"Function":{let Y=b2(W)?W():W;if(d(Y,"root"))return Y;return L(g7("Function"))}default:return L(g7(X??X0(W)))}},hA=(W,$)=>Nw(W,$)??kw(W,$),g7=(W)=>`Type definitions must be strings or objects (was ${W})`;class m7 extends RW{constructor(W){let $=Object.assign({errors:p1,hkt:N1,$:W,raw:W.parse,module:W.constructor.module,scope:W.constructor.scope,define:W.define,match:W.match,generic:W.generic,schema:W.schema,keywords:W.ambient,unit:W.unit,enumerated:W.enumerated,instanceOf:W.instanceOf,valueOf:W.valueOf,or:W.or,and:W.and,merge:W.merge,pipe:W.pipe},W.ambientAttachments);super((...X)=>{if(X.length===1)return W.parse(X[0]);if(X.length===2&&typeof X[0]==="string"&&X[0][0]==="<"&&X[0].at(-1)===">"){let Y=X[0].slice(1,-1),J=W.parseGenericParams(Y,{});return new p2(J,X[1],W,W,null)}return W.parse(X)},{bind:W,attach:$})}}var v$=R;class z9 extends sY{get ambientAttachments(){if(!v$.typeAttachments)return;return this.cacheGetter("ambientAttachments",$0(v$.typeAttachments,(W,$)=>[W,this.bindReference($)]))}preparseOwnAliasEntry(W,$){let X=W.indexOf("<");if(X===-1){if(d($,"module")||d($,"generic"))return[W,$];let G=this.name==="ark"?W:W==="root"?this.name:`${this.name}.${W}`,H=this.resolvedConfig.keywords?.[G];if(H)$=[$,"@",H];return[W,$]}if(W.at(-1)!==">")L("'>' must be the last character of a generic declaration in a scope");let Y=W.slice(0,X),J=W.slice(X+1,-1);return[Y,()=>{let G=this.parseGenericParams(J,{alias:Y});return tT(G,$,this)}]}parseGenericParams(W,$){return G9(new w2(W),[],this.createParseContext({...$,def:W,prefix:"generic"}))}normalizeRootScopeValue(W){if(b2(W)&&!d(W,"generic"))return W();return W}preparseOwnDefinitionFormat(W,$){return{...$,def:W,prefix:$.alias??"type"}}parseOwnDefinitionFormat(W,$){if(!($.alias&&($.alias in this.aliases))&&!$.args)$.args={this:$.id};let Y=Q9(W,$);if(C0(Y)){if(Y[1]==="=")return L($9);if(Y[1]==="?")return L(W9)}return Y}unit=(W)=>this.units([W]);valueOf=(W)=>this.units(VT(W));enumerated=(...W)=>this.units(W);instanceOf=(W)=>this.node("proto",{proto:W},{prereduced:!0});or=(...W)=>this.schema(W.map(($)=>this.parse($)));and=(...W)=>W.reduce(($,X)=>$.and(this.parse(X)),this.intrinsic.unknown);merge=(...W)=>W.reduce(($,X)=>$.merge(this.parse(X)),this.intrinsic.object);pipe=(...W)=>this.intrinsic.unknown.pipe(...W);match=new v7(this);declare=()=>({type:this.type});define(W){return W}type=new m7(this);static scope=(W,$={})=>new z9(W,$);static module=(W,$={})=>this.scope(W,$).export()}var p7=Object.assign(z9.scope,{define:(W)=>W}),z0=z9;class fw extends N1{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var gA=UW(["base",r.object],["props",r.object])((W)=>W.base.merge(W.props),fw),Pw=z0.module({Key:r.key,Merge:gA});class xw extends N1{}var mA=UW("element")((W)=>{let $=W.element.exclude(r.Array),X=$.array();return $.rawOr(X).pipe(v2).distribute((Y)=>Y.assertHasKind("morph").declareOut(X),E0)},xw),vw=z0.module({root:r.Array,readonly:"root",index:r.nonNegativeIntegerString,liftFrom:mA},{name:"Array"});var u7=E0(["string",B8.FileConstructor]),pA=u7.rawOr(u7.array()),bw=E0({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:pA}}),yw=z0.module({root:["instanceof",FormData],value:u7,parsed:bw,parse:E0({in:FormData,morphs:(W)=>{let $={};for(let[X,Y]of W)if(X in $){let J=$[X];if(typeof J==="string"||J instanceof B8.FileConstructor)$[X]=[J,Y];else J.push(Y)}else $[X]=Y;return $},declaredOut:bw})},{name:"FormData"});var hw=z0.module({Int8:["instanceof",Int8Array],Uint8:["instanceof",Uint8Array],Uint8Clamped:["instanceof",Uint8ClampedArray],Int16:["instanceof",Int16Array],Uint16:["instanceof",Uint16Array],Int32:["instanceof",Int32Array],Uint32:["instanceof",Uint32Array],Float32:["instanceof",Float32Array],Float64:["instanceof",Float64Array],BigInt64:["instanceof",BigInt64Array],BigUint64:["instanceof",BigUint64Array]},{name:"TypedArray"});var uA={Boolean:1,Number:1,String:1},gw=z0.module({...$0({...C5,...I5},(W,$)=>(W in uA)?[]:[W,["instanceof",$]]),Array:vw,TypedArray:hw,FormData:yw});var cA=E0({domain:{domain:"number",meta:"a number representing a Unix timestamp"},divisor:{rule:1,meta:"an integer representing a Unix timestamp"},min:{rule:-8640000000000000,meta:"a Unix timestamp after -8640000000000000"},max:{rule:8640000000000000,meta:"a Unix timestamp before 8640000000000000"},meta:"an integer representing a safe Unix timestamp"}),dA=E0({domain:"number",divisor:1}),F9=z0.module({root:r.number,integer:dA,epoch:cA,safe:E0({domain:{domain:"number",numberAllowsNaN:!1},min:Number.MIN_SAFE_INTEGER,max:Number.MAX_SAFE_INTEGER}),NaN:["===",Number.NaN],Infinity:["===",Number.POSITIVE_INFINITY],NegativeInfinity:["===",Number.NEGATIVE_INFINITY]},{name:"number"});var h0=(W,$,X)=>{let Y={domain:"string",pattern:{rule:W.source,flags:W.flags,meta:$}};if(X)Y.meta={format:X};return f$("intersection",Y)},mw=h0(Z6,"a well-formed integer string"),sw=z0.module({root:mw,parse:E0({in:mw,morphs:(W,$)=>{let X=Number.parseInt(W);return Number.isSafeInteger(X)?X:$.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:r.integer})},{name:"string.integer"}),lA=h0(/^[\dA-Fa-f]+$/,"hex characters only"),oA=z0.module({root:h0(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:h0(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),pw=h0(/^[A-Z].*$/,"capitalized"),iA=z0.module({root:E0({in:"string",morphs:(W)=>W.charAt(0).toUpperCase()+W.slice(1),declaredOut:pw}),preformatted:pw},{name:"string.capitalize"}),nA=(W)=>{let $=W.replaceAll(/[ -]+/g,""),X=0,Y,J,G=!1;for(let H=$.length-1;H>=0;H--){if(Y=$.substring(H,H+1),J=Number.parseInt(Y,10),G)J*=2,X+=J>=10?J%10+1:J;else X+=J;G=!G}return!!(X%10===0?$:!1)},rA=/^(?:4\d{12}(?:\d{3,6})?|5[1-5]\d{14}|(222[1-9]|22[3-9]\d|2[3-6]\d{2}|27[01]\d|2720)\d{12}|6(?:011|5\d\d)\d{12,15}|3[47]\d{13}|3(?:0[0-5]|[68]\d)\d{11}|(?:2131|1800|35\d{3})\d{11}|6[27]\d{14}|^(81\d{14,17}))$/,tA=E0({domain:"string",pattern:{meta:"a credit card number",rule:rA.source},predicate:{meta:"a credit card number",predicate:nA}});var aA=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))(T((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([,.]\d+(?!:))?)?(\17[0-5]\d([,.]\d+)?)?([Zz]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;var sA=(W)=>!Number.isNaN(new Date(W).valueOf()),uw=E0({domain:"string",predicate:{meta:"a parsable date",predicate:sA}}).assertHasKind("intersection"),cw=sw.root.internal.narrow((W,$)=>{let X=Number.parseInt(W),Y=F9.epoch(X);if(Y instanceof p1)return $.errors.merge(Y),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),eA=z0.module({root:cw,parse:E0({in:cw,morphs:(W)=>new Date(W),declaredOut:r.Date})},{name:"string.date.epoch"}),dw=h0(aA,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),WE=z0.module({root:dw,parse:E0({in:dw,morphs:(W)=>new Date(W),declaredOut:r.Date})},{name:"string.date.iso"}),$E=z0.module({root:uw,parse:E0({declaredIn:uw,in:"string",morphs:(W,$)=>{let X=new Date(W);if(Number.isNaN(X.valueOf()))return $.error("a parsable date");return X},declaredOut:r.Date}),iso:WE,epoch:eA},{name:"string.date"}),XE=h0(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),lw="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",u2=`(${lw}[.]){3}${lw}`,YE=new RegExp(`^${u2}$`),a0="(?:[0-9a-fA-F]{1,4})",JE=new RegExp(`^((?:${a0}:){7}(?:${a0}|:)|(?:${a0}:){6}(?:${u2}|:${a0}|:)|(?:${a0}:){5}(?::${u2}|(:${a0}){1,2}|:)|(?:${a0}:){4}(?:(:${a0}){0,1}:${u2}|(:${a0}){1,3}|:)|(?:${a0}:){3}(?:(:${a0}){0,2}:${u2}|(:${a0}){1,4}|:)|(?:${a0}:){2}(?:(:${a0}){0,3}:${u2}|(:${a0}){1,5}|:)|(?:${a0}:){1}(?:(:${a0}){0,4}:${u2}|(:${a0}){1,6}|:)|(?::((?::${a0}){0,5}:${u2}|(?::${a0}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),GE=z0.module({root:["v4 | v6","@","an IP address"],v4:h0(YE,"an IPv4 address","ipv4"),v6:h0(JE,"an IPv6 address","ipv6")},{name:"string.ip"}),b$="a JSON string",ew=(W)=>{if(!(W instanceof SyntaxError))throw W;return`must be ${b$} (${W})`},HE=E0({meta:b$,domain:"string",predicate:{meta:b$,predicate:(W,$)=>{try{return JSON.parse(W),!0}catch(X){return $.reject({code:"predicate",expected:b$,problem:ew(X)})}}}}),QE=(W,$)=>{if(W.length===0)return $.error({code:"predicate",expected:b$,actual:"empty"});try{return JSON.parse(W)}catch(X){return $.error({code:"predicate",expected:b$,problem:ew(X)})}},zE=z0.module({root:HE,parse:E0({meta:"safe JSON string parser",in:"string",morphs:QE,declaredOut:r.jsonObject})},{name:"string.json"}),ow=h0(/^[a-z]*$/,"only lowercase letters"),FE=z0.module({root:E0({in:"string",morphs:(W)=>W.toLowerCase(),declaredOut:ow}),preformatted:ow},{name:"string.lower"}),WM=["NFC","NFD","NFKC","NFKD"],i6=$0(WM,(W,$)=>[$,E0({domain:"string",predicate:(X)=>X.normalize($)===X,meta:`${$}-normalized unicode`})]),T9=$0(WM,(W,$)=>[$,E0({in:"string",morphs:(X)=>X.normalize($),declaredOut:i6[$]})]),TE=z0.module({root:T9.NFC,preformatted:i6.NFC},{name:"string.normalize.NFC"}),UE=z0.module({root:T9.NFD,preformatted:i6.NFD},{name:"string.normalize.NFD"}),wE=z0.module({root:T9.NFKC,preformatted:i6.NFKC},{name:"string.normalize.NFKC"}),ME=z0.module({root:T9.NFKD,preformatted:i6.NFKD},{name:"string.normalize.NFKD"}),_E=z0.module({root:"NFC",NFC:TE,NFD:UE,NFKC:wE,NFKD:ME},{name:"string.normalize"}),iw=h0(yY,"a well-formed numeric string"),DE=z0.module({root:iw,parse:E0({in:iw,morphs:(W)=>Number.parseFloat(W),declaredOut:r.number})},{name:"string.numeric"}),nw="a regex pattern",VE=E0({domain:"string",predicate:{meta:nw,predicate:(W,$)=>{try{return new RegExp(W),!0}catch(X){return $.reject({code:"predicate",expected:nw,problem:String(X)})}}},meta:{format:"regex"}}),OE=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*))*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?$/,KE=h0(OE,"a semantic version (see https://semver.org/)"),rw=h0(/^\S.*\S$|^\S?$/,"trimmed"),LE=z0.module({root:E0({in:"string",morphs:(W)=>W.trim(),declaredOut:rw}),preformatted:rw},{name:"string.trim"}),tw=h0(/^[A-Z]*$/,"only uppercase letters"),AE=z0.module({root:E0({in:"string",morphs:(W)=>W.toUpperCase(),declaredOut:tw}),preformatted:tw},{name:"string.upper"}),EE=(W)=>{if(URL.canParse)return URL.canParse(W);try{return new URL(W),!0}catch{return!1}},aw=E0({domain:"string",predicate:{meta:"a URL string",predicate:EE},meta:{format:"uri"}}),NE=z0.module({root:aw,parse:E0({declaredIn:aw,in:"string",morphs:(W,$)=>{try{return new URL(W)}catch{return $.error("a URL string")}},declaredOut:E0(URL)})},{name:"string.url"}),BE=z0.module({root:["versioned | nil | max","@",{description:"a UUID",format:"uuid"}],"#nil":"'00000000-0000-0000-0000-000000000000'","#max":"'ffffffff-ffff-ffff-ffff-ffffffffffff'","#versioned":/[\da-f]{8}-[\da-f]{4}-[1-8][\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}/i,v1:h0(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:h0(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:h0(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:h0(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:h0(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:h0(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:h0(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:h0(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),$M=z0.module({root:r.string,alpha:h0(/^[A-Za-z]*$/,"only letters"),alphanumeric:h0(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:lA,base64:oA,capitalize:iA,creditCard:tA,date:$E,digits:h0(/^\d*$/,"only digits 0-9"),email:XE,integer:sw,ip:GE,json:zE,lower:FE,normalize:_E,numeric:DE,regex:VE,semver:KE,trim:LE,upper:AE,url:NE,uuid:BE},{name:"string"});var XM=z0.module({bigint:r.bigint,boolean:r.boolean,false:r.false,never:r.never,null:r.null,number:r.number,object:r.object,string:r.string,symbol:r.symbol,true:r.true,unknown:r.unknown,undefined:r.undefined}),YM=z0.module({root:r.unknown,any:r.unknown},{name:"unknown"}),RE=z0.module({root:r.jsonObject,stringify:f$("morph",{in:r.jsonObject,morphs:(W)=>JSON.stringify(W),declaredOut:r.string})},{name:"object.json"}),JM=z0.module({root:r.object,json:RE},{name:"object"});class GM extends N1{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var ZE=UW(["K",r.key],"V")((W)=>({domain:"object",index:{signature:W.K,value:W.V}}),GM);class HM extends N1{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var SE=UW(["T",r.object],["K",r.key])((W)=>W.T.pick(W.K),HM);class QM extends N1{description='omit a set of properties from an object like `Omit(User, "age")`'}var qE=UW(["T",r.object],["K",r.key])((W)=>W.T.omit(W.K),QM);class zM extends N1{description="make all named properties of an object optional like `Partial(User)`"}var CE=UW(["T",r.object])((W)=>W.T.partial(),zM);class FM extends N1{description="make all named properties of an object required like `Required(User)`"}var kE=UW(["T",r.object])((W)=>W.T.required(),FM);class TM extends N1{description='exclude branches of a union like `Exclude("boolean", "true")`'}var IE=UW("T","U")((W)=>W.T.exclude(W.U),TM);class UM extends N1{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var jE=UW("T","U")((W)=>W.T.extract(W.U),UM),wM=z0.module({Exclude:IE,Extract:jE,Omit:qE,Partial:CE,Pick:SE,Record:ZE,Required:kE});var c2=p7({...XM,...wM,...gw,...Pw,string:$M,number:F9,object:JM,unknown:YM},{prereducedAliases:!0,name:"ark"}),F1=c2.export();Object.assign(v$.ambient,F1);v$.typeAttachments={string:F1.string.root,number:F1.number.root,bigint:F1.bigint,boolean:F1.boolean,symbol:F1.symbol,undefined:F1.undefined,null:F1.null,object:F1.object.root,unknown:F1.unknown.root,false:F1.false,true:F1.true,never:F1.never,arrayIndex:F1.Array.index,Key:F1.Key,Record:F1.Record,Array:F1.Array.root,Date:F1.Date};var qW=Object.assign(c2.type,v$.typeAttachments),fE=c2.match,PE=c2.generic,Aa=c2.schema,xE=c2.define,vE=c2.declare;var bE="__vite_start_time"in globalThis,yE=typeof window!=="undefined",ha="vitest"in globalThis,M2=qW("string"),MM=qW('"true" | "false" | undefined'),_2=Z5({isServer:!bE&&!yE,server:{CI:qW("string | undefined").pipe(Boolean),POSTGRES_USER:M2,POSTGRES_PASSWORD:M2,POSTGRES_DATABASE:M2,POSTGRES_HOST:M2,POSTGRES_PORT:M2.pipe((W)=>Number.parseInt(W,10)),BACKEND_PORT:M2.pipe((W)=>Number.parseInt(W,10)),RUN_WORKERS_FROM_SOURCE:MM.pipe((W)=>W==="true"),FRONTEND_PORT:M2.pipe((W)=>Number.parseInt(W,10)),FRONTEND_ORIGINS:M2.pipe.try((W)=>JSON.parse(W),qW("string[]")),API_KEY_OPENAI:qW("string | undefined"),API_KEY_RESEND:qW("string | undefined")},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:M2,VITE_DEV_FRONTEND_HOST:qW("string | undefined"),VITE_DEV_HTTPS:MM.pipe((W)=>W==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var d7={};C_(d7,{users:()=>S8,untrackedUserColumnNames:()=>hE,twoFactorMethod:()=>KM,trackedUserColumnName:()=>gE,trackableUserColumnNames:()=>VM,signInHistory:()=>pE,role:()=>DM,players:()=>c7,passwordResetAttempts:()=>uE,games:()=>U9,banishedIps:()=>w9,accountActions:()=>mE,accountAction:()=>OM});function _M(W){return D`lower(${W})`}var DM=s4("role",["admin","user"]),S8=f2("users",{id:HW().primaryKey().defaultRandom(),username:k1({length:16}).notNull(),emailOffered:k1({length:254}).notNull(),emailVerified:k1({length:254}),password:k1({length:254}),createdAt:NW({withTimezone:!0}).notNull().defaultNow(),createdIp:k1({length:45}).notNull(),isActive:J6().notNull().default(!1),verifiedAt:NW({withTimezone:!0}),userRole:DM().default("user")},(W)=>[A5("usernameUniqueIndex").on(_M(W.username)),A5("emailVerifiedUniqueIndex").on(_M(W.emailVerified))]),hE=["id","createdAt","createdIp","isActive","verifiedAt"],VM=["username","emailOffered","emailVerified","password","userRole"],gE=s4("trackedUserColumnName",VM),OM=s4("accountAction",["cooldown","confirmEmail","signIn","resetPassword"]),mE=f2("accountActions",{userId:HW().references(()=>S8.id).primaryKey(),action:OM().notNull(),code:k1({length:254}).notNull(),wrongCodeCount:G6().notNull().default(0),expiresAt:NW({withTimezone:!0}).notNull()}),U9=f2("games",{id:HW().primaryKey().defaultRandom()}),c7=f2("players",{userId:HW().notNull().references(()=>S8.id,{onDelete:"cascade"}),gameId:HW().notNull().references(()=>U9.id,{onDelete:"cascade"}),score:G6().notNull()},(W)=>[GF({name:"players_userId_gameId_pk",columns:[W.userId,W.gameId]})]),pE=f2("signInHistory",{id:HW().primaryKey().defaultRandom(),userId:HW().references(()=>S8.id,{onDelete:"cascade"}),signInTime:NW({withTimezone:!0}).notNull().defaultNow(),ipAddress:k1({length:45}).notNull(),userAgent:k1({length:1024}),successful:J6().notNull().default(!1)}),KM=s4("twoFactorMethod",["email","phone"]),uE=f2("passwordResetAttempts",{id:HW().primaryKey().defaultRandom(),userId:HW().notNull().references(()=>S8.id,{onDelete:"cascade"}),requestedIp:k1({length:45}).notNull(),requestedAt:NW({withTimezone:!0}).notNull().defaultNow(),succeededIp:k1({length:45}),succeededAt:NW({withTimezone:!0}),verificationMethod:KM().notNull()}),w9=f2("banishedIps",{ip:k1({length:45}).primaryKey(),reason:k1({length:2048}).notNull(),banishedAt:NW({withTimezone:!0}).notNull().defaultNow(),banishedUntil:NW({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class l7{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(cE.resolve(__dirname,"notify_update.sql"));let W=[U1(S8),U1(U9),U1(c7)];await this.sql`SELECT create_notify_triggers(${this.sql.array(W)})`,await this.sql.listen("table_update",($)=>{let X=$.split(","),Y=X[0],J=X[1],G=`${Y}("${J}")`;if(this.observers.has(G))this.observers.get(G).next(G)})}constructor(W=!1,$={host:_2.POSTGRES_HOST,port:_2.POSTGRES_PORT,user:_2.POSTGRES_USER,password:_2.POSTGRES_PASSWORD,database:_2.POSTGRES_DATABASE}){this.options=$,this.sql=D$($),this.drizzle=vY(this.sql,{schema:d7,logger:W})}observe(W,$){if(!this.observers.has(W))this.observers.set(W,new Z0);this.observers.get(W).subscribe("SINGLETON",$)}}import{resolve as oE}from"path";import{existsSync as o7,mkdirSync as LM,readFileSync as dE,readdirSync as AM,rmSync as EM,statSync as NM,writeFileSync as lE}from"fs";import{resolve as i7}from"path";var BM=class{rootDir;get initialized(){return o7(this.rootDir)}initialize(){if(!this.initialized)LM(this.rootDir,{recursive:!0})}constructor(W){if(this.rootDir=W.path,W.eagerInit)this.initialize()}getItem(W){let $=i7(this.rootDir,W);if(o7($))return dE($,"utf-8");return null}setItem(W,$){this.initialize();let X=i7(this.rootDir,W);lE(X,$)}removeItem(W){let $=i7(this.rootDir,W);if(o7($))this.initialize(),EM($)}key(W){return AM(this.rootDir).sort((Y,J)=>{let G=NM(Y);return NM(J).ctimeMs-G.ctimeMs})[W]??null}clear(){EM(this.rootDir,{recursive:!0}),LM(this.rootDir,{recursive:!0})}get length(){return AM(this.rootDir).length}};var n7=new BM({path:oE(process.cwd(),"storage")});import*as M9 from"fs";import*as RM from"readline";function iE(W){let X=W.replace(":","T").replace(" ","").replace(/(\d{2})\/(\w{3})\/(\d{4})T(.+)/,(Y,J,G,H,Q)=>{let F={Jan:"01",Feb:"02",Mar:"03",Apr:"04",May:"05",Jun:"06",Jul:"07",Aug:"08",Sep:"09",Oct:"10",Nov:"11",Dec:"12"}[G];return`${H}-${F}-${J}T${Q}`});return new Date(X)}async function ZM(W,$="/var/log/nginx/access.log",X=new Date){let Y=new Map;if(!M9.existsSync($))return W.error(`Log file not found: ${$}`),Y;let J=M9.createReadStream($),G=RM.createInterface({input:J,crlfDelay:Number.POSITIVE_INFINITY}),H=new Date(X.getTime()-3600000);return G.on("line",(Q)=>{let z=/^(?<ip>\S+) \S+ \S+ \[(?<dateTime>.*?)\]/,F=Q.match(z);if(F?.groups){let T=F.groups.ip,U=F.groups.dateTime,M=iE(U);if(!Number.isNaN(M.getTime())){if(M>=H&&M<=X){let V=Y.get(T);if(!V)V=[],Y.set(T,V);V.push(Q)}}else W.error(`Failed to parse date: ${U}`)}}),new Promise((Q,z)=>{G.on("error",(F)=>{z(F)}),G.on("close",()=>{Q(Y)})})}function SM(W){return W.toJsonSchema()}var nE=["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(`
128
+ `);function qM(W){return nE+W.join(`
140
129
 
141
- `)}var JU={schema:k1([{shouldBanIp:"false"},"|",{shouldBanIp:"true",veryConciseReason:"string"}]),toJsonSchema:TU,fallback:{shouldBanIp:!1}};var CL=[".env","php"];async function WU({generator:T,logFilePath:$,logger:J,now:W=new Date}){let X=T.usdBudget,F=new l5({logQuery(y,V){J.info("\uD83D\uDCDD query",y,V)}}),Y=await eO(J,$,W),G=[],H=T.from(JU),M=0,z=0;for(let[y,V]of Y){J.info(`\uD83D\uDD0D ruling on ${y}. logs:`),J.info(V.map((C)=>` ${C}`).join(`
142
- `));let f=!1;for(let C of CL)if(V.some((B)=>B.includes(C))){G.push({ip:y,reason:`Always ban ${C}`}),J.info(` \uD83E\uDDD1\u200D\u2696\uFE0F banning ${y}--always ban ${C}
143
- `),f=!0;break}if(f)continue;if(T.usdBudget>T.usdMinimum){let C=$U(V),B=await H(C);if(B.shouldBanIp)G.push({ip:y,reason:B.veryConciseReason}),J.info(` \uD83E\uDDD1\u200D\u2696\uFE0F banning ${y}--${B.veryConciseReason}
144
- `);else z++,J.info(` \uD83D\uDD4A\uFE0F not banning ${y}
145
- `);M++}else{J.warn("\uD83D\uDCB0 insufficient funds to process all logs"),J.warn(`\uD83D\uDCB0 got through ${M}/${Y.size} ips
146
- `);break}}let A=G.length;if(G.length>0)await F.drizzle.insert(t6).values(G).onConflictDoNothing();let w=[],_=t5.getItem("lastTribunalProcessedDate"),D=new Date(_??"1970-01-01");try{w.push(...await F.drizzle.query.banishedIps.findMany({columns:{ip:!0},where:$6(t6.banishedAt,D)}))}catch(y){J.error(y)}try{if(process.env.EXPERIMENTAL_BAN_IPS)await Promise.all(w.map((y)=>new Promise((V,f)=>NL(`iptables -D INPUT -s ${y.ip} -j DROP`).on("exit",(C)=>{if(C===0)J.info(`\uD83E\uDDD1\u200D\u2696\uFE0F banned ${y.ip}`),V();else f(new Error(`iptables exited with code ${C}`))}))));else J.info("\uD83E\uDDD1\u200D\u2696\uFE0F skipping iptables update")}catch(y){if(y instanceof Error)J.error(y.message);else{let V=hW(y);J.error("iptables exited with error",V)}}t5.setItem("lastTribunalProcessedDate",W.toISOString()),J.info(`\u2728 banned ${A} ips, didn't ban ${z} ips`);let S=X-T.usdBudget,Z=S.toLocaleString("en",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:6}),q=X.toLocaleString("en",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:6}),N=Math.round(S/X*100);J.info(`\uD83D\uDCB8 spent ${Z}, ${N}% of ${q} budget`)}var j1=new EF;Object.assign(console,j1.logger,{log:j1.logger.info});process.on("SIGINT",()=>{j1.logger.info("\u2757 received SIGINT; exiting gracefully"),a6()});process.on("SIGTERM",()=>{j1.logger.info("\u2757 received SIGTERM; exiting gracefully"),a6()});process.on("exit",()=>{j1.logger.info("\u2757 received exit; exiting gracefully"),a6()});j1.logger.info("\uD83D\uDEEB tribunal worker ready");var ZL=new zH({usdBudget:0.01,usdMinimum:0,model:"gpt-4o-mini",apiKey:I1.OPENAI_API_KEY,cachingMode:"off",logger:j1.logger});if(I1.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 WU({generator:ZL,logFilePath:"/var/log/nginx/access.log",logger:j1.logger});a6();function a6(){j1.logger.info("\uD83D\uDEEC tribunal server exiting"),process.exit(0)}
130
+ `)}var CM={schema:qW([{shouldBanIp:"false"},"|",{shouldBanIp:"true",veryConciseReason:"string"}]),toJsonSchema:SM,fallback:{shouldBanIp:!1}};var tE=[".env","php"];async function kM({generator:W,logFilePath:$,logger:X,now:Y=new Date}){let J=W.usdBudget,G=new l7({logQuery(q,m){X.info("\uD83D\uDCDD query",q,m)}}),H=await ZM(X,$,Y),Q=[],z=W.from(CM),F=0,T=0;for(let[q,m]of H){X.info(`\uD83D\uDD0D ruling on ${q}. logs:`),X.info(m.map((v)=>` ${v}`).join(`
131
+ `));let c=!1;for(let v of tE)if(m.some((h)=>h.includes(v))){Q.push({ip:q,reason:`Always ban ${v}`}),X.info(` \uD83E\uDDD1\u200D\u2696\uFE0F banning ${q}--always ban ${v}
132
+ `),c=!0;break}if(c)continue;if(W.usdBudget>W.usdMinimum){let v=qM(m),h=await z(v);if(h.shouldBanIp)Q.push({ip:q,reason:h.veryConciseReason}),X.info(` \uD83E\uDDD1\u200D\u2696\uFE0F banning ${q}--${h.veryConciseReason}
133
+ `);else T++,X.info(` \uD83D\uDD4A\uFE0F not banning ${q}
134
+ `);F++}else{X.warn("\uD83D\uDCB0 insufficient funds to process all logs"),X.warn(`\uD83D\uDCB0 got through ${F}/${H.size} ips
135
+ `);break}}let U=Q.length;if(Q.length>0)await G.drizzle.insert(w9).values(Q).onConflictDoNothing();let M=[],V=n7.getItem("lastTribunalProcessedDate"),K=new Date(V??"1970-01-01");try{M.push(...await G.drizzle.query.banishedIps.findMany({columns:{ip:!0},where:KY(w9.banishedAt,K)}))}catch(q){X.error(q)}try{if(process.env.EXPERIMENTAL_BAN_IPS)await Promise.all(M.map((q)=>new Promise((m,c)=>rE(`iptables -D INPUT -s ${q.ip} -j DROP`).on("exit",(v)=>{if(v===0)X.info(`\uD83E\uDDD1\u200D\u2696\uFE0F banned ${q.ip}`),m();else c(new Error(`iptables exited with code ${v}`))}))));else X.info("\uD83E\uDDD1\u200D\u2696\uFE0F skipping iptables update")}catch(q){if(q instanceof Error)X.error(q.message);else{let m=mH(q);X.error("iptables exited with error",m)}}n7.setItem("lastTribunalProcessedDate",Y.toISOString()),X.info(`\u2728 banned ${U} ips, didn't ban ${T} ips`);let N=J-W.usdBudget,I=N.toLocaleString("en",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:6}),C=J.toLocaleString("en",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:6}),B=Math.round(N/J*100);X.info(`\uD83D\uDCB8 spent ${I}, ${B}% of ${C} budget`)}var D2=new k9;Object.assign(console,D2.logger,{log:D2.logger.info});process.on("SIGINT",()=>{D2.logger.info("\u2757 received SIGINT; exiting gracefully"),_9()});process.on("SIGTERM",()=>{D2.logger.info("\u2757 received SIGTERM; exiting gracefully"),_9()});process.on("exit",()=>{D2.logger.info("\u2757 received exit; exiting gracefully"),_9()});D2.logger.info("\uD83D\uDEEB tribunal worker ready");var aE=new gH({usdBudget:0.01,usdMinimum:0,model:"gpt-4o-mini",apiKey:_2.API_KEY_OPENAI,cachingMode:"off",logger:D2.logger});if(_2.API_KEY_OPENAI===void 0&&!("VITEST"in import.meta.env))throw new Error("OPENAI_API_KEY is not set and vitest is not running.");await kM({generator:aE,logFilePath:"/var/log/nginx/access.log",logger:D2.logger});_9();function _9(){D2.logger.info("\uD83D\uDEEC tribunal server exiting"),process.exit(0)}