orc-ai 0.1.4 → 0.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +88 -88
- package/package.json +63 -63
package/dist/index.js
CHANGED
|
@@ -1,38 +1,38 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var qV=Object.create;var{getPrototypeOf:SV,defineProperty:$G,getOwnPropertyNames:PO,getOwnPropertyDescriptor:kV}=Object,qO=Object.prototype.hasOwnProperty;function SO($){return this[$]}var bV,ZV,AJ=($,w,E)=>{var X=$!=null&&typeof $==="object";if(X){var G=w?bV??=new WeakMap:ZV??=new WeakMap,J=G.get($);if(J)return J}E=$!=null?qV(SV($)):{};let A=w||!$||!$.__esModule?$G(E,"default",{value:$,enumerable:!0}):E;for(let D of PO($))if(!qO.call(A,D))$G(A,D,{get:SO.bind($,D),enumerable:!0});if(X)G.set($,A);return A},kO=($)=>{var w=(VO??=new WeakMap).get($),E;if(w)return w;if(w=$G({},"__esModule",{value:!0}),$&&typeof $==="object"||typeof $==="function"){for(var X of PO($))if(!qO.call(w,X))$G(w,X,{get:SO.bind($,X),enumerable:!(E=kV($,X))||E.enumerable})}return VO.set($,w),w},VO,Z=($,w)=>()=>(w||$((w={exports:{}}).exports,w),w.exports);var CV=($)=>$;function _V($,w){this[$]=CV.bind(null,w)}var Ww=($,w)=>{for(var E in w)$G($,E,{get:w[E],enumerable:!0,configurable:!0,set:_V.bind(w,E)})};var R=($,w)=>()=>($&&(w=$($=0)),w);var V$=import.meta.require;var Y0,TD,f,o1=($)=>{switch(typeof $){case"undefined":return f.undefined;case"string":return f.string;case"number":return Number.isNaN($)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":if(Array.isArray($))return f.array;if($===null)return f.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return f.promise;if(typeof Map<"u"&&$ instanceof Map)return f.map;if(typeof Set<"u"&&$ instanceof Set)return f.set;if(typeof Date<"u"&&$ instanceof Date)return f.date;return f.object;default:return f.unknown}};var wG=R(()=>{(function($){$.assertEqual=(G)=>{};function w(G){}$.assertIs=w;function E(G){throw Error()}$.assertNever=E,$.arrayToEnum=(G)=>{let J={};for(let A of G)J[A]=A;return J},$.getValidEnumValues=(G)=>{let J=$.objectKeys(G).filter((D)=>typeof G[G[D]]!=="number"),A={};for(let D of J)A[D]=G[D];return $.objectValues(A)},$.objectValues=(G)=>{return $.objectKeys(G).map(function(J){return G[J]})},$.objectKeys=typeof Object.keys==="function"?(G)=>Object.keys(G):(G)=>{let J=[];for(let A in G)if(Object.prototype.hasOwnProperty.call(G,A))J.push(A);return J},$.find=(G,J)=>{for(let A of G)if(J(A))return A;return},$.isInteger=typeof Number.isInteger==="function"?(G)=>Number.isInteger(G):(G)=>typeof G==="number"&&Number.isFinite(G)&&Math.floor(G)===G;function X(G,J=" | "){return G.map((A)=>typeof A==="string"?`'${A}'`:A).join(J)}$.joinValues=X,$.jsonStringifyReplacer=(G,J)=>{if(typeof J==="bigint")return J.toString();return J}})(Y0||(Y0={}));(function($){$.mergeShapes=(w,E)=>{return{...w,...E}}})(TD||(TD={}));f=Y0.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"])});var _,vV=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")},r$;var DJ=R(()=>{wG();_=Y0.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"]);r$=class r$ extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(E)=>{this.issues=[...this.issues,E]},this.addIssues=(E=[])=>{this.issues=[...this.issues,...E]};let w=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,w);else this.__proto__=w;this.name="ZodError",this.issues=$}format($){let w=$||function(G){return G.message},E={_errors:[]},X=(G)=>{for(let J of G.issues)if(J.code==="invalid_union")J.unionErrors.map(X);else if(J.code==="invalid_return_type")X(J.returnTypeError);else if(J.code==="invalid_arguments")X(J.argumentsError);else if(J.path.length===0)E._errors.push(w(J));else{let A=E,D=0;while(D<J.path.length){let N=J.path[D];if(D!==J.path.length-1)A[N]=A[N]||{_errors:[]};else A[N]=A[N]||{_errors:[]},A[N]._errors.push(w(J));A=A[N],D++}}};return X(this),E}static assert($){if(!($ instanceof r$))throw Error(`Not a ZodError: ${$}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Y0.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten($=(w)=>w.message){let w={},E=[];for(let X of this.issues)if(X.path.length>0){let G=X.path[0];w[G]=w[G]||[],w[G].push($(X))}else E.push($(X));return{formErrors:E,fieldErrors:w}}get formErrors(){return this.flatten()}};r$.create=($)=>{return new r$($)}});var fV=($,w)=>{let E;switch($.code){case _.invalid_type:if($.received===f.undefined)E="Required";else E=`Expected ${$.expected}, received ${$.received}`;break;case _.invalid_literal:E=`Invalid literal value, expected ${JSON.stringify($.expected,Y0.jsonStringifyReplacer)}`;break;case _.unrecognized_keys:E=`Unrecognized key(s) in object: ${Y0.joinValues($.keys,", ")}`;break;case _.invalid_union:E="Invalid input";break;case _.invalid_union_discriminator:E=`Invalid discriminator value. Expected ${Y0.joinValues($.options)}`;break;case _.invalid_enum_value:E=`Invalid enum value. Expected ${Y0.joinValues($.options)}, received '${$.received}'`;break;case _.invalid_arguments:E="Invalid function arguments";break;case _.invalid_return_type:E="Invalid function return type";break;case _.invalid_date:E="Invalid date";break;case _.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(E=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")E=`${E} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)E=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)E=`Invalid input: must end with "${$.validation.endsWith}"`;else Y0.assertNever($.validation);else if($.validation!=="regex")E=`Invalid ${$.validation}`;else E="Invalid";break;case _.too_small:if($.type==="array")E=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")E=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")E=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="bigint")E=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")E=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else E="Invalid input";break;case _.too_big:if($.type==="array")E=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")E=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")E=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")E=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")E=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else E="Invalid input";break;case _.custom:E="Invalid input";break;case _.invalid_intersection_types:E="Intersection results could not be merged";break;case _.not_multiple_of:E=`Number must be a multiple of ${$.multipleOf}`;break;case _.not_finite:E="Number must be finite";break;default:E=w.defaultError,Y0.assertNever($)}return{message:E}},Ow;var BD=R(()=>{DJ();wG();Ow=fV});function xV($){bO=$}function fE(){return bO}var bO;var NJ=R(()=>{BD();bO=Ow});function g($,w){let E=fE(),X=EG({issueData:w,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,E,E===Ow?void 0:Ow].filter((G)=>!!G)});$.common.issues.push(X)}class j${constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,w){let E=[];for(let X of w){if(X.status==="aborted")return d;if(X.status==="dirty")$.dirty();E.push(X.value)}return{status:$.value,value:E}}static async mergeObjectAsync($,w){let E=[];for(let X of w){let G=await X.key,J=await X.value;E.push({key:G,value:J})}return j$.mergeObjectSync($,E)}static mergeObjectSync($,w){let E={};for(let X of w){let{key:G,value:J}=X;if(G.status==="aborted")return d;if(J.status==="aborted")return d;if(G.status==="dirty")$.dirty();if(J.status==="dirty")$.dirty();if(G.value!=="__proto__"&&(typeof J.value<"u"||X.alwaysSet))E[G.value]=J.value}return{status:$.value,value:E}}}var EG=($)=>{let{data:w,path:E,errorMaps:X,issueData:G}=$,J=[...E,...G.path||[]],A={...G,path:J};if(G.message!==void 0)return{...G,path:J,message:G.message};let D="",N=X.filter((W)=>!!W).slice().reverse();for(let W of N)D=W(A,{data:w,defaultError:D}).message;return{...G,path:J,message:D}},yV,d,AE=($)=>({status:"dirty",value:$}),P$=($)=>({status:"valid",value:$}),WJ=($)=>$.status==="aborted",OJ=($)=>$.status==="dirty",Zw=($)=>$.status==="valid",xE=($)=>typeof Promise<"u"&&$ instanceof Promise;var QD=R(()=>{NJ();BD();yV=[];d=Object.freeze({status:"aborted"})});var ZO=()=>{};var c;var CO=R(()=>{(function($){$.errToObj=(w)=>typeof w==="string"?{message:w}:w||{},$.toString=(w)=>typeof w==="string"?w:w?.message})(c||(c={}))});class S1{constructor($,w,E,X){this._cachedPath=[],this.parent=$,this.data=w,this._path=E,this._key=X}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}function X0($){if(!$)return{};let{errorMap:w,invalid_type_error:E,required_error:X,description:G}=$;if(w&&(E||X))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(w)return{errorMap:w,description:G};return{errorMap:(A,D)=>{let{message:N}=$;if(A.code==="invalid_enum_value")return{message:N??D.defaultError};if(typeof D.data>"u")return{message:N??X??D.defaultError};if(A.code!=="invalid_type")return{message:D.defaultError};return{message:N??E??D.defaultError}},description:G}}class G0{get description(){return this._def.description}_getType($){return o1($.data)}_getOrReturnCtx($,w){return w||{common:$.parent.common,data:$.data,parsedType:o1($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new j$,ctx:{common:$.parent.common,data:$.data,parsedType:o1($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let w=this._parse($);if(xE(w))throw Error("Synchronous parse encountered promise.");return w}_parseAsync($){let w=this._parse($);return Promise.resolve(w)}parse($,w){let E=this.safeParse($,w);if(E.success)return E.data;throw E.error}safeParse($,w){let E={common:{issues:[],async:w?.async??!1,contextualErrorMap:w?.errorMap},path:w?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:o1($)},X=this._parseSync({data:$,path:E.path,parent:E});return _O(E,X)}"~validate"($){let w={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:o1($)};if(!this["~standard"].async)try{let E=this._parseSync({data:$,path:[],parent:w});return Zw(E)?{value:E.value}:{issues:w.common.issues}}catch(E){if(E?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;w.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:w}).then((E)=>Zw(E)?{value:E.value}:{issues:w.common.issues})}async parseAsync($,w){let E=await this.safeParseAsync($,w);if(E.success)return E.data;throw E.error}async safeParseAsync($,w){let E={common:{issues:[],contextualErrorMap:w?.errorMap,async:!0},path:w?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:o1($)},X=this._parse({data:$,path:E.path,parent:E}),G=await(xE(X)?X:Promise.resolve(X));return _O(E,G)}refine($,w){let E=(X)=>{if(typeof w==="string"||typeof w>"u")return{message:w};else if(typeof w==="function")return w(X);else return w};return this._refinement((X,G)=>{let J=$(X),A=()=>G.addIssue({code:_.custom,...E(X)});if(typeof Promise<"u"&&J instanceof Promise)return J.then((D)=>{if(!D)return A(),!1;else return!0});if(!J)return A(),!1;else return!0})}refinement($,w){return this._refinement((E,X)=>{if(!$(E))return X.addIssue(typeof w==="function"?w(E,X):w),!1;else return!0})}_refinement($){return new k1({schema:this,typeName:a.ZodEffects,effect:{type:"refinement",refinement:$}})}superRefine($){return this._refinement($)}constructor($){this.spa=this.safeParseAsync,this._def=$,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:(w)=>this["~validate"](w)}}optional(){return q1.create(this,this._def)}nullable(){return Yw.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return P1.create(this)}promise(){return OE.create(this,this._def)}or($){return nE.create([this,$],this._def)}and($){return mE.create(this,$,this._def)}transform($){return new k1({...X0(this._def),schema:this,typeName:a.ZodEffects,effect:{type:"transform",transform:$}})}default($){let w=typeof $==="function"?$:()=>$;return new tE({...X0(this._def),innerType:this,defaultValue:w,typeName:a.ZodDefault})}brand(){return new YJ({typeName:a.ZodBranded,type:this,...X0(this._def)})}catch($){let w=typeof $==="function"?$:()=>$;return new iE({...X0(this._def),innerType:this,catchValue:w,typeName:a.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return NG.create(this,$)}readonly(){return dE.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}function xO($){let w="[0-5]\\d";if($.precision)w=`${w}\\.\\d{${$.precision}}`;else if($.precision==null)w=`${w}(\\.\\d+)?`;let E=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${w})${E}`}function $P($){return new RegExp(`^${xO($)}$`)}function yO($){let w=`${fO}T${xO($)}`,E=[];if(E.push($.local?"Z?":"Z"),$.offset)E.push("([+-]\\d{2}:?\\d{2})");return w=`${w}(${E.join("|")})`,new RegExp(`^${w}$`)}function wP($,w){if((w==="v4"||!w)&&tV.test($))return!0;if((w==="v6"||!w)&&dV.test($))return!0;return!1}function EP($,w){if(!mV.test($))return!1;try{let[E]=$.split(".");if(!E)return!1;let X=E.replace(/-/g,"+").replace(/_/g,"/").padEnd(E.length+(4-E.length%4)%4,"="),G=JSON.parse(atob(X));if(typeof G!=="object"||G===null)return!1;if("typ"in G&&G?.typ!=="JWT")return!1;if(!G.alg)return!1;if(w&&G.alg!==w)return!1;return!0}catch{return!1}}function XP($,w){if((w==="v4"||!w)&&iV.test($))return!0;if((w==="v6"||!w)&&lV.test($))return!0;return!1}function GP($,w){let E=($.toString().split(".")[1]||"").length,X=(w.toString().split(".")[1]||"").length,G=E>X?E:X,J=Number.parseInt($.toFixed(G).replace(".","")),A=Number.parseInt(w.toFixed(G).replace(".",""));return J%A/10**G}function yE($){if($ instanceof l0){let w={};for(let E in $.shape){let X=$.shape[E];w[E]=q1.create(yE(X))}return new l0({...$._def,shape:()=>w})}else if($ instanceof P1)return new P1({...$._def,type:yE($.element)});else if($ instanceof q1)return q1.create(yE($.unwrap()));else if($ instanceof Yw)return Yw.create(yE($.unwrap()));else if($ instanceof i1)return i1.create($.items.map((w)=>yE(w)));else return $}function KD($,w){let E=o1($),X=o1(w);if($===w)return{valid:!0,data:$};else if(E===f.object&&X===f.object){let G=Y0.objectKeys(w),J=Y0.objectKeys($).filter((D)=>G.indexOf(D)!==-1),A={...$,...w};for(let D of J){let N=KD($[D],w[D]);if(!N.valid)return{valid:!1};A[D]=N.data}return{valid:!0,data:A}}else if(E===f.array&&X===f.array){if($.length!==w.length)return{valid:!1};let G=[];for(let J=0;J<$.length;J++){let A=$[J],D=w[J],N=KD(A,D);if(!N.valid)return{valid:!1};G.push(N.data)}return{valid:!0,data:G}}else if(E===f.date&&X===f.date&&+$===+w)return{valid:!0,data:$};else return{valid:!1}}function gO($,w){return new fw({values:$,typeName:a.ZodEnum,...X0(w)})}function vO($,w){let E=typeof $==="function"?$(w):typeof $==="string"?{message:$}:$;return typeof E==="string"?{message:E}:E}function uO($,w={},E){if($)return NE.create().superRefine((X,G)=>{let J=$(X);if(J instanceof Promise)return J.then((A)=>{if(!A){let D=vO(w,X),N=D.fatal??E??!0;G.addIssue({code:"custom",...D,fatal:N})}});if(!J){let A=vO(w,X),D=A.fatal??E??!0;G.addIssue({code:"custom",...A,fatal:D})}return});return NE.create()}var _O=($,w)=>{if(Zw(w))return{success:!0,data:w.value};else{if(!$.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let E=new r$($.common.issues);return this._error=E,this._error}}}},gV,uV,hV,cV,nV,mV,rV,pV,oV="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ID,tV,iV,dV,lV,sV,aV,fO="((\\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])))",eV,V1,_w,vw,uE,DE,XG,hE,cE,NE,Cw,t1,GG,P1,l0,nE,Uw=($)=>{if($ instanceof rE)return Uw($.schema);else if($ instanceof k1)return Uw($.innerType());else if($ instanceof pE)return[$.value];else if($ instanceof fw)return $.options;else if($ instanceof oE)return Y0.objectValues($.enum);else if($ instanceof tE)return Uw($._def.innerType);else if($ instanceof hE)return[void 0];else if($ instanceof cE)return[null];else if($ instanceof q1)return[void 0,...Uw($.unwrap())];else if($ instanceof Yw)return[null,...Uw($.unwrap())];else if($ instanceof YJ)return Uw($.unwrap());else if($ instanceof dE)return Uw($.unwrap());else if($ instanceof iE)return Uw($._def.innerType);else return[]},UJ,mE,i1,JG,AG,WE,gE,rE,pE,fw,oE,OE,k1,q1,Yw,tE,iE,DG,JP,YJ,NG,dE,AP,a,DP=($,w={message:`Input not instance of ${$.name}`})=>uO((E)=>E instanceof $,w),hO,cO,NP,WP,nO,OP,UP,YP,HP,LP,FP,jP,MP,RP,zP,TP,BP,QP,IP,KP,VP,PP,qP,SP,kP,bP,ZP,CP,_P,vP,fP,xP,yP,gP,uP=()=>hO().optional(),hP=()=>cO().optional(),cP=()=>nO().optional(),nP,mP;var mO=R(()=>{DJ();NJ();CO();QD();wG();gV=/^c[^\s-]{8,}$/i,uV=/^[0-9a-z]+$/,hV=/^[0-9A-HJKMNP-TV-Z]{26}$/i,cV=/^[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,nV=/^[a-z0-9_-]{21}$/i,mV=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,rV=/^[-+]?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)?)??$/,pV=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,tV=/^(?:(?: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])$/,iV=/^(?:(?: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])$/,dV=/^(([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]))$/,lV=/^(([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])$/,sV=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,aV=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,eV=new RegExp(`^${fO}$`);V1=class V1 extends G0{_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==f.string){let G=this._getOrReturnCtx($);return g(G,{code:_.invalid_type,expected:f.string,received:G.parsedType}),d}let E=new j$,X=void 0;for(let G of this._def.checks)if(G.kind==="min"){if($.data.length<G.value)X=this._getOrReturnCtx($,X),g(X,{code:_.too_small,minimum:G.value,type:"string",inclusive:!0,exact:!1,message:G.message}),E.dirty()}else if(G.kind==="max"){if($.data.length>G.value)X=this._getOrReturnCtx($,X),g(X,{code:_.too_big,maximum:G.value,type:"string",inclusive:!0,exact:!1,message:G.message}),E.dirty()}else if(G.kind==="length"){let J=$.data.length>G.value,A=$.data.length<G.value;if(J||A){if(X=this._getOrReturnCtx($,X),J)g(X,{code:_.too_big,maximum:G.value,type:"string",inclusive:!0,exact:!0,message:G.message});else if(A)g(X,{code:_.too_small,minimum:G.value,type:"string",inclusive:!0,exact:!0,message:G.message});E.dirty()}}else if(G.kind==="email"){if(!pV.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"email",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="emoji"){if(!ID)ID=new RegExp(oV,"u");if(!ID.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"emoji",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="uuid"){if(!cV.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"uuid",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="nanoid"){if(!nV.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"nanoid",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="cuid"){if(!gV.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"cuid",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="cuid2"){if(!uV.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"cuid2",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="ulid"){if(!hV.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"ulid",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="url")try{new URL($.data)}catch{X=this._getOrReturnCtx($,X),g(X,{validation:"url",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="regex"){if(G.regex.lastIndex=0,!G.regex.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"regex",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="trim")$.data=$.data.trim();else if(G.kind==="includes"){if(!$.data.includes(G.value,G.position))X=this._getOrReturnCtx($,X),g(X,{code:_.invalid_string,validation:{includes:G.value,position:G.position},message:G.message}),E.dirty()}else if(G.kind==="toLowerCase")$.data=$.data.toLowerCase();else if(G.kind==="toUpperCase")$.data=$.data.toUpperCase();else if(G.kind==="startsWith"){if(!$.data.startsWith(G.value))X=this._getOrReturnCtx($,X),g(X,{code:_.invalid_string,validation:{startsWith:G.value},message:G.message}),E.dirty()}else if(G.kind==="endsWith"){if(!$.data.endsWith(G.value))X=this._getOrReturnCtx($,X),g(X,{code:_.invalid_string,validation:{endsWith:G.value},message:G.message}),E.dirty()}else if(G.kind==="datetime"){if(!yO(G).test($.data))X=this._getOrReturnCtx($,X),g(X,{code:_.invalid_string,validation:"datetime",message:G.message}),E.dirty()}else if(G.kind==="date"){if(!eV.test($.data))X=this._getOrReturnCtx($,X),g(X,{code:_.invalid_string,validation:"date",message:G.message}),E.dirty()}else if(G.kind==="time"){if(!$P(G).test($.data))X=this._getOrReturnCtx($,X),g(X,{code:_.invalid_string,validation:"time",message:G.message}),E.dirty()}else if(G.kind==="duration"){if(!rV.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"duration",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="ip"){if(!wP($.data,G.version))X=this._getOrReturnCtx($,X),g(X,{validation:"ip",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="jwt"){if(!EP($.data,G.alg))X=this._getOrReturnCtx($,X),g(X,{validation:"jwt",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="cidr"){if(!XP($.data,G.version))X=this._getOrReturnCtx($,X),g(X,{validation:"cidr",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="base64"){if(!sV.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"base64",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="base64url"){if(!aV.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"base64url",code:_.invalid_string,message:G.message}),E.dirty()}else Y0.assertNever(G);return{status:E.value,value:$.data}}_regex($,w,E){return this.refinement((X)=>$.test(X),{validation:w,code:_.invalid_string,...c.errToObj(E)})}_addCheck($){return new V1({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...c.errToObj($)})}url($){return this._addCheck({kind:"url",...c.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...c.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...c.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...c.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...c.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...c.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...c.errToObj($)})}base64($){return this._addCheck({kind:"base64",...c.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...c.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...c.errToObj($)})}ip($){return this._addCheck({kind:"ip",...c.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...c.errToObj($)})}datetime($){if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof $?.precision>"u"?null:$?.precision,offset:$?.offset??!1,local:$?.local??!1,...c.errToObj($?.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof $?.precision>"u"?null:$?.precision,...c.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...c.errToObj($)})}regex($,w){return this._addCheck({kind:"regex",regex:$,...c.errToObj(w)})}includes($,w){return this._addCheck({kind:"includes",value:$,position:w?.position,...c.errToObj(w?.message)})}startsWith($,w){return this._addCheck({kind:"startsWith",value:$,...c.errToObj(w)})}endsWith($,w){return this._addCheck({kind:"endsWith",value:$,...c.errToObj(w)})}min($,w){return this._addCheck({kind:"min",value:$,...c.errToObj(w)})}max($,w){return this._addCheck({kind:"max",value:$,...c.errToObj(w)})}length($,w){return this._addCheck({kind:"length",value:$,...c.errToObj(w)})}nonempty($){return this.min(1,c.errToObj($))}trim(){return new V1({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new V1({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new V1({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(($)=>$.kind==="datetime")}get isDate(){return!!this._def.checks.find(($)=>$.kind==="date")}get isTime(){return!!this._def.checks.find(($)=>$.kind==="time")}get isDuration(){return!!this._def.checks.find(($)=>$.kind==="duration")}get isEmail(){return!!this._def.checks.find(($)=>$.kind==="email")}get isURL(){return!!this._def.checks.find(($)=>$.kind==="url")}get isEmoji(){return!!this._def.checks.find(($)=>$.kind==="emoji")}get isUUID(){return!!this._def.checks.find(($)=>$.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(($)=>$.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(($)=>$.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(($)=>$.kind==="cuid2")}get isULID(){return!!this._def.checks.find(($)=>$.kind==="ulid")}get isIP(){return!!this._def.checks.find(($)=>$.kind==="ip")}get isCIDR(){return!!this._def.checks.find(($)=>$.kind==="cidr")}get isBase64(){return!!this._def.checks.find(($)=>$.kind==="base64")}get isBase64url(){return!!this._def.checks.find(($)=>$.kind==="base64url")}get minLength(){let $=null;for(let w of this._def.checks)if(w.kind==="min"){if($===null||w.value>$)$=w.value}return $}get maxLength(){let $=null;for(let w of this._def.checks)if(w.kind==="max"){if($===null||w.value<$)$=w.value}return $}};V1.create=($)=>{return new V1({checks:[],typeName:a.ZodString,coerce:$?.coerce??!1,...X0($)})};_w=class _w extends G0{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse($){if(this._def.coerce)$.data=Number($.data);if(this._getType($)!==f.number){let G=this._getOrReturnCtx($);return g(G,{code:_.invalid_type,expected:f.number,received:G.parsedType}),d}let E=void 0,X=new j$;for(let G of this._def.checks)if(G.kind==="int"){if(!Y0.isInteger($.data))E=this._getOrReturnCtx($,E),g(E,{code:_.invalid_type,expected:"integer",received:"float",message:G.message}),X.dirty()}else if(G.kind==="min"){if(G.inclusive?$.data<G.value:$.data<=G.value)E=this._getOrReturnCtx($,E),g(E,{code:_.too_small,minimum:G.value,type:"number",inclusive:G.inclusive,exact:!1,message:G.message}),X.dirty()}else if(G.kind==="max"){if(G.inclusive?$.data>G.value:$.data>=G.value)E=this._getOrReturnCtx($,E),g(E,{code:_.too_big,maximum:G.value,type:"number",inclusive:G.inclusive,exact:!1,message:G.message}),X.dirty()}else if(G.kind==="multipleOf"){if(GP($.data,G.value)!==0)E=this._getOrReturnCtx($,E),g(E,{code:_.not_multiple_of,multipleOf:G.value,message:G.message}),X.dirty()}else if(G.kind==="finite"){if(!Number.isFinite($.data))E=this._getOrReturnCtx($,E),g(E,{code:_.not_finite,message:G.message}),X.dirty()}else Y0.assertNever(G);return{status:X.value,value:$.data}}gte($,w){return this.setLimit("min",$,!0,c.toString(w))}gt($,w){return this.setLimit("min",$,!1,c.toString(w))}lte($,w){return this.setLimit("max",$,!0,c.toString(w))}lt($,w){return this.setLimit("max",$,!1,c.toString(w))}setLimit($,w,E,X){return new _w({...this._def,checks:[...this._def.checks,{kind:$,value:w,inclusive:E,message:c.toString(X)}]})}_addCheck($){return new _w({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:c.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:c.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:c.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:c.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:c.toString($)})}multipleOf($,w){return this._addCheck({kind:"multipleOf",value:$,message:c.toString(w)})}finite($){return this._addCheck({kind:"finite",message:c.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:c.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:c.toString($)})}get minValue(){let $=null;for(let w of this._def.checks)if(w.kind==="min"){if($===null||w.value>$)$=w.value}return $}get maxValue(){let $=null;for(let w of this._def.checks)if(w.kind==="max"){if($===null||w.value<$)$=w.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&Y0.isInteger($.value))}get isFinite(){let $=null,w=null;for(let E of this._def.checks)if(E.kind==="finite"||E.kind==="int"||E.kind==="multipleOf")return!0;else if(E.kind==="min"){if(w===null||E.value>w)w=E.value}else if(E.kind==="max"){if($===null||E.value<$)$=E.value}return Number.isFinite(w)&&Number.isFinite($)}};_w.create=($)=>{return new _w({checks:[],typeName:a.ZodNumber,coerce:$?.coerce||!1,...X0($)})};vw=class vw extends G0{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch{return this._getInvalidInput($)}if(this._getType($)!==f.bigint)return this._getInvalidInput($);let E=void 0,X=new j$;for(let G of this._def.checks)if(G.kind==="min"){if(G.inclusive?$.data<G.value:$.data<=G.value)E=this._getOrReturnCtx($,E),g(E,{code:_.too_small,type:"bigint",minimum:G.value,inclusive:G.inclusive,message:G.message}),X.dirty()}else if(G.kind==="max"){if(G.inclusive?$.data>G.value:$.data>=G.value)E=this._getOrReturnCtx($,E),g(E,{code:_.too_big,type:"bigint",maximum:G.value,inclusive:G.inclusive,message:G.message}),X.dirty()}else if(G.kind==="multipleOf"){if($.data%G.value!==BigInt(0))E=this._getOrReturnCtx($,E),g(E,{code:_.not_multiple_of,multipleOf:G.value,message:G.message}),X.dirty()}else Y0.assertNever(G);return{status:X.value,value:$.data}}_getInvalidInput($){let w=this._getOrReturnCtx($);return g(w,{code:_.invalid_type,expected:f.bigint,received:w.parsedType}),d}gte($,w){return this.setLimit("min",$,!0,c.toString(w))}gt($,w){return this.setLimit("min",$,!1,c.toString(w))}lte($,w){return this.setLimit("max",$,!0,c.toString(w))}lt($,w){return this.setLimit("max",$,!1,c.toString(w))}setLimit($,w,E,X){return new vw({...this._def,checks:[...this._def.checks,{kind:$,value:w,inclusive:E,message:c.toString(X)}]})}_addCheck($){return new vw({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:c.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:c.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:c.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:c.toString($)})}multipleOf($,w){return this._addCheck({kind:"multipleOf",value:$,message:c.toString(w)})}get minValue(){let $=null;for(let w of this._def.checks)if(w.kind==="min"){if($===null||w.value>$)$=w.value}return $}get maxValue(){let $=null;for(let w of this._def.checks)if(w.kind==="max"){if($===null||w.value<$)$=w.value}return $}};vw.create=($)=>{return new vw({checks:[],typeName:a.ZodBigInt,coerce:$?.coerce??!1,...X0($)})};uE=class uE extends G0{_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==f.boolean){let E=this._getOrReturnCtx($);return g(E,{code:_.invalid_type,expected:f.boolean,received:E.parsedType}),d}return P$($.data)}};uE.create=($)=>{return new uE({typeName:a.ZodBoolean,coerce:$?.coerce||!1,...X0($)})};DE=class DE extends G0{_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==f.date){let G=this._getOrReturnCtx($);return g(G,{code:_.invalid_type,expected:f.date,received:G.parsedType}),d}if(Number.isNaN($.data.getTime())){let G=this._getOrReturnCtx($);return g(G,{code:_.invalid_date}),d}let E=new j$,X=void 0;for(let G of this._def.checks)if(G.kind==="min"){if($.data.getTime()<G.value)X=this._getOrReturnCtx($,X),g(X,{code:_.too_small,message:G.message,inclusive:!0,exact:!1,minimum:G.value,type:"date"}),E.dirty()}else if(G.kind==="max"){if($.data.getTime()>G.value)X=this._getOrReturnCtx($,X),g(X,{code:_.too_big,message:G.message,inclusive:!0,exact:!1,maximum:G.value,type:"date"}),E.dirty()}else Y0.assertNever(G);return{status:E.value,value:new Date($.data.getTime())}}_addCheck($){return new DE({...this._def,checks:[...this._def.checks,$]})}min($,w){return this._addCheck({kind:"min",value:$.getTime(),message:c.toString(w)})}max($,w){return this._addCheck({kind:"max",value:$.getTime(),message:c.toString(w)})}get minDate(){let $=null;for(let w of this._def.checks)if(w.kind==="min"){if($===null||w.value>$)$=w.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let w of this._def.checks)if(w.kind==="max"){if($===null||w.value<$)$=w.value}return $!=null?new Date($):null}};DE.create=($)=>{return new DE({checks:[],coerce:$?.coerce||!1,typeName:a.ZodDate,...X0($)})};XG=class XG extends G0{_parse($){if(this._getType($)!==f.symbol){let E=this._getOrReturnCtx($);return g(E,{code:_.invalid_type,expected:f.symbol,received:E.parsedType}),d}return P$($.data)}};XG.create=($)=>{return new XG({typeName:a.ZodSymbol,...X0($)})};hE=class hE extends G0{_parse($){if(this._getType($)!==f.undefined){let E=this._getOrReturnCtx($);return g(E,{code:_.invalid_type,expected:f.undefined,received:E.parsedType}),d}return P$($.data)}};hE.create=($)=>{return new hE({typeName:a.ZodUndefined,...X0($)})};cE=class cE extends G0{_parse($){if(this._getType($)!==f.null){let E=this._getOrReturnCtx($);return g(E,{code:_.invalid_type,expected:f.null,received:E.parsedType}),d}return P$($.data)}};cE.create=($)=>{return new cE({typeName:a.ZodNull,...X0($)})};NE=class NE extends G0{constructor(){super(...arguments);this._any=!0}_parse($){return P$($.data)}};NE.create=($)=>{return new NE({typeName:a.ZodAny,...X0($)})};Cw=class Cw extends G0{constructor(){super(...arguments);this._unknown=!0}_parse($){return P$($.data)}};Cw.create=($)=>{return new Cw({typeName:a.ZodUnknown,...X0($)})};t1=class t1 extends G0{_parse($){let w=this._getOrReturnCtx($);return g(w,{code:_.invalid_type,expected:f.never,received:w.parsedType}),d}};t1.create=($)=>{return new t1({typeName:a.ZodNever,...X0($)})};GG=class GG extends G0{_parse($){if(this._getType($)!==f.undefined){let E=this._getOrReturnCtx($);return g(E,{code:_.invalid_type,expected:f.void,received:E.parsedType}),d}return P$($.data)}};GG.create=($)=>{return new GG({typeName:a.ZodVoid,...X0($)})};P1=class P1 extends G0{_parse($){let{ctx:w,status:E}=this._processInputParams($),X=this._def;if(w.parsedType!==f.array)return g(w,{code:_.invalid_type,expected:f.array,received:w.parsedType}),d;if(X.exactLength!==null){let J=w.data.length>X.exactLength.value,A=w.data.length<X.exactLength.value;if(J||A)g(w,{code:J?_.too_big:_.too_small,minimum:A?X.exactLength.value:void 0,maximum:J?X.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:X.exactLength.message}),E.dirty()}if(X.minLength!==null){if(w.data.length<X.minLength.value)g(w,{code:_.too_small,minimum:X.minLength.value,type:"array",inclusive:!0,exact:!1,message:X.minLength.message}),E.dirty()}if(X.maxLength!==null){if(w.data.length>X.maxLength.value)g(w,{code:_.too_big,maximum:X.maxLength.value,type:"array",inclusive:!0,exact:!1,message:X.maxLength.message}),E.dirty()}if(w.common.async)return Promise.all([...w.data].map((J,A)=>{return X.type._parseAsync(new S1(w,J,w.path,A))})).then((J)=>{return j$.mergeArray(E,J)});let G=[...w.data].map((J,A)=>{return X.type._parseSync(new S1(w,J,w.path,A))});return j$.mergeArray(E,G)}get element(){return this._def.type}min($,w){return new P1({...this._def,minLength:{value:$,message:c.toString(w)}})}max($,w){return new P1({...this._def,maxLength:{value:$,message:c.toString(w)}})}length($,w){return new P1({...this._def,exactLength:{value:$,message:c.toString(w)}})}nonempty($){return this.min(1,$)}};P1.create=($,w)=>{return new P1({type:$,minLength:null,maxLength:null,exactLength:null,typeName:a.ZodArray,...X0(w)})};l0=class l0 extends G0{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let $=this._def.shape(),w=Y0.objectKeys($);return this._cached={shape:$,keys:w},this._cached}_parse($){if(this._getType($)!==f.object){let N=this._getOrReturnCtx($);return g(N,{code:_.invalid_type,expected:f.object,received:N.parsedType}),d}let{status:E,ctx:X}=this._processInputParams($),{shape:G,keys:J}=this._getCached(),A=[];if(!(this._def.catchall instanceof t1&&this._def.unknownKeys==="strip")){for(let N in X.data)if(!J.includes(N))A.push(N)}let D=[];for(let N of J){let W=G[N],O=X.data[N];D.push({key:{status:"valid",value:N},value:W._parse(new S1(X,O,X.path,N)),alwaysSet:N in X.data})}if(this._def.catchall instanceof t1){let N=this._def.unknownKeys;if(N==="passthrough")for(let W of A)D.push({key:{status:"valid",value:W},value:{status:"valid",value:X.data[W]}});else if(N==="strict"){if(A.length>0)g(X,{code:_.unrecognized_keys,keys:A}),E.dirty()}else if(N==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let N=this._def.catchall;for(let W of A){let O=X.data[W];D.push({key:{status:"valid",value:W},value:N._parse(new S1(X,O,X.path,W)),alwaysSet:W in X.data})}}if(X.common.async)return Promise.resolve().then(async()=>{let N=[];for(let W of D){let O=await W.key,Y=await W.value;N.push({key:O,value:Y,alwaysSet:W.alwaysSet})}return N}).then((N)=>{return j$.mergeObjectSync(E,N)});else return j$.mergeObjectSync(E,D)}get shape(){return this._def.shape()}strict($){return c.errToObj,new l0({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(w,E)=>{let X=this._def.errorMap?.(w,E).message??E.defaultError;if(w.code==="unrecognized_keys")return{message:c.errToObj($).message??X};return{message:X}}}:{}})}strip(){return new l0({...this._def,unknownKeys:"strip"})}passthrough(){return new l0({...this._def,unknownKeys:"passthrough"})}extend($){return new l0({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new l0({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:a.ZodObject})}setKey($,w){return this.augment({[$]:w})}catchall($){return new l0({...this._def,catchall:$})}pick($){let w={};for(let E of Y0.objectKeys($))if($[E]&&this.shape[E])w[E]=this.shape[E];return new l0({...this._def,shape:()=>w})}omit($){let w={};for(let E of Y0.objectKeys(this.shape))if(!$[E])w[E]=this.shape[E];return new l0({...this._def,shape:()=>w})}deepPartial(){return yE(this)}partial($){let w={};for(let E of Y0.objectKeys(this.shape)){let X=this.shape[E];if($&&!$[E])w[E]=X;else w[E]=X.optional()}return new l0({...this._def,shape:()=>w})}required($){let w={};for(let E of Y0.objectKeys(this.shape))if($&&!$[E])w[E]=this.shape[E];else{let G=this.shape[E];while(G instanceof q1)G=G._def.innerType;w[E]=G}return new l0({...this._def,shape:()=>w})}keyof(){return gO(Y0.objectKeys(this.shape))}};l0.create=($,w)=>{return new l0({shape:()=>$,unknownKeys:"strip",catchall:t1.create(),typeName:a.ZodObject,...X0(w)})};l0.strictCreate=($,w)=>{return new l0({shape:()=>$,unknownKeys:"strict",catchall:t1.create(),typeName:a.ZodObject,...X0(w)})};l0.lazycreate=($,w)=>{return new l0({shape:$,unknownKeys:"strip",catchall:t1.create(),typeName:a.ZodObject,...X0(w)})};nE=class nE extends G0{_parse($){let{ctx:w}=this._processInputParams($),E=this._def.options;function X(G){for(let A of G)if(A.result.status==="valid")return A.result;for(let A of G)if(A.result.status==="dirty")return w.common.issues.push(...A.ctx.common.issues),A.result;let J=G.map((A)=>new r$(A.ctx.common.issues));return g(w,{code:_.invalid_union,unionErrors:J}),d}if(w.common.async)return Promise.all(E.map(async(G)=>{let J={...w,common:{...w.common,issues:[]},parent:null};return{result:await G._parseAsync({data:w.data,path:w.path,parent:J}),ctx:J}})).then(X);else{let G=void 0,J=[];for(let D of E){let N={...w,common:{...w.common,issues:[]},parent:null},W=D._parseSync({data:w.data,path:w.path,parent:N});if(W.status==="valid")return W;else if(W.status==="dirty"&&!G)G={result:W,ctx:N};if(N.common.issues.length)J.push(N.common.issues)}if(G)return w.common.issues.push(...G.ctx.common.issues),G.result;let A=J.map((D)=>new r$(D));return g(w,{code:_.invalid_union,unionErrors:A}),d}}get options(){return this._def.options}};nE.create=($,w)=>{return new nE({options:$,typeName:a.ZodUnion,...X0(w)})};UJ=class UJ extends G0{_parse($){let{ctx:w}=this._processInputParams($);if(w.parsedType!==f.object)return g(w,{code:_.invalid_type,expected:f.object,received:w.parsedType}),d;let E=this.discriminator,X=w.data[E],G=this.optionsMap.get(X);if(!G)return g(w,{code:_.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[E]}),d;if(w.common.async)return G._parseAsync({data:w.data,path:w.path,parent:w});else return G._parseSync({data:w.data,path:w.path,parent:w})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,w,E){let X=new Map;for(let G of w){let J=Uw(G.shape[$]);if(!J.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let A of J){if(X.has(A))throw Error(`Discriminator property ${String($)} has duplicate value ${String(A)}`);X.set(A,G)}}return new UJ({typeName:a.ZodDiscriminatedUnion,discriminator:$,options:w,optionsMap:X,...X0(E)})}};mE=class mE extends G0{_parse($){let{status:w,ctx:E}=this._processInputParams($),X=(G,J)=>{if(WJ(G)||WJ(J))return d;let A=KD(G.value,J.value);if(!A.valid)return g(E,{code:_.invalid_intersection_types}),d;if(OJ(G)||OJ(J))w.dirty();return{status:w.value,value:A.data}};if(E.common.async)return Promise.all([this._def.left._parseAsync({data:E.data,path:E.path,parent:E}),this._def.right._parseAsync({data:E.data,path:E.path,parent:E})]).then(([G,J])=>X(G,J));else return X(this._def.left._parseSync({data:E.data,path:E.path,parent:E}),this._def.right._parseSync({data:E.data,path:E.path,parent:E}))}};mE.create=($,w,E)=>{return new mE({left:$,right:w,typeName:a.ZodIntersection,...X0(E)})};i1=class i1 extends G0{_parse($){let{status:w,ctx:E}=this._processInputParams($);if(E.parsedType!==f.array)return g(E,{code:_.invalid_type,expected:f.array,received:E.parsedType}),d;if(E.data.length<this._def.items.length)return g(E,{code:_.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),d;if(!this._def.rest&&E.data.length>this._def.items.length)g(E,{code:_.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),w.dirty();let G=[...E.data].map((J,A)=>{let D=this._def.items[A]||this._def.rest;if(!D)return null;return D._parse(new S1(E,J,E.path,A))}).filter((J)=>!!J);if(E.common.async)return Promise.all(G).then((J)=>{return j$.mergeArray(w,J)});else return j$.mergeArray(w,G)}get items(){return this._def.items}rest($){return new i1({...this._def,rest:$})}};i1.create=($,w)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new i1({items:$,typeName:a.ZodTuple,rest:null,...X0(w)})};JG=class JG extends G0{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:w,ctx:E}=this._processInputParams($);if(E.parsedType!==f.object)return g(E,{code:_.invalid_type,expected:f.object,received:E.parsedType}),d;let X=[],G=this._def.keyType,J=this._def.valueType;for(let A in E.data)X.push({key:G._parse(new S1(E,A,E.path,A)),value:J._parse(new S1(E,E.data[A],E.path,A)),alwaysSet:A in E.data});if(E.common.async)return j$.mergeObjectAsync(w,X);else return j$.mergeObjectSync(w,X)}get element(){return this._def.valueType}static create($,w,E){if(w instanceof G0)return new JG({keyType:$,valueType:w,typeName:a.ZodRecord,...X0(E)});return new JG({keyType:V1.create(),valueType:$,typeName:a.ZodRecord,...X0(w)})}};AG=class AG extends G0{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:w,ctx:E}=this._processInputParams($);if(E.parsedType!==f.map)return g(E,{code:_.invalid_type,expected:f.map,received:E.parsedType}),d;let X=this._def.keyType,G=this._def.valueType,J=[...E.data.entries()].map(([A,D],N)=>{return{key:X._parse(new S1(E,A,E.path,[N,"key"])),value:G._parse(new S1(E,D,E.path,[N,"value"]))}});if(E.common.async){let A=new Map;return Promise.resolve().then(async()=>{for(let D of J){let N=await D.key,W=await D.value;if(N.status==="aborted"||W.status==="aborted")return d;if(N.status==="dirty"||W.status==="dirty")w.dirty();A.set(N.value,W.value)}return{status:w.value,value:A}})}else{let A=new Map;for(let D of J){let{key:N,value:W}=D;if(N.status==="aborted"||W.status==="aborted")return d;if(N.status==="dirty"||W.status==="dirty")w.dirty();A.set(N.value,W.value)}return{status:w.value,value:A}}}};AG.create=($,w,E)=>{return new AG({valueType:w,keyType:$,typeName:a.ZodMap,...X0(E)})};WE=class WE extends G0{_parse($){let{status:w,ctx:E}=this._processInputParams($);if(E.parsedType!==f.set)return g(E,{code:_.invalid_type,expected:f.set,received:E.parsedType}),d;let X=this._def;if(X.minSize!==null){if(E.data.size<X.minSize.value)g(E,{code:_.too_small,minimum:X.minSize.value,type:"set",inclusive:!0,exact:!1,message:X.minSize.message}),w.dirty()}if(X.maxSize!==null){if(E.data.size>X.maxSize.value)g(E,{code:_.too_big,maximum:X.maxSize.value,type:"set",inclusive:!0,exact:!1,message:X.maxSize.message}),w.dirty()}let G=this._def.valueType;function J(D){let N=new Set;for(let W of D){if(W.status==="aborted")return d;if(W.status==="dirty")w.dirty();N.add(W.value)}return{status:w.value,value:N}}let A=[...E.data.values()].map((D,N)=>G._parse(new S1(E,D,E.path,N)));if(E.common.async)return Promise.all(A).then((D)=>J(D));else return J(A)}min($,w){return new WE({...this._def,minSize:{value:$,message:c.toString(w)}})}max($,w){return new WE({...this._def,maxSize:{value:$,message:c.toString(w)}})}size($,w){return this.min($,w).max($,w)}nonempty($){return this.min(1,$)}};WE.create=($,w)=>{return new WE({valueType:$,minSize:null,maxSize:null,typeName:a.ZodSet,...X0(w)})};gE=class gE extends G0{constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:w}=this._processInputParams($);if(w.parsedType!==f.function)return g(w,{code:_.invalid_type,expected:f.function,received:w.parsedType}),d;function E(A,D){return EG({data:A,path:w.path,errorMaps:[w.common.contextualErrorMap,w.schemaErrorMap,fE(),Ow].filter((N)=>!!N),issueData:{code:_.invalid_arguments,argumentsError:D}})}function X(A,D){return EG({data:A,path:w.path,errorMaps:[w.common.contextualErrorMap,w.schemaErrorMap,fE(),Ow].filter((N)=>!!N),issueData:{code:_.invalid_return_type,returnTypeError:D}})}let G={errorMap:w.common.contextualErrorMap},J=w.data;if(this._def.returns instanceof OE){let A=this;return P$(async function(...D){let N=new r$([]),W=await A._def.args.parseAsync(D,G).catch((H)=>{throw N.addIssue(E(D,H)),N}),O=await Reflect.apply(J,this,W);return await A._def.returns._def.type.parseAsync(O,G).catch((H)=>{throw N.addIssue(X(O,H)),N})})}else{let A=this;return P$(function(...D){let N=A._def.args.safeParse(D,G);if(!N.success)throw new r$([E(D,N.error)]);let W=Reflect.apply(J,this,N.data),O=A._def.returns.safeParse(W,G);if(!O.success)throw new r$([X(W,O.error)]);return O.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new gE({...this._def,args:i1.create($).rest(Cw.create())})}returns($){return new gE({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,w,E){return new gE({args:$?$:i1.create([]).rest(Cw.create()),returns:w||Cw.create(),typeName:a.ZodFunction,...X0(E)})}};rE=class rE extends G0{get schema(){return this._def.getter()}_parse($){let{ctx:w}=this._processInputParams($);return this._def.getter()._parse({data:w.data,path:w.path,parent:w})}};rE.create=($,w)=>{return new rE({getter:$,typeName:a.ZodLazy,...X0(w)})};pE=class pE extends G0{_parse($){if($.data!==this._def.value){let w=this._getOrReturnCtx($);return g(w,{received:w.data,code:_.invalid_literal,expected:this._def.value}),d}return{status:"valid",value:$.data}}get value(){return this._def.value}};pE.create=($,w)=>{return new pE({value:$,typeName:a.ZodLiteral,...X0(w)})};fw=class fw extends G0{_parse($){if(typeof $.data!=="string"){let w=this._getOrReturnCtx($),E=this._def.values;return g(w,{expected:Y0.joinValues(E),received:w.parsedType,code:_.invalid_type}),d}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let w=this._getOrReturnCtx($),E=this._def.values;return g(w,{received:w.data,code:_.invalid_enum_value,options:E}),d}return P$($.data)}get options(){return this._def.values}get enum(){let $={};for(let w of this._def.values)$[w]=w;return $}get Values(){let $={};for(let w of this._def.values)$[w]=w;return $}get Enum(){let $={};for(let w of this._def.values)$[w]=w;return $}extract($,w=this._def){return fw.create($,{...this._def,...w})}exclude($,w=this._def){return fw.create(this.options.filter((E)=>!$.includes(E)),{...this._def,...w})}};fw.create=gO;oE=class oE extends G0{_parse($){let w=Y0.getValidEnumValues(this._def.values),E=this._getOrReturnCtx($);if(E.parsedType!==f.string&&E.parsedType!==f.number){let X=Y0.objectValues(w);return g(E,{expected:Y0.joinValues(X),received:E.parsedType,code:_.invalid_type}),d}if(!this._cache)this._cache=new Set(Y0.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let X=Y0.objectValues(w);return g(E,{received:E.data,code:_.invalid_enum_value,options:X}),d}return P$($.data)}get enum(){return this._def.values}};oE.create=($,w)=>{return new oE({values:$,typeName:a.ZodNativeEnum,...X0(w)})};OE=class OE extends G0{unwrap(){return this._def.type}_parse($){let{ctx:w}=this._processInputParams($);if(w.parsedType!==f.promise&&w.common.async===!1)return g(w,{code:_.invalid_type,expected:f.promise,received:w.parsedType}),d;let E=w.parsedType===f.promise?w.data:Promise.resolve(w.data);return P$(E.then((X)=>{return this._def.type.parseAsync(X,{path:w.path,errorMap:w.common.contextualErrorMap})}))}};OE.create=($,w)=>{return new OE({type:$,typeName:a.ZodPromise,...X0(w)})};k1=class k1 extends G0{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===a.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:w,ctx:E}=this._processInputParams($),X=this._def.effect||null,G={addIssue:(J)=>{if(g(E,J),J.fatal)w.abort();else w.dirty()},get path(){return E.path}};if(G.addIssue=G.addIssue.bind(G),X.type==="preprocess"){let J=X.transform(E.data,G);if(E.common.async)return Promise.resolve(J).then(async(A)=>{if(w.value==="aborted")return d;let D=await this._def.schema._parseAsync({data:A,path:E.path,parent:E});if(D.status==="aborted")return d;if(D.status==="dirty")return AE(D.value);if(w.value==="dirty")return AE(D.value);return D});else{if(w.value==="aborted")return d;let A=this._def.schema._parseSync({data:J,path:E.path,parent:E});if(A.status==="aborted")return d;if(A.status==="dirty")return AE(A.value);if(w.value==="dirty")return AE(A.value);return A}}if(X.type==="refinement"){let J=(A)=>{let D=X.refinement(A,G);if(E.common.async)return Promise.resolve(D);if(D instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return A};if(E.common.async===!1){let A=this._def.schema._parseSync({data:E.data,path:E.path,parent:E});if(A.status==="aborted")return d;if(A.status==="dirty")w.dirty();return J(A.value),{status:w.value,value:A.value}}else return this._def.schema._parseAsync({data:E.data,path:E.path,parent:E}).then((A)=>{if(A.status==="aborted")return d;if(A.status==="dirty")w.dirty();return J(A.value).then(()=>{return{status:w.value,value:A.value}})})}if(X.type==="transform")if(E.common.async===!1){let J=this._def.schema._parseSync({data:E.data,path:E.path,parent:E});if(!Zw(J))return d;let A=X.transform(J.value,G);if(A instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:w.value,value:A}}else return this._def.schema._parseAsync({data:E.data,path:E.path,parent:E}).then((J)=>{if(!Zw(J))return d;return Promise.resolve(X.transform(J.value,G)).then((A)=>({status:w.value,value:A}))});Y0.assertNever(X)}};k1.create=($,w,E)=>{return new k1({schema:$,typeName:a.ZodEffects,effect:w,...X0(E)})};k1.createWithPreprocess=($,w,E)=>{return new k1({schema:w,effect:{type:"preprocess",transform:$},typeName:a.ZodEffects,...X0(E)})};q1=class q1 extends G0{_parse($){if(this._getType($)===f.undefined)return P$(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}};q1.create=($,w)=>{return new q1({innerType:$,typeName:a.ZodOptional,...X0(w)})};Yw=class Yw extends G0{_parse($){if(this._getType($)===f.null)return P$(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}};Yw.create=($,w)=>{return new Yw({innerType:$,typeName:a.ZodNullable,...X0(w)})};tE=class tE extends G0{_parse($){let{ctx:w}=this._processInputParams($),E=w.data;if(w.parsedType===f.undefined)E=this._def.defaultValue();return this._def.innerType._parse({data:E,path:w.path,parent:w})}removeDefault(){return this._def.innerType}};tE.create=($,w)=>{return new tE({innerType:$,typeName:a.ZodDefault,defaultValue:typeof w.default==="function"?w.default:()=>w.default,...X0(w)})};iE=class iE extends G0{_parse($){let{ctx:w}=this._processInputParams($),E={...w,common:{...w.common,issues:[]}},X=this._def.innerType._parse({data:E.data,path:E.path,parent:{...E}});if(xE(X))return X.then((G)=>{return{status:"valid",value:G.status==="valid"?G.value:this._def.catchValue({get error(){return new r$(E.common.issues)},input:E.data})}});else return{status:"valid",value:X.status==="valid"?X.value:this._def.catchValue({get error(){return new r$(E.common.issues)},input:E.data})}}removeCatch(){return this._def.innerType}};iE.create=($,w)=>{return new iE({innerType:$,typeName:a.ZodCatch,catchValue:typeof w.catch==="function"?w.catch:()=>w.catch,...X0(w)})};DG=class DG extends G0{_parse($){if(this._getType($)!==f.nan){let E=this._getOrReturnCtx($);return g(E,{code:_.invalid_type,expected:f.nan,received:E.parsedType}),d}return{status:"valid",value:$.data}}};DG.create=($)=>{return new DG({typeName:a.ZodNaN,...X0($)})};JP=Symbol("zod_brand");YJ=class YJ extends G0{_parse($){let{ctx:w}=this._processInputParams($),E=w.data;return this._def.type._parse({data:E,path:w.path,parent:w})}unwrap(){return this._def.type}};NG=class NG extends G0{_parse($){let{status:w,ctx:E}=this._processInputParams($);if(E.common.async)return(async()=>{let G=await this._def.in._parseAsync({data:E.data,path:E.path,parent:E});if(G.status==="aborted")return d;if(G.status==="dirty")return w.dirty(),AE(G.value);else return this._def.out._parseAsync({data:G.value,path:E.path,parent:E})})();else{let X=this._def.in._parseSync({data:E.data,path:E.path,parent:E});if(X.status==="aborted")return d;if(X.status==="dirty")return w.dirty(),{status:"dirty",value:X.value};else return this._def.out._parseSync({data:X.value,path:E.path,parent:E})}}static create($,w){return new NG({in:$,out:w,typeName:a.ZodPipeline})}};dE=class dE extends G0{_parse($){let w=this._def.innerType._parse($),E=(X)=>{if(Zw(X))X.value=Object.freeze(X.value);return X};return xE(w)?w.then((X)=>E(X)):E(w)}unwrap(){return this._def.innerType}};dE.create=($,w)=>{return new dE({innerType:$,typeName:a.ZodReadonly,...X0(w)})};AP={object:l0.lazycreate};(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(a||(a={}));hO=V1.create,cO=_w.create,NP=DG.create,WP=vw.create,nO=uE.create,OP=DE.create,UP=XG.create,YP=hE.create,HP=cE.create,LP=NE.create,FP=Cw.create,jP=t1.create,MP=GG.create,RP=P1.create,zP=l0.create,TP=l0.strictCreate,BP=nE.create,QP=UJ.create,IP=mE.create,KP=i1.create,VP=JG.create,PP=AG.create,qP=WE.create,SP=gE.create,kP=rE.create,bP=pE.create,ZP=fw.create,CP=oE.create,_P=OE.create,vP=k1.create,fP=q1.create,xP=Yw.create,yP=k1.createWithPreprocess,gP=NG.create,nP={string:($)=>V1.create({...$,coerce:!0}),number:($)=>_w.create({...$,coerce:!0}),boolean:($)=>uE.create({...$,coerce:!0}),bigint:($)=>vw.create({...$,coerce:!0}),date:($)=>DE.create({...$,coerce:!0})},mP=d});var U={};Ww(U,{void:()=>MP,util:()=>Y0,unknown:()=>FP,union:()=>BP,undefined:()=>YP,tuple:()=>KP,transformer:()=>vP,symbol:()=>UP,string:()=>hO,strictObject:()=>TP,setErrorMap:()=>xV,set:()=>qP,record:()=>VP,quotelessJson:()=>vV,promise:()=>_P,preprocess:()=>yP,pipeline:()=>gP,ostring:()=>uP,optional:()=>fP,onumber:()=>hP,oboolean:()=>cP,objectUtil:()=>TD,object:()=>zP,number:()=>cO,nullable:()=>xP,null:()=>HP,never:()=>jP,nativeEnum:()=>CP,nan:()=>NP,map:()=>PP,makeIssue:()=>EG,literal:()=>bP,lazy:()=>kP,late:()=>AP,isValid:()=>Zw,isDirty:()=>OJ,isAsync:()=>xE,isAborted:()=>WJ,intersection:()=>IP,instanceof:()=>DP,getParsedType:()=>o1,getErrorMap:()=>fE,function:()=>SP,enum:()=>ZP,effect:()=>vP,discriminatedUnion:()=>QP,defaultErrorMap:()=>Ow,datetimeRegex:()=>yO,date:()=>OP,custom:()=>uO,coerce:()=>nP,boolean:()=>nO,bigint:()=>WP,array:()=>RP,any:()=>LP,addIssueToContext:()=>g,ZodVoid:()=>GG,ZodUnknown:()=>Cw,ZodUnion:()=>nE,ZodUndefined:()=>hE,ZodType:()=>G0,ZodTuple:()=>i1,ZodTransformer:()=>k1,ZodSymbol:()=>XG,ZodString:()=>V1,ZodSet:()=>WE,ZodSchema:()=>G0,ZodRecord:()=>JG,ZodReadonly:()=>dE,ZodPromise:()=>OE,ZodPipeline:()=>NG,ZodParsedType:()=>f,ZodOptional:()=>q1,ZodObject:()=>l0,ZodNumber:()=>_w,ZodNullable:()=>Yw,ZodNull:()=>cE,ZodNever:()=>t1,ZodNativeEnum:()=>oE,ZodNaN:()=>DG,ZodMap:()=>AG,ZodLiteral:()=>pE,ZodLazy:()=>rE,ZodIssueCode:()=>_,ZodIntersection:()=>mE,ZodFunction:()=>gE,ZodFirstPartyTypeKind:()=>a,ZodError:()=>r$,ZodEnum:()=>fw,ZodEffects:()=>k1,ZodDiscriminatedUnion:()=>UJ,ZodDefault:()=>tE,ZodDate:()=>DE,ZodCatch:()=>iE,ZodBranded:()=>YJ,ZodBoolean:()=>uE,ZodBigInt:()=>vw,ZodArray:()=>P1,ZodAny:()=>NE,Schema:()=>G0,ParseStatus:()=>j$,OK:()=>P$,NEVER:()=>mP,INVALID:()=>d,EMPTY_PATH:()=>yV,DIRTY:()=>AE,BRAND:()=>JP});var VD=R(()=>{NJ();QD();ZO();wG();mO();DJ()});var WG=R(()=>{VD();VD()});import{existsSync as rO,readFileSync as rP}from"fs";import{homedir as tO}from"os";import{join as PD}from"path";function dP($){if($.startsWith("~/"))return PD(tO(),$.slice(2));return $}function oO($){try{return JSON.parse(rP($,"utf-8"))}catch{return{}}}function OG($,w){let E={...$};for(let[X,G]of Object.entries(w))if(G!==null&&typeof G==="object"&&!Array.isArray(G)&&typeof E[X]==="object"&&E[X]!==null)E[X]=OG(E[X],G);else E[X]=G;return E}function lP(){let $={};if(process.env.ORC_DB_PATH)$.db={path:process.env.ORC_DB_PATH};let w={};if(process.env.ORC_API_PORT)w.port=Number(process.env.ORC_API_PORT);if(process.env.ORC_API_HOST)w.host=process.env.ORC_API_HOST;if(process.env.ORC_API_SECRET)w.secret=process.env.ORC_API_SECRET;if(Object.keys(w).length)$.api=w;let E={};if(process.env.ORC_RUNNER_TIMEOUT)E.default_timeout_secs=Number(process.env.ORC_RUNNER_TIMEOUT);if(process.env.ORC_RUNNER_MAX_JOBS)E.max_concurrent_jobs=Number(process.env.ORC_RUNNER_MAX_JOBS);if(process.env.ORC_RUNNER_LOG_DAYS)E.log_retention_days=Number(process.env.ORC_RUNNER_LOG_DAYS);if(Object.keys(E).length)$.runner=E;let X={};if(process.env.ORC_SNAPSHOT_MAX_BYTES)X.snapshot_max_bytes=Number(process.env.ORC_SNAPSHOT_MAX_BYTES);if(process.env.ORC_LAYER1_TASKS)X.layer1_task_limit=Number(process.env.ORC_LAYER1_TASKS);if(process.env.ORC_LAYER1_MEMORIES)X.layer1_memory_limit=Number(process.env.ORC_LAYER1_MEMORIES);if(Object.keys(X).length)$.context=X;let G={};if(process.env.ORC_TELEGRAM_TOKEN)G.telegram={token:process.env.ORC_TELEGRAM_TOKEN,enabled:!0};if(process.env.ORC_SLACK_BOT_TOKEN||process.env.ORC_SLACK_APP_TOKEN)G.slack={bot_token:process.env.ORC_SLACK_BOT_TOKEN,app_token:process.env.ORC_SLACK_APP_TOKEN,enabled:!0};if(Object.keys(G).length)$.gateway=G;let J={};if(process.env.ORC_SPEECH_PROVIDER)J.provider=process.env.ORC_SPEECH_PROVIDER;if(process.env.ORC_SPEECH_LANGUAGE)J.language=process.env.ORC_SPEECH_LANGUAGE;if(process.env.ORC_OPENAI_API_KEY)J.openai={api_key:process.env.ORC_OPENAI_API_KEY};if(process.env.ORC_GROQ_API_KEY)J.groq={api_key:process.env.ORC_GROQ_API_KEY};if(process.env.ORC_QWEN_API_KEY)J.qwen={api_key:process.env.ORC_QWEN_API_KEY};if(Object.keys(J).length)J.enabled=!0,$.speech=J;let A={};if(process.env.ORC_TTS_PROVIDER)A.provider=process.env.ORC_TTS_PROVIDER;if(process.env.ORC_TTS_VOICE)A.voice=process.env.ORC_TTS_VOICE;if(process.env.ORC_TTS_MODE)A.mode=process.env.ORC_TTS_MODE;if(Object.keys(A).length)A.enabled=!0,$.tts=A;return $}function O0($){if(HJ&&!$)return HJ;let w=PD(tO(),".orc","config.json"),E=PD(process.cwd(),".orc","config.json"),X={};if(rO(w))X=OG(X,oO(w));if(rO(E))X=OG(X,oO(E));if(X=OG(X,lP()),$)X=OG(X,$);if(X.bridge&&!X.gateway)X.gateway=X.bridge;delete X.bridge;let G=iP.safeParse(X);if(!G.success)throw Error(`Invalid orc config:
|
|
4
|
-
${G.error.message}`);return G.data.db.path=
|
|
5
|
-
`)}displayWidth($){return
|
|
3
|
+
var bV=Object.create;var{getPrototypeOf:ZV,defineProperty:wG,getOwnPropertyNames:kO,getOwnPropertyDescriptor:CV}=Object,bO=Object.prototype.hasOwnProperty;function ZO($){return this[$]}var _V,vV,DJ=($,w,E)=>{var X=$!=null&&typeof $==="object";if(X){var G=w?_V??=new WeakMap:vV??=new WeakMap,J=G.get($);if(J)return J}E=$!=null?bV(ZV($)):{};let A=w||!$||!$.__esModule?wG(E,"default",{value:$,enumerable:!0}):E;for(let D of kO($))if(!bO.call(A,D))wG(A,D,{get:ZO.bind($,D),enumerable:!0});if(X)G.set($,A);return A},CO=($)=>{var w=(SO??=new WeakMap).get($),E;if(w)return w;if(w=wG({},"__esModule",{value:!0}),$&&typeof $==="object"||typeof $==="function"){for(var X of kO($))if(!bO.call(w,X))wG(w,X,{get:ZO.bind($,X),enumerable:!(E=CV($,X))||E.enumerable})}return SO.set($,w),w},SO,Z=($,w)=>()=>(w||$((w={exports:{}}).exports,w),w.exports);var fV=($)=>$;function xV($,w){this[$]=fV.bind(null,w)}var Ww=($,w)=>{for(var E in w)wG($,E,{get:w[E],enumerable:!0,configurable:!0,set:xV.bind(w,E)})};var R=($,w)=>()=>($&&(w=$($=0)),w);var V$=import.meta.require;var Y0,QD,f,o1=($)=>{switch(typeof $){case"undefined":return f.undefined;case"string":return f.string;case"number":return Number.isNaN($)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":if(Array.isArray($))return f.array;if($===null)return f.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return f.promise;if(typeof Map<"u"&&$ instanceof Map)return f.map;if(typeof Set<"u"&&$ instanceof Set)return f.set;if(typeof Date<"u"&&$ instanceof Date)return f.date;return f.object;default:return f.unknown}};var EG=R(()=>{(function($){$.assertEqual=(G)=>{};function w(G){}$.assertIs=w;function E(G){throw Error()}$.assertNever=E,$.arrayToEnum=(G)=>{let J={};for(let A of G)J[A]=A;return J},$.getValidEnumValues=(G)=>{let J=$.objectKeys(G).filter((D)=>typeof G[G[D]]!=="number"),A={};for(let D of J)A[D]=G[D];return $.objectValues(A)},$.objectValues=(G)=>{return $.objectKeys(G).map(function(J){return G[J]})},$.objectKeys=typeof Object.keys==="function"?(G)=>Object.keys(G):(G)=>{let J=[];for(let A in G)if(Object.prototype.hasOwnProperty.call(G,A))J.push(A);return J},$.find=(G,J)=>{for(let A of G)if(J(A))return A;return},$.isInteger=typeof Number.isInteger==="function"?(G)=>Number.isInteger(G):(G)=>typeof G==="number"&&Number.isFinite(G)&&Math.floor(G)===G;function X(G,J=" | "){return G.map((A)=>typeof A==="string"?`'${A}'`:A).join(J)}$.joinValues=X,$.jsonStringifyReplacer=(G,J)=>{if(typeof J==="bigint")return J.toString();return J}})(Y0||(Y0={}));(function($){$.mergeShapes=(w,E)=>{return{...w,...E}}})(QD||(QD={}));f=Y0.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"])});var _,yV=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")},r$;var NJ=R(()=>{EG();_=Y0.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"]);r$=class r$ extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(E)=>{this.issues=[...this.issues,E]},this.addIssues=(E=[])=>{this.issues=[...this.issues,...E]};let w=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,w);else this.__proto__=w;this.name="ZodError",this.issues=$}format($){let w=$||function(G){return G.message},E={_errors:[]},X=(G)=>{for(let J of G.issues)if(J.code==="invalid_union")J.unionErrors.map(X);else if(J.code==="invalid_return_type")X(J.returnTypeError);else if(J.code==="invalid_arguments")X(J.argumentsError);else if(J.path.length===0)E._errors.push(w(J));else{let A=E,D=0;while(D<J.path.length){let N=J.path[D];if(D!==J.path.length-1)A[N]=A[N]||{_errors:[]};else A[N]=A[N]||{_errors:[]},A[N]._errors.push(w(J));A=A[N],D++}}};return X(this),E}static assert($){if(!($ instanceof r$))throw Error(`Not a ZodError: ${$}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Y0.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten($=(w)=>w.message){let w={},E=[];for(let X of this.issues)if(X.path.length>0){let G=X.path[0];w[G]=w[G]||[],w[G].push($(X))}else E.push($(X));return{formErrors:E,fieldErrors:w}}get formErrors(){return this.flatten()}};r$.create=($)=>{return new r$($)}});var gV=($,w)=>{let E;switch($.code){case _.invalid_type:if($.received===f.undefined)E="Required";else E=`Expected ${$.expected}, received ${$.received}`;break;case _.invalid_literal:E=`Invalid literal value, expected ${JSON.stringify($.expected,Y0.jsonStringifyReplacer)}`;break;case _.unrecognized_keys:E=`Unrecognized key(s) in object: ${Y0.joinValues($.keys,", ")}`;break;case _.invalid_union:E="Invalid input";break;case _.invalid_union_discriminator:E=`Invalid discriminator value. Expected ${Y0.joinValues($.options)}`;break;case _.invalid_enum_value:E=`Invalid enum value. Expected ${Y0.joinValues($.options)}, received '${$.received}'`;break;case _.invalid_arguments:E="Invalid function arguments";break;case _.invalid_return_type:E="Invalid function return type";break;case _.invalid_date:E="Invalid date";break;case _.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(E=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")E=`${E} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)E=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)E=`Invalid input: must end with "${$.validation.endsWith}"`;else Y0.assertNever($.validation);else if($.validation!=="regex")E=`Invalid ${$.validation}`;else E="Invalid";break;case _.too_small:if($.type==="array")E=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")E=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")E=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="bigint")E=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")E=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else E="Invalid input";break;case _.too_big:if($.type==="array")E=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")E=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")E=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")E=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")E=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else E="Invalid input";break;case _.custom:E="Invalid input";break;case _.invalid_intersection_types:E="Intersection results could not be merged";break;case _.not_multiple_of:E=`Number must be a multiple of ${$.multipleOf}`;break;case _.not_finite:E="Number must be finite";break;default:E=w.defaultError,Y0.assertNever($)}return{message:E}},Ow;var ID=R(()=>{NJ();EG();Ow=gV});function uV($){_O=$}function fE(){return _O}var _O;var WJ=R(()=>{ID();_O=Ow});function g($,w){let E=fE(),X=XG({issueData:w,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,E,E===Ow?void 0:Ow].filter((G)=>!!G)});$.common.issues.push(X)}class j${constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,w){let E=[];for(let X of w){if(X.status==="aborted")return d;if(X.status==="dirty")$.dirty();E.push(X.value)}return{status:$.value,value:E}}static async mergeObjectAsync($,w){let E=[];for(let X of w){let G=await X.key,J=await X.value;E.push({key:G,value:J})}return j$.mergeObjectSync($,E)}static mergeObjectSync($,w){let E={};for(let X of w){let{key:G,value:J}=X;if(G.status==="aborted")return d;if(J.status==="aborted")return d;if(G.status==="dirty")$.dirty();if(J.status==="dirty")$.dirty();if(G.value!=="__proto__"&&(typeof J.value<"u"||X.alwaysSet))E[G.value]=J.value}return{status:$.value,value:E}}}var XG=($)=>{let{data:w,path:E,errorMaps:X,issueData:G}=$,J=[...E,...G.path||[]],A={...G,path:J};if(G.message!==void 0)return{...G,path:J,message:G.message};let D="",N=X.filter((W)=>!!W).slice().reverse();for(let W of N)D=W(A,{data:w,defaultError:D}).message;return{...G,path:J,message:D}},hV,d,AE=($)=>({status:"dirty",value:$}),P$=($)=>({status:"valid",value:$}),OJ=($)=>$.status==="aborted",UJ=($)=>$.status==="dirty",Zw=($)=>$.status==="valid",xE=($)=>typeof Promise<"u"&&$ instanceof Promise;var KD=R(()=>{WJ();ID();hV=[];d=Object.freeze({status:"aborted"})});var vO=()=>{};var c;var fO=R(()=>{(function($){$.errToObj=(w)=>typeof w==="string"?{message:w}:w||{},$.toString=(w)=>typeof w==="string"?w:w?.message})(c||(c={}))});class S1{constructor($,w,E,X){this._cachedPath=[],this.parent=$,this.data=w,this._path=E,this._key=X}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}function X0($){if(!$)return{};let{errorMap:w,invalid_type_error:E,required_error:X,description:G}=$;if(w&&(E||X))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(w)return{errorMap:w,description:G};return{errorMap:(A,D)=>{let{message:N}=$;if(A.code==="invalid_enum_value")return{message:N??D.defaultError};if(typeof D.data>"u")return{message:N??X??D.defaultError};if(A.code!=="invalid_type")return{message:D.defaultError};return{message:N??E??D.defaultError}},description:G}}class G0{get description(){return this._def.description}_getType($){return o1($.data)}_getOrReturnCtx($,w){return w||{common:$.parent.common,data:$.data,parsedType:o1($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new j$,ctx:{common:$.parent.common,data:$.data,parsedType:o1($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let w=this._parse($);if(xE(w))throw Error("Synchronous parse encountered promise.");return w}_parseAsync($){let w=this._parse($);return Promise.resolve(w)}parse($,w){let E=this.safeParse($,w);if(E.success)return E.data;throw E.error}safeParse($,w){let E={common:{issues:[],async:w?.async??!1,contextualErrorMap:w?.errorMap},path:w?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:o1($)},X=this._parseSync({data:$,path:E.path,parent:E});return xO(E,X)}"~validate"($){let w={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:o1($)};if(!this["~standard"].async)try{let E=this._parseSync({data:$,path:[],parent:w});return Zw(E)?{value:E.value}:{issues:w.common.issues}}catch(E){if(E?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;w.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:w}).then((E)=>Zw(E)?{value:E.value}:{issues:w.common.issues})}async parseAsync($,w){let E=await this.safeParseAsync($,w);if(E.success)return E.data;throw E.error}async safeParseAsync($,w){let E={common:{issues:[],contextualErrorMap:w?.errorMap,async:!0},path:w?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:o1($)},X=this._parse({data:$,path:E.path,parent:E}),G=await(xE(X)?X:Promise.resolve(X));return xO(E,G)}refine($,w){let E=(X)=>{if(typeof w==="string"||typeof w>"u")return{message:w};else if(typeof w==="function")return w(X);else return w};return this._refinement((X,G)=>{let J=$(X),A=()=>G.addIssue({code:_.custom,...E(X)});if(typeof Promise<"u"&&J instanceof Promise)return J.then((D)=>{if(!D)return A(),!1;else return!0});if(!J)return A(),!1;else return!0})}refinement($,w){return this._refinement((E,X)=>{if(!$(E))return X.addIssue(typeof w==="function"?w(E,X):w),!1;else return!0})}_refinement($){return new k1({schema:this,typeName:a.ZodEffects,effect:{type:"refinement",refinement:$}})}superRefine($){return this._refinement($)}constructor($){this.spa=this.safeParseAsync,this._def=$,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:(w)=>this["~validate"](w)}}optional(){return q1.create(this,this._def)}nullable(){return Yw.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return P1.create(this)}promise(){return OE.create(this,this._def)}or($){return nE.create([this,$],this._def)}and($){return mE.create(this,$,this._def)}transform($){return new k1({...X0(this._def),schema:this,typeName:a.ZodEffects,effect:{type:"transform",transform:$}})}default($){let w=typeof $==="function"?$:()=>$;return new tE({...X0(this._def),innerType:this,defaultValue:w,typeName:a.ZodDefault})}brand(){return new HJ({typeName:a.ZodBranded,type:this,...X0(this._def)})}catch($){let w=typeof $==="function"?$:()=>$;return new iE({...X0(this._def),innerType:this,catchValue:w,typeName:a.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return WG.create(this,$)}readonly(){return dE.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}function uO($){let w="[0-5]\\d";if($.precision)w=`${w}\\.\\d{${$.precision}}`;else if($.precision==null)w=`${w}(\\.\\d+)?`;let E=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${w})${E}`}function XP($){return new RegExp(`^${uO($)}$`)}function hO($){let w=`${gO}T${uO($)}`,E=[];if(E.push($.local?"Z?":"Z"),$.offset)E.push("([+-]\\d{2}:?\\d{2})");return w=`${w}(${E.join("|")})`,new RegExp(`^${w}$`)}function GP($,w){if((w==="v4"||!w)&&lV.test($))return!0;if((w==="v6"||!w)&&aV.test($))return!0;return!1}function JP($,w){if(!oV.test($))return!1;try{let[E]=$.split(".");if(!E)return!1;let X=E.replace(/-/g,"+").replace(/_/g,"/").padEnd(E.length+(4-E.length%4)%4,"="),G=JSON.parse(atob(X));if(typeof G!=="object"||G===null)return!1;if("typ"in G&&G?.typ!=="JWT")return!1;if(!G.alg)return!1;if(w&&G.alg!==w)return!1;return!0}catch{return!1}}function AP($,w){if((w==="v4"||!w)&&sV.test($))return!0;if((w==="v6"||!w)&&eV.test($))return!0;return!1}function DP($,w){let E=($.toString().split(".")[1]||"").length,X=(w.toString().split(".")[1]||"").length,G=E>X?E:X,J=Number.parseInt($.toFixed(G).replace(".","")),A=Number.parseInt(w.toFixed(G).replace(".",""));return J%A/10**G}function yE($){if($ instanceof l0){let w={};for(let E in $.shape){let X=$.shape[E];w[E]=q1.create(yE(X))}return new l0({...$._def,shape:()=>w})}else if($ instanceof P1)return new P1({...$._def,type:yE($.element)});else if($ instanceof q1)return q1.create(yE($.unwrap()));else if($ instanceof Yw)return Yw.create(yE($.unwrap()));else if($ instanceof i1)return i1.create($.items.map((w)=>yE(w)));else return $}function PD($,w){let E=o1($),X=o1(w);if($===w)return{valid:!0,data:$};else if(E===f.object&&X===f.object){let G=Y0.objectKeys(w),J=Y0.objectKeys($).filter((D)=>G.indexOf(D)!==-1),A={...$,...w};for(let D of J){let N=PD($[D],w[D]);if(!N.valid)return{valid:!1};A[D]=N.data}return{valid:!0,data:A}}else if(E===f.array&&X===f.array){if($.length!==w.length)return{valid:!1};let G=[];for(let J=0;J<$.length;J++){let A=$[J],D=w[J],N=PD(A,D);if(!N.valid)return{valid:!1};G.push(N.data)}return{valid:!0,data:G}}else if(E===f.date&&X===f.date&&+$===+w)return{valid:!0,data:$};else return{valid:!1}}function cO($,w){return new fw({values:$,typeName:a.ZodEnum,...X0(w)})}function yO($,w){let E=typeof $==="function"?$(w):typeof $==="string"?{message:$}:$;return typeof E==="string"?{message:E}:E}function nO($,w={},E){if($)return NE.create().superRefine((X,G)=>{let J=$(X);if(J instanceof Promise)return J.then((A)=>{if(!A){let D=yO(w,X),N=D.fatal??E??!0;G.addIssue({code:"custom",...D,fatal:N})}});if(!J){let A=yO(w,X),D=A.fatal??E??!0;G.addIssue({code:"custom",...A,fatal:D})}return});return NE.create()}var xO=($,w)=>{if(Zw(w))return{success:!0,data:w.value};else{if(!$.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let E=new r$($.common.issues);return this._error=E,this._error}}}},cV,nV,mV,rV,pV,oV,tV,iV,dV="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",VD,lV,sV,aV,eV,$P,wP,gO="((\\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])))",EP,V1,_w,vw,uE,DE,GG,hE,cE,NE,Cw,t1,JG,P1,l0,nE,Uw=($)=>{if($ instanceof rE)return Uw($.schema);else if($ instanceof k1)return Uw($.innerType());else if($ instanceof pE)return[$.value];else if($ instanceof fw)return $.options;else if($ instanceof oE)return Y0.objectValues($.enum);else if($ instanceof tE)return Uw($._def.innerType);else if($ instanceof hE)return[void 0];else if($ instanceof cE)return[null];else if($ instanceof q1)return[void 0,...Uw($.unwrap())];else if($ instanceof Yw)return[null,...Uw($.unwrap())];else if($ instanceof HJ)return Uw($.unwrap());else if($ instanceof dE)return Uw($.unwrap());else if($ instanceof iE)return Uw($._def.innerType);else return[]},YJ,mE,i1,AG,DG,WE,gE,rE,pE,fw,oE,OE,k1,q1,Yw,tE,iE,NG,NP,HJ,WG,dE,WP,a,OP=($,w={message:`Input not instance of ${$.name}`})=>nO((E)=>E instanceof $,w),mO,rO,UP,YP,pO,HP,LP,FP,jP,MP,RP,zP,TP,BP,QP,IP,KP,VP,PP,qP,SP,kP,bP,ZP,CP,_P,vP,fP,xP,yP,gP,uP,hP,cP,nP=()=>mO().optional(),mP=()=>rO().optional(),rP=()=>pO().optional(),pP,oP;var oO=R(()=>{NJ();WJ();fO();KD();EG();cV=/^c[^\s-]{8,}$/i,nV=/^[0-9a-z]+$/,mV=/^[0-9A-HJKMNP-TV-Z]{26}$/i,rV=/^[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,pV=/^[a-z0-9_-]{21}$/i,oV=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,tV=/^[-+]?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)?)??$/,iV=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,lV=/^(?:(?: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])$/,sV=/^(?:(?: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])$/,aV=/^(([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]))$/,eV=/^(([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])$/,$P=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,wP=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,EP=new RegExp(`^${gO}$`);V1=class V1 extends G0{_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==f.string){let G=this._getOrReturnCtx($);return g(G,{code:_.invalid_type,expected:f.string,received:G.parsedType}),d}let E=new j$,X=void 0;for(let G of this._def.checks)if(G.kind==="min"){if($.data.length<G.value)X=this._getOrReturnCtx($,X),g(X,{code:_.too_small,minimum:G.value,type:"string",inclusive:!0,exact:!1,message:G.message}),E.dirty()}else if(G.kind==="max"){if($.data.length>G.value)X=this._getOrReturnCtx($,X),g(X,{code:_.too_big,maximum:G.value,type:"string",inclusive:!0,exact:!1,message:G.message}),E.dirty()}else if(G.kind==="length"){let J=$.data.length>G.value,A=$.data.length<G.value;if(J||A){if(X=this._getOrReturnCtx($,X),J)g(X,{code:_.too_big,maximum:G.value,type:"string",inclusive:!0,exact:!0,message:G.message});else if(A)g(X,{code:_.too_small,minimum:G.value,type:"string",inclusive:!0,exact:!0,message:G.message});E.dirty()}}else if(G.kind==="email"){if(!iV.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"email",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="emoji"){if(!VD)VD=new RegExp(dV,"u");if(!VD.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"emoji",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="uuid"){if(!rV.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"uuid",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="nanoid"){if(!pV.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"nanoid",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="cuid"){if(!cV.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"cuid",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="cuid2"){if(!nV.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"cuid2",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="ulid"){if(!mV.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"ulid",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="url")try{new URL($.data)}catch{X=this._getOrReturnCtx($,X),g(X,{validation:"url",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="regex"){if(G.regex.lastIndex=0,!G.regex.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"regex",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="trim")$.data=$.data.trim();else if(G.kind==="includes"){if(!$.data.includes(G.value,G.position))X=this._getOrReturnCtx($,X),g(X,{code:_.invalid_string,validation:{includes:G.value,position:G.position},message:G.message}),E.dirty()}else if(G.kind==="toLowerCase")$.data=$.data.toLowerCase();else if(G.kind==="toUpperCase")$.data=$.data.toUpperCase();else if(G.kind==="startsWith"){if(!$.data.startsWith(G.value))X=this._getOrReturnCtx($,X),g(X,{code:_.invalid_string,validation:{startsWith:G.value},message:G.message}),E.dirty()}else if(G.kind==="endsWith"){if(!$.data.endsWith(G.value))X=this._getOrReturnCtx($,X),g(X,{code:_.invalid_string,validation:{endsWith:G.value},message:G.message}),E.dirty()}else if(G.kind==="datetime"){if(!hO(G).test($.data))X=this._getOrReturnCtx($,X),g(X,{code:_.invalid_string,validation:"datetime",message:G.message}),E.dirty()}else if(G.kind==="date"){if(!EP.test($.data))X=this._getOrReturnCtx($,X),g(X,{code:_.invalid_string,validation:"date",message:G.message}),E.dirty()}else if(G.kind==="time"){if(!XP(G).test($.data))X=this._getOrReturnCtx($,X),g(X,{code:_.invalid_string,validation:"time",message:G.message}),E.dirty()}else if(G.kind==="duration"){if(!tV.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"duration",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="ip"){if(!GP($.data,G.version))X=this._getOrReturnCtx($,X),g(X,{validation:"ip",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="jwt"){if(!JP($.data,G.alg))X=this._getOrReturnCtx($,X),g(X,{validation:"jwt",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="cidr"){if(!AP($.data,G.version))X=this._getOrReturnCtx($,X),g(X,{validation:"cidr",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="base64"){if(!$P.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"base64",code:_.invalid_string,message:G.message}),E.dirty()}else if(G.kind==="base64url"){if(!wP.test($.data))X=this._getOrReturnCtx($,X),g(X,{validation:"base64url",code:_.invalid_string,message:G.message}),E.dirty()}else Y0.assertNever(G);return{status:E.value,value:$.data}}_regex($,w,E){return this.refinement((X)=>$.test(X),{validation:w,code:_.invalid_string,...c.errToObj(E)})}_addCheck($){return new V1({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...c.errToObj($)})}url($){return this._addCheck({kind:"url",...c.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...c.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...c.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...c.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...c.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...c.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...c.errToObj($)})}base64($){return this._addCheck({kind:"base64",...c.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...c.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...c.errToObj($)})}ip($){return this._addCheck({kind:"ip",...c.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...c.errToObj($)})}datetime($){if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof $?.precision>"u"?null:$?.precision,offset:$?.offset??!1,local:$?.local??!1,...c.errToObj($?.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof $?.precision>"u"?null:$?.precision,...c.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...c.errToObj($)})}regex($,w){return this._addCheck({kind:"regex",regex:$,...c.errToObj(w)})}includes($,w){return this._addCheck({kind:"includes",value:$,position:w?.position,...c.errToObj(w?.message)})}startsWith($,w){return this._addCheck({kind:"startsWith",value:$,...c.errToObj(w)})}endsWith($,w){return this._addCheck({kind:"endsWith",value:$,...c.errToObj(w)})}min($,w){return this._addCheck({kind:"min",value:$,...c.errToObj(w)})}max($,w){return this._addCheck({kind:"max",value:$,...c.errToObj(w)})}length($,w){return this._addCheck({kind:"length",value:$,...c.errToObj(w)})}nonempty($){return this.min(1,c.errToObj($))}trim(){return new V1({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new V1({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new V1({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(($)=>$.kind==="datetime")}get isDate(){return!!this._def.checks.find(($)=>$.kind==="date")}get isTime(){return!!this._def.checks.find(($)=>$.kind==="time")}get isDuration(){return!!this._def.checks.find(($)=>$.kind==="duration")}get isEmail(){return!!this._def.checks.find(($)=>$.kind==="email")}get isURL(){return!!this._def.checks.find(($)=>$.kind==="url")}get isEmoji(){return!!this._def.checks.find(($)=>$.kind==="emoji")}get isUUID(){return!!this._def.checks.find(($)=>$.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(($)=>$.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(($)=>$.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(($)=>$.kind==="cuid2")}get isULID(){return!!this._def.checks.find(($)=>$.kind==="ulid")}get isIP(){return!!this._def.checks.find(($)=>$.kind==="ip")}get isCIDR(){return!!this._def.checks.find(($)=>$.kind==="cidr")}get isBase64(){return!!this._def.checks.find(($)=>$.kind==="base64")}get isBase64url(){return!!this._def.checks.find(($)=>$.kind==="base64url")}get minLength(){let $=null;for(let w of this._def.checks)if(w.kind==="min"){if($===null||w.value>$)$=w.value}return $}get maxLength(){let $=null;for(let w of this._def.checks)if(w.kind==="max"){if($===null||w.value<$)$=w.value}return $}};V1.create=($)=>{return new V1({checks:[],typeName:a.ZodString,coerce:$?.coerce??!1,...X0($)})};_w=class _w extends G0{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse($){if(this._def.coerce)$.data=Number($.data);if(this._getType($)!==f.number){let G=this._getOrReturnCtx($);return g(G,{code:_.invalid_type,expected:f.number,received:G.parsedType}),d}let E=void 0,X=new j$;for(let G of this._def.checks)if(G.kind==="int"){if(!Y0.isInteger($.data))E=this._getOrReturnCtx($,E),g(E,{code:_.invalid_type,expected:"integer",received:"float",message:G.message}),X.dirty()}else if(G.kind==="min"){if(G.inclusive?$.data<G.value:$.data<=G.value)E=this._getOrReturnCtx($,E),g(E,{code:_.too_small,minimum:G.value,type:"number",inclusive:G.inclusive,exact:!1,message:G.message}),X.dirty()}else if(G.kind==="max"){if(G.inclusive?$.data>G.value:$.data>=G.value)E=this._getOrReturnCtx($,E),g(E,{code:_.too_big,maximum:G.value,type:"number",inclusive:G.inclusive,exact:!1,message:G.message}),X.dirty()}else if(G.kind==="multipleOf"){if(DP($.data,G.value)!==0)E=this._getOrReturnCtx($,E),g(E,{code:_.not_multiple_of,multipleOf:G.value,message:G.message}),X.dirty()}else if(G.kind==="finite"){if(!Number.isFinite($.data))E=this._getOrReturnCtx($,E),g(E,{code:_.not_finite,message:G.message}),X.dirty()}else Y0.assertNever(G);return{status:X.value,value:$.data}}gte($,w){return this.setLimit("min",$,!0,c.toString(w))}gt($,w){return this.setLimit("min",$,!1,c.toString(w))}lte($,w){return this.setLimit("max",$,!0,c.toString(w))}lt($,w){return this.setLimit("max",$,!1,c.toString(w))}setLimit($,w,E,X){return new _w({...this._def,checks:[...this._def.checks,{kind:$,value:w,inclusive:E,message:c.toString(X)}]})}_addCheck($){return new _w({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:c.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:c.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:c.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:c.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:c.toString($)})}multipleOf($,w){return this._addCheck({kind:"multipleOf",value:$,message:c.toString(w)})}finite($){return this._addCheck({kind:"finite",message:c.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:c.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:c.toString($)})}get minValue(){let $=null;for(let w of this._def.checks)if(w.kind==="min"){if($===null||w.value>$)$=w.value}return $}get maxValue(){let $=null;for(let w of this._def.checks)if(w.kind==="max"){if($===null||w.value<$)$=w.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&Y0.isInteger($.value))}get isFinite(){let $=null,w=null;for(let E of this._def.checks)if(E.kind==="finite"||E.kind==="int"||E.kind==="multipleOf")return!0;else if(E.kind==="min"){if(w===null||E.value>w)w=E.value}else if(E.kind==="max"){if($===null||E.value<$)$=E.value}return Number.isFinite(w)&&Number.isFinite($)}};_w.create=($)=>{return new _w({checks:[],typeName:a.ZodNumber,coerce:$?.coerce||!1,...X0($)})};vw=class vw extends G0{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch{return this._getInvalidInput($)}if(this._getType($)!==f.bigint)return this._getInvalidInput($);let E=void 0,X=new j$;for(let G of this._def.checks)if(G.kind==="min"){if(G.inclusive?$.data<G.value:$.data<=G.value)E=this._getOrReturnCtx($,E),g(E,{code:_.too_small,type:"bigint",minimum:G.value,inclusive:G.inclusive,message:G.message}),X.dirty()}else if(G.kind==="max"){if(G.inclusive?$.data>G.value:$.data>=G.value)E=this._getOrReturnCtx($,E),g(E,{code:_.too_big,type:"bigint",maximum:G.value,inclusive:G.inclusive,message:G.message}),X.dirty()}else if(G.kind==="multipleOf"){if($.data%G.value!==BigInt(0))E=this._getOrReturnCtx($,E),g(E,{code:_.not_multiple_of,multipleOf:G.value,message:G.message}),X.dirty()}else Y0.assertNever(G);return{status:X.value,value:$.data}}_getInvalidInput($){let w=this._getOrReturnCtx($);return g(w,{code:_.invalid_type,expected:f.bigint,received:w.parsedType}),d}gte($,w){return this.setLimit("min",$,!0,c.toString(w))}gt($,w){return this.setLimit("min",$,!1,c.toString(w))}lte($,w){return this.setLimit("max",$,!0,c.toString(w))}lt($,w){return this.setLimit("max",$,!1,c.toString(w))}setLimit($,w,E,X){return new vw({...this._def,checks:[...this._def.checks,{kind:$,value:w,inclusive:E,message:c.toString(X)}]})}_addCheck($){return new vw({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:c.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:c.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:c.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:c.toString($)})}multipleOf($,w){return this._addCheck({kind:"multipleOf",value:$,message:c.toString(w)})}get minValue(){let $=null;for(let w of this._def.checks)if(w.kind==="min"){if($===null||w.value>$)$=w.value}return $}get maxValue(){let $=null;for(let w of this._def.checks)if(w.kind==="max"){if($===null||w.value<$)$=w.value}return $}};vw.create=($)=>{return new vw({checks:[],typeName:a.ZodBigInt,coerce:$?.coerce??!1,...X0($)})};uE=class uE extends G0{_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==f.boolean){let E=this._getOrReturnCtx($);return g(E,{code:_.invalid_type,expected:f.boolean,received:E.parsedType}),d}return P$($.data)}};uE.create=($)=>{return new uE({typeName:a.ZodBoolean,coerce:$?.coerce||!1,...X0($)})};DE=class DE extends G0{_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==f.date){let G=this._getOrReturnCtx($);return g(G,{code:_.invalid_type,expected:f.date,received:G.parsedType}),d}if(Number.isNaN($.data.getTime())){let G=this._getOrReturnCtx($);return g(G,{code:_.invalid_date}),d}let E=new j$,X=void 0;for(let G of this._def.checks)if(G.kind==="min"){if($.data.getTime()<G.value)X=this._getOrReturnCtx($,X),g(X,{code:_.too_small,message:G.message,inclusive:!0,exact:!1,minimum:G.value,type:"date"}),E.dirty()}else if(G.kind==="max"){if($.data.getTime()>G.value)X=this._getOrReturnCtx($,X),g(X,{code:_.too_big,message:G.message,inclusive:!0,exact:!1,maximum:G.value,type:"date"}),E.dirty()}else Y0.assertNever(G);return{status:E.value,value:new Date($.data.getTime())}}_addCheck($){return new DE({...this._def,checks:[...this._def.checks,$]})}min($,w){return this._addCheck({kind:"min",value:$.getTime(),message:c.toString(w)})}max($,w){return this._addCheck({kind:"max",value:$.getTime(),message:c.toString(w)})}get minDate(){let $=null;for(let w of this._def.checks)if(w.kind==="min"){if($===null||w.value>$)$=w.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let w of this._def.checks)if(w.kind==="max"){if($===null||w.value<$)$=w.value}return $!=null?new Date($):null}};DE.create=($)=>{return new DE({checks:[],coerce:$?.coerce||!1,typeName:a.ZodDate,...X0($)})};GG=class GG extends G0{_parse($){if(this._getType($)!==f.symbol){let E=this._getOrReturnCtx($);return g(E,{code:_.invalid_type,expected:f.symbol,received:E.parsedType}),d}return P$($.data)}};GG.create=($)=>{return new GG({typeName:a.ZodSymbol,...X0($)})};hE=class hE extends G0{_parse($){if(this._getType($)!==f.undefined){let E=this._getOrReturnCtx($);return g(E,{code:_.invalid_type,expected:f.undefined,received:E.parsedType}),d}return P$($.data)}};hE.create=($)=>{return new hE({typeName:a.ZodUndefined,...X0($)})};cE=class cE extends G0{_parse($){if(this._getType($)!==f.null){let E=this._getOrReturnCtx($);return g(E,{code:_.invalid_type,expected:f.null,received:E.parsedType}),d}return P$($.data)}};cE.create=($)=>{return new cE({typeName:a.ZodNull,...X0($)})};NE=class NE extends G0{constructor(){super(...arguments);this._any=!0}_parse($){return P$($.data)}};NE.create=($)=>{return new NE({typeName:a.ZodAny,...X0($)})};Cw=class Cw extends G0{constructor(){super(...arguments);this._unknown=!0}_parse($){return P$($.data)}};Cw.create=($)=>{return new Cw({typeName:a.ZodUnknown,...X0($)})};t1=class t1 extends G0{_parse($){let w=this._getOrReturnCtx($);return g(w,{code:_.invalid_type,expected:f.never,received:w.parsedType}),d}};t1.create=($)=>{return new t1({typeName:a.ZodNever,...X0($)})};JG=class JG extends G0{_parse($){if(this._getType($)!==f.undefined){let E=this._getOrReturnCtx($);return g(E,{code:_.invalid_type,expected:f.void,received:E.parsedType}),d}return P$($.data)}};JG.create=($)=>{return new JG({typeName:a.ZodVoid,...X0($)})};P1=class P1 extends G0{_parse($){let{ctx:w,status:E}=this._processInputParams($),X=this._def;if(w.parsedType!==f.array)return g(w,{code:_.invalid_type,expected:f.array,received:w.parsedType}),d;if(X.exactLength!==null){let J=w.data.length>X.exactLength.value,A=w.data.length<X.exactLength.value;if(J||A)g(w,{code:J?_.too_big:_.too_small,minimum:A?X.exactLength.value:void 0,maximum:J?X.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:X.exactLength.message}),E.dirty()}if(X.minLength!==null){if(w.data.length<X.minLength.value)g(w,{code:_.too_small,minimum:X.minLength.value,type:"array",inclusive:!0,exact:!1,message:X.minLength.message}),E.dirty()}if(X.maxLength!==null){if(w.data.length>X.maxLength.value)g(w,{code:_.too_big,maximum:X.maxLength.value,type:"array",inclusive:!0,exact:!1,message:X.maxLength.message}),E.dirty()}if(w.common.async)return Promise.all([...w.data].map((J,A)=>{return X.type._parseAsync(new S1(w,J,w.path,A))})).then((J)=>{return j$.mergeArray(E,J)});let G=[...w.data].map((J,A)=>{return X.type._parseSync(new S1(w,J,w.path,A))});return j$.mergeArray(E,G)}get element(){return this._def.type}min($,w){return new P1({...this._def,minLength:{value:$,message:c.toString(w)}})}max($,w){return new P1({...this._def,maxLength:{value:$,message:c.toString(w)}})}length($,w){return new P1({...this._def,exactLength:{value:$,message:c.toString(w)}})}nonempty($){return this.min(1,$)}};P1.create=($,w)=>{return new P1({type:$,minLength:null,maxLength:null,exactLength:null,typeName:a.ZodArray,...X0(w)})};l0=class l0 extends G0{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let $=this._def.shape(),w=Y0.objectKeys($);return this._cached={shape:$,keys:w},this._cached}_parse($){if(this._getType($)!==f.object){let N=this._getOrReturnCtx($);return g(N,{code:_.invalid_type,expected:f.object,received:N.parsedType}),d}let{status:E,ctx:X}=this._processInputParams($),{shape:G,keys:J}=this._getCached(),A=[];if(!(this._def.catchall instanceof t1&&this._def.unknownKeys==="strip")){for(let N in X.data)if(!J.includes(N))A.push(N)}let D=[];for(let N of J){let W=G[N],O=X.data[N];D.push({key:{status:"valid",value:N},value:W._parse(new S1(X,O,X.path,N)),alwaysSet:N in X.data})}if(this._def.catchall instanceof t1){let N=this._def.unknownKeys;if(N==="passthrough")for(let W of A)D.push({key:{status:"valid",value:W},value:{status:"valid",value:X.data[W]}});else if(N==="strict"){if(A.length>0)g(X,{code:_.unrecognized_keys,keys:A}),E.dirty()}else if(N==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let N=this._def.catchall;for(let W of A){let O=X.data[W];D.push({key:{status:"valid",value:W},value:N._parse(new S1(X,O,X.path,W)),alwaysSet:W in X.data})}}if(X.common.async)return Promise.resolve().then(async()=>{let N=[];for(let W of D){let O=await W.key,Y=await W.value;N.push({key:O,value:Y,alwaysSet:W.alwaysSet})}return N}).then((N)=>{return j$.mergeObjectSync(E,N)});else return j$.mergeObjectSync(E,D)}get shape(){return this._def.shape()}strict($){return c.errToObj,new l0({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(w,E)=>{let X=this._def.errorMap?.(w,E).message??E.defaultError;if(w.code==="unrecognized_keys")return{message:c.errToObj($).message??X};return{message:X}}}:{}})}strip(){return new l0({...this._def,unknownKeys:"strip"})}passthrough(){return new l0({...this._def,unknownKeys:"passthrough"})}extend($){return new l0({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new l0({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:a.ZodObject})}setKey($,w){return this.augment({[$]:w})}catchall($){return new l0({...this._def,catchall:$})}pick($){let w={};for(let E of Y0.objectKeys($))if($[E]&&this.shape[E])w[E]=this.shape[E];return new l0({...this._def,shape:()=>w})}omit($){let w={};for(let E of Y0.objectKeys(this.shape))if(!$[E])w[E]=this.shape[E];return new l0({...this._def,shape:()=>w})}deepPartial(){return yE(this)}partial($){let w={};for(let E of Y0.objectKeys(this.shape)){let X=this.shape[E];if($&&!$[E])w[E]=X;else w[E]=X.optional()}return new l0({...this._def,shape:()=>w})}required($){let w={};for(let E of Y0.objectKeys(this.shape))if($&&!$[E])w[E]=this.shape[E];else{let G=this.shape[E];while(G instanceof q1)G=G._def.innerType;w[E]=G}return new l0({...this._def,shape:()=>w})}keyof(){return cO(Y0.objectKeys(this.shape))}};l0.create=($,w)=>{return new l0({shape:()=>$,unknownKeys:"strip",catchall:t1.create(),typeName:a.ZodObject,...X0(w)})};l0.strictCreate=($,w)=>{return new l0({shape:()=>$,unknownKeys:"strict",catchall:t1.create(),typeName:a.ZodObject,...X0(w)})};l0.lazycreate=($,w)=>{return new l0({shape:$,unknownKeys:"strip",catchall:t1.create(),typeName:a.ZodObject,...X0(w)})};nE=class nE extends G0{_parse($){let{ctx:w}=this._processInputParams($),E=this._def.options;function X(G){for(let A of G)if(A.result.status==="valid")return A.result;for(let A of G)if(A.result.status==="dirty")return w.common.issues.push(...A.ctx.common.issues),A.result;let J=G.map((A)=>new r$(A.ctx.common.issues));return g(w,{code:_.invalid_union,unionErrors:J}),d}if(w.common.async)return Promise.all(E.map(async(G)=>{let J={...w,common:{...w.common,issues:[]},parent:null};return{result:await G._parseAsync({data:w.data,path:w.path,parent:J}),ctx:J}})).then(X);else{let G=void 0,J=[];for(let D of E){let N={...w,common:{...w.common,issues:[]},parent:null},W=D._parseSync({data:w.data,path:w.path,parent:N});if(W.status==="valid")return W;else if(W.status==="dirty"&&!G)G={result:W,ctx:N};if(N.common.issues.length)J.push(N.common.issues)}if(G)return w.common.issues.push(...G.ctx.common.issues),G.result;let A=J.map((D)=>new r$(D));return g(w,{code:_.invalid_union,unionErrors:A}),d}}get options(){return this._def.options}};nE.create=($,w)=>{return new nE({options:$,typeName:a.ZodUnion,...X0(w)})};YJ=class YJ extends G0{_parse($){let{ctx:w}=this._processInputParams($);if(w.parsedType!==f.object)return g(w,{code:_.invalid_type,expected:f.object,received:w.parsedType}),d;let E=this.discriminator,X=w.data[E],G=this.optionsMap.get(X);if(!G)return g(w,{code:_.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[E]}),d;if(w.common.async)return G._parseAsync({data:w.data,path:w.path,parent:w});else return G._parseSync({data:w.data,path:w.path,parent:w})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,w,E){let X=new Map;for(let G of w){let J=Uw(G.shape[$]);if(!J.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let A of J){if(X.has(A))throw Error(`Discriminator property ${String($)} has duplicate value ${String(A)}`);X.set(A,G)}}return new YJ({typeName:a.ZodDiscriminatedUnion,discriminator:$,options:w,optionsMap:X,...X0(E)})}};mE=class mE extends G0{_parse($){let{status:w,ctx:E}=this._processInputParams($),X=(G,J)=>{if(OJ(G)||OJ(J))return d;let A=PD(G.value,J.value);if(!A.valid)return g(E,{code:_.invalid_intersection_types}),d;if(UJ(G)||UJ(J))w.dirty();return{status:w.value,value:A.data}};if(E.common.async)return Promise.all([this._def.left._parseAsync({data:E.data,path:E.path,parent:E}),this._def.right._parseAsync({data:E.data,path:E.path,parent:E})]).then(([G,J])=>X(G,J));else return X(this._def.left._parseSync({data:E.data,path:E.path,parent:E}),this._def.right._parseSync({data:E.data,path:E.path,parent:E}))}};mE.create=($,w,E)=>{return new mE({left:$,right:w,typeName:a.ZodIntersection,...X0(E)})};i1=class i1 extends G0{_parse($){let{status:w,ctx:E}=this._processInputParams($);if(E.parsedType!==f.array)return g(E,{code:_.invalid_type,expected:f.array,received:E.parsedType}),d;if(E.data.length<this._def.items.length)return g(E,{code:_.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),d;if(!this._def.rest&&E.data.length>this._def.items.length)g(E,{code:_.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),w.dirty();let G=[...E.data].map((J,A)=>{let D=this._def.items[A]||this._def.rest;if(!D)return null;return D._parse(new S1(E,J,E.path,A))}).filter((J)=>!!J);if(E.common.async)return Promise.all(G).then((J)=>{return j$.mergeArray(w,J)});else return j$.mergeArray(w,G)}get items(){return this._def.items}rest($){return new i1({...this._def,rest:$})}};i1.create=($,w)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new i1({items:$,typeName:a.ZodTuple,rest:null,...X0(w)})};AG=class AG extends G0{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:w,ctx:E}=this._processInputParams($);if(E.parsedType!==f.object)return g(E,{code:_.invalid_type,expected:f.object,received:E.parsedType}),d;let X=[],G=this._def.keyType,J=this._def.valueType;for(let A in E.data)X.push({key:G._parse(new S1(E,A,E.path,A)),value:J._parse(new S1(E,E.data[A],E.path,A)),alwaysSet:A in E.data});if(E.common.async)return j$.mergeObjectAsync(w,X);else return j$.mergeObjectSync(w,X)}get element(){return this._def.valueType}static create($,w,E){if(w instanceof G0)return new AG({keyType:$,valueType:w,typeName:a.ZodRecord,...X0(E)});return new AG({keyType:V1.create(),valueType:$,typeName:a.ZodRecord,...X0(w)})}};DG=class DG extends G0{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:w,ctx:E}=this._processInputParams($);if(E.parsedType!==f.map)return g(E,{code:_.invalid_type,expected:f.map,received:E.parsedType}),d;let X=this._def.keyType,G=this._def.valueType,J=[...E.data.entries()].map(([A,D],N)=>{return{key:X._parse(new S1(E,A,E.path,[N,"key"])),value:G._parse(new S1(E,D,E.path,[N,"value"]))}});if(E.common.async){let A=new Map;return Promise.resolve().then(async()=>{for(let D of J){let N=await D.key,W=await D.value;if(N.status==="aborted"||W.status==="aborted")return d;if(N.status==="dirty"||W.status==="dirty")w.dirty();A.set(N.value,W.value)}return{status:w.value,value:A}})}else{let A=new Map;for(let D of J){let{key:N,value:W}=D;if(N.status==="aborted"||W.status==="aborted")return d;if(N.status==="dirty"||W.status==="dirty")w.dirty();A.set(N.value,W.value)}return{status:w.value,value:A}}}};DG.create=($,w,E)=>{return new DG({valueType:w,keyType:$,typeName:a.ZodMap,...X0(E)})};WE=class WE extends G0{_parse($){let{status:w,ctx:E}=this._processInputParams($);if(E.parsedType!==f.set)return g(E,{code:_.invalid_type,expected:f.set,received:E.parsedType}),d;let X=this._def;if(X.minSize!==null){if(E.data.size<X.minSize.value)g(E,{code:_.too_small,minimum:X.minSize.value,type:"set",inclusive:!0,exact:!1,message:X.minSize.message}),w.dirty()}if(X.maxSize!==null){if(E.data.size>X.maxSize.value)g(E,{code:_.too_big,maximum:X.maxSize.value,type:"set",inclusive:!0,exact:!1,message:X.maxSize.message}),w.dirty()}let G=this._def.valueType;function J(D){let N=new Set;for(let W of D){if(W.status==="aborted")return d;if(W.status==="dirty")w.dirty();N.add(W.value)}return{status:w.value,value:N}}let A=[...E.data.values()].map((D,N)=>G._parse(new S1(E,D,E.path,N)));if(E.common.async)return Promise.all(A).then((D)=>J(D));else return J(A)}min($,w){return new WE({...this._def,minSize:{value:$,message:c.toString(w)}})}max($,w){return new WE({...this._def,maxSize:{value:$,message:c.toString(w)}})}size($,w){return this.min($,w).max($,w)}nonempty($){return this.min(1,$)}};WE.create=($,w)=>{return new WE({valueType:$,minSize:null,maxSize:null,typeName:a.ZodSet,...X0(w)})};gE=class gE extends G0{constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:w}=this._processInputParams($);if(w.parsedType!==f.function)return g(w,{code:_.invalid_type,expected:f.function,received:w.parsedType}),d;function E(A,D){return XG({data:A,path:w.path,errorMaps:[w.common.contextualErrorMap,w.schemaErrorMap,fE(),Ow].filter((N)=>!!N),issueData:{code:_.invalid_arguments,argumentsError:D}})}function X(A,D){return XG({data:A,path:w.path,errorMaps:[w.common.contextualErrorMap,w.schemaErrorMap,fE(),Ow].filter((N)=>!!N),issueData:{code:_.invalid_return_type,returnTypeError:D}})}let G={errorMap:w.common.contextualErrorMap},J=w.data;if(this._def.returns instanceof OE){let A=this;return P$(async function(...D){let N=new r$([]),W=await A._def.args.parseAsync(D,G).catch((H)=>{throw N.addIssue(E(D,H)),N}),O=await Reflect.apply(J,this,W);return await A._def.returns._def.type.parseAsync(O,G).catch((H)=>{throw N.addIssue(X(O,H)),N})})}else{let A=this;return P$(function(...D){let N=A._def.args.safeParse(D,G);if(!N.success)throw new r$([E(D,N.error)]);let W=Reflect.apply(J,this,N.data),O=A._def.returns.safeParse(W,G);if(!O.success)throw new r$([X(W,O.error)]);return O.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new gE({...this._def,args:i1.create($).rest(Cw.create())})}returns($){return new gE({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,w,E){return new gE({args:$?$:i1.create([]).rest(Cw.create()),returns:w||Cw.create(),typeName:a.ZodFunction,...X0(E)})}};rE=class rE extends G0{get schema(){return this._def.getter()}_parse($){let{ctx:w}=this._processInputParams($);return this._def.getter()._parse({data:w.data,path:w.path,parent:w})}};rE.create=($,w)=>{return new rE({getter:$,typeName:a.ZodLazy,...X0(w)})};pE=class pE extends G0{_parse($){if($.data!==this._def.value){let w=this._getOrReturnCtx($);return g(w,{received:w.data,code:_.invalid_literal,expected:this._def.value}),d}return{status:"valid",value:$.data}}get value(){return this._def.value}};pE.create=($,w)=>{return new pE({value:$,typeName:a.ZodLiteral,...X0(w)})};fw=class fw extends G0{_parse($){if(typeof $.data!=="string"){let w=this._getOrReturnCtx($),E=this._def.values;return g(w,{expected:Y0.joinValues(E),received:w.parsedType,code:_.invalid_type}),d}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let w=this._getOrReturnCtx($),E=this._def.values;return g(w,{received:w.data,code:_.invalid_enum_value,options:E}),d}return P$($.data)}get options(){return this._def.values}get enum(){let $={};for(let w of this._def.values)$[w]=w;return $}get Values(){let $={};for(let w of this._def.values)$[w]=w;return $}get Enum(){let $={};for(let w of this._def.values)$[w]=w;return $}extract($,w=this._def){return fw.create($,{...this._def,...w})}exclude($,w=this._def){return fw.create(this.options.filter((E)=>!$.includes(E)),{...this._def,...w})}};fw.create=cO;oE=class oE extends G0{_parse($){let w=Y0.getValidEnumValues(this._def.values),E=this._getOrReturnCtx($);if(E.parsedType!==f.string&&E.parsedType!==f.number){let X=Y0.objectValues(w);return g(E,{expected:Y0.joinValues(X),received:E.parsedType,code:_.invalid_type}),d}if(!this._cache)this._cache=new Set(Y0.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let X=Y0.objectValues(w);return g(E,{received:E.data,code:_.invalid_enum_value,options:X}),d}return P$($.data)}get enum(){return this._def.values}};oE.create=($,w)=>{return new oE({values:$,typeName:a.ZodNativeEnum,...X0(w)})};OE=class OE extends G0{unwrap(){return this._def.type}_parse($){let{ctx:w}=this._processInputParams($);if(w.parsedType!==f.promise&&w.common.async===!1)return g(w,{code:_.invalid_type,expected:f.promise,received:w.parsedType}),d;let E=w.parsedType===f.promise?w.data:Promise.resolve(w.data);return P$(E.then((X)=>{return this._def.type.parseAsync(X,{path:w.path,errorMap:w.common.contextualErrorMap})}))}};OE.create=($,w)=>{return new OE({type:$,typeName:a.ZodPromise,...X0(w)})};k1=class k1 extends G0{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===a.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:w,ctx:E}=this._processInputParams($),X=this._def.effect||null,G={addIssue:(J)=>{if(g(E,J),J.fatal)w.abort();else w.dirty()},get path(){return E.path}};if(G.addIssue=G.addIssue.bind(G),X.type==="preprocess"){let J=X.transform(E.data,G);if(E.common.async)return Promise.resolve(J).then(async(A)=>{if(w.value==="aborted")return d;let D=await this._def.schema._parseAsync({data:A,path:E.path,parent:E});if(D.status==="aborted")return d;if(D.status==="dirty")return AE(D.value);if(w.value==="dirty")return AE(D.value);return D});else{if(w.value==="aborted")return d;let A=this._def.schema._parseSync({data:J,path:E.path,parent:E});if(A.status==="aborted")return d;if(A.status==="dirty")return AE(A.value);if(w.value==="dirty")return AE(A.value);return A}}if(X.type==="refinement"){let J=(A)=>{let D=X.refinement(A,G);if(E.common.async)return Promise.resolve(D);if(D instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return A};if(E.common.async===!1){let A=this._def.schema._parseSync({data:E.data,path:E.path,parent:E});if(A.status==="aborted")return d;if(A.status==="dirty")w.dirty();return J(A.value),{status:w.value,value:A.value}}else return this._def.schema._parseAsync({data:E.data,path:E.path,parent:E}).then((A)=>{if(A.status==="aborted")return d;if(A.status==="dirty")w.dirty();return J(A.value).then(()=>{return{status:w.value,value:A.value}})})}if(X.type==="transform")if(E.common.async===!1){let J=this._def.schema._parseSync({data:E.data,path:E.path,parent:E});if(!Zw(J))return d;let A=X.transform(J.value,G);if(A instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:w.value,value:A}}else return this._def.schema._parseAsync({data:E.data,path:E.path,parent:E}).then((J)=>{if(!Zw(J))return d;return Promise.resolve(X.transform(J.value,G)).then((A)=>({status:w.value,value:A}))});Y0.assertNever(X)}};k1.create=($,w,E)=>{return new k1({schema:$,typeName:a.ZodEffects,effect:w,...X0(E)})};k1.createWithPreprocess=($,w,E)=>{return new k1({schema:w,effect:{type:"preprocess",transform:$},typeName:a.ZodEffects,...X0(E)})};q1=class q1 extends G0{_parse($){if(this._getType($)===f.undefined)return P$(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}};q1.create=($,w)=>{return new q1({innerType:$,typeName:a.ZodOptional,...X0(w)})};Yw=class Yw extends G0{_parse($){if(this._getType($)===f.null)return P$(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}};Yw.create=($,w)=>{return new Yw({innerType:$,typeName:a.ZodNullable,...X0(w)})};tE=class tE extends G0{_parse($){let{ctx:w}=this._processInputParams($),E=w.data;if(w.parsedType===f.undefined)E=this._def.defaultValue();return this._def.innerType._parse({data:E,path:w.path,parent:w})}removeDefault(){return this._def.innerType}};tE.create=($,w)=>{return new tE({innerType:$,typeName:a.ZodDefault,defaultValue:typeof w.default==="function"?w.default:()=>w.default,...X0(w)})};iE=class iE extends G0{_parse($){let{ctx:w}=this._processInputParams($),E={...w,common:{...w.common,issues:[]}},X=this._def.innerType._parse({data:E.data,path:E.path,parent:{...E}});if(xE(X))return X.then((G)=>{return{status:"valid",value:G.status==="valid"?G.value:this._def.catchValue({get error(){return new r$(E.common.issues)},input:E.data})}});else return{status:"valid",value:X.status==="valid"?X.value:this._def.catchValue({get error(){return new r$(E.common.issues)},input:E.data})}}removeCatch(){return this._def.innerType}};iE.create=($,w)=>{return new iE({innerType:$,typeName:a.ZodCatch,catchValue:typeof w.catch==="function"?w.catch:()=>w.catch,...X0(w)})};NG=class NG extends G0{_parse($){if(this._getType($)!==f.nan){let E=this._getOrReturnCtx($);return g(E,{code:_.invalid_type,expected:f.nan,received:E.parsedType}),d}return{status:"valid",value:$.data}}};NG.create=($)=>{return new NG({typeName:a.ZodNaN,...X0($)})};NP=Symbol("zod_brand");HJ=class HJ extends G0{_parse($){let{ctx:w}=this._processInputParams($),E=w.data;return this._def.type._parse({data:E,path:w.path,parent:w})}unwrap(){return this._def.type}};WG=class WG extends G0{_parse($){let{status:w,ctx:E}=this._processInputParams($);if(E.common.async)return(async()=>{let G=await this._def.in._parseAsync({data:E.data,path:E.path,parent:E});if(G.status==="aborted")return d;if(G.status==="dirty")return w.dirty(),AE(G.value);else return this._def.out._parseAsync({data:G.value,path:E.path,parent:E})})();else{let X=this._def.in._parseSync({data:E.data,path:E.path,parent:E});if(X.status==="aborted")return d;if(X.status==="dirty")return w.dirty(),{status:"dirty",value:X.value};else return this._def.out._parseSync({data:X.value,path:E.path,parent:E})}}static create($,w){return new WG({in:$,out:w,typeName:a.ZodPipeline})}};dE=class dE extends G0{_parse($){let w=this._def.innerType._parse($),E=(X)=>{if(Zw(X))X.value=Object.freeze(X.value);return X};return xE(w)?w.then((X)=>E(X)):E(w)}unwrap(){return this._def.innerType}};dE.create=($,w)=>{return new dE({innerType:$,typeName:a.ZodReadonly,...X0(w)})};WP={object:l0.lazycreate};(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(a||(a={}));mO=V1.create,rO=_w.create,UP=NG.create,YP=vw.create,pO=uE.create,HP=DE.create,LP=GG.create,FP=hE.create,jP=cE.create,MP=NE.create,RP=Cw.create,zP=t1.create,TP=JG.create,BP=P1.create,QP=l0.create,IP=l0.strictCreate,KP=nE.create,VP=YJ.create,PP=mE.create,qP=i1.create,SP=AG.create,kP=DG.create,bP=WE.create,ZP=gE.create,CP=rE.create,_P=pE.create,vP=fw.create,fP=oE.create,xP=OE.create,yP=k1.create,gP=q1.create,uP=Yw.create,hP=k1.createWithPreprocess,cP=WG.create,pP={string:($)=>V1.create({...$,coerce:!0}),number:($)=>_w.create({...$,coerce:!0}),boolean:($)=>uE.create({...$,coerce:!0}),bigint:($)=>vw.create({...$,coerce:!0}),date:($)=>DE.create({...$,coerce:!0})},oP=d});var U={};Ww(U,{void:()=>TP,util:()=>Y0,unknown:()=>RP,union:()=>KP,undefined:()=>FP,tuple:()=>qP,transformer:()=>yP,symbol:()=>LP,string:()=>mO,strictObject:()=>IP,setErrorMap:()=>uV,set:()=>bP,record:()=>SP,quotelessJson:()=>yV,promise:()=>xP,preprocess:()=>hP,pipeline:()=>cP,ostring:()=>nP,optional:()=>gP,onumber:()=>mP,oboolean:()=>rP,objectUtil:()=>QD,object:()=>QP,number:()=>rO,nullable:()=>uP,null:()=>jP,never:()=>zP,nativeEnum:()=>fP,nan:()=>UP,map:()=>kP,makeIssue:()=>XG,literal:()=>_P,lazy:()=>CP,late:()=>WP,isValid:()=>Zw,isDirty:()=>UJ,isAsync:()=>xE,isAborted:()=>OJ,intersection:()=>PP,instanceof:()=>OP,getParsedType:()=>o1,getErrorMap:()=>fE,function:()=>ZP,enum:()=>vP,effect:()=>yP,discriminatedUnion:()=>VP,defaultErrorMap:()=>Ow,datetimeRegex:()=>hO,date:()=>HP,custom:()=>nO,coerce:()=>pP,boolean:()=>pO,bigint:()=>YP,array:()=>BP,any:()=>MP,addIssueToContext:()=>g,ZodVoid:()=>JG,ZodUnknown:()=>Cw,ZodUnion:()=>nE,ZodUndefined:()=>hE,ZodType:()=>G0,ZodTuple:()=>i1,ZodTransformer:()=>k1,ZodSymbol:()=>GG,ZodString:()=>V1,ZodSet:()=>WE,ZodSchema:()=>G0,ZodRecord:()=>AG,ZodReadonly:()=>dE,ZodPromise:()=>OE,ZodPipeline:()=>WG,ZodParsedType:()=>f,ZodOptional:()=>q1,ZodObject:()=>l0,ZodNumber:()=>_w,ZodNullable:()=>Yw,ZodNull:()=>cE,ZodNever:()=>t1,ZodNativeEnum:()=>oE,ZodNaN:()=>NG,ZodMap:()=>DG,ZodLiteral:()=>pE,ZodLazy:()=>rE,ZodIssueCode:()=>_,ZodIntersection:()=>mE,ZodFunction:()=>gE,ZodFirstPartyTypeKind:()=>a,ZodError:()=>r$,ZodEnum:()=>fw,ZodEffects:()=>k1,ZodDiscriminatedUnion:()=>YJ,ZodDefault:()=>tE,ZodDate:()=>DE,ZodCatch:()=>iE,ZodBranded:()=>HJ,ZodBoolean:()=>uE,ZodBigInt:()=>vw,ZodArray:()=>P1,ZodAny:()=>NE,Schema:()=>G0,ParseStatus:()=>j$,OK:()=>P$,NEVER:()=>oP,INVALID:()=>d,EMPTY_PATH:()=>hV,DIRTY:()=>AE,BRAND:()=>NP});var qD=R(()=>{WJ();KD();vO();EG();oO();NJ()});var OG=R(()=>{qD();qD()});import{existsSync as tO,readFileSync as tP}from"fs";import{homedir as lO}from"os";import{join as SD}from"path";function aP($){if($.startsWith("~/"))return SD(lO(),$.slice(2));return $}function dO($){try{return JSON.parse(tP($,"utf-8"))}catch{return{}}}function UG($,w){let E={...$};for(let[X,G]of Object.entries(w))if(G!==null&&typeof G==="object"&&!Array.isArray(G)&&typeof E[X]==="object"&&E[X]!==null)E[X]=UG(E[X],G);else E[X]=G;return E}function eP(){let $={};if(process.env.ORC_DB_PATH)$.db={path:process.env.ORC_DB_PATH};let w={};if(process.env.ORC_API_PORT)w.port=Number(process.env.ORC_API_PORT);if(process.env.ORC_API_HOST)w.host=process.env.ORC_API_HOST;if(process.env.ORC_API_SECRET)w.secret=process.env.ORC_API_SECRET;if(Object.keys(w).length)$.api=w;let E={};if(process.env.ORC_RUNNER_TIMEOUT)E.default_timeout_secs=Number(process.env.ORC_RUNNER_TIMEOUT);if(process.env.ORC_RUNNER_MAX_JOBS)E.max_concurrent_jobs=Number(process.env.ORC_RUNNER_MAX_JOBS);if(process.env.ORC_RUNNER_LOG_DAYS)E.log_retention_days=Number(process.env.ORC_RUNNER_LOG_DAYS);if(Object.keys(E).length)$.runner=E;let X={};if(process.env.ORC_SNAPSHOT_MAX_BYTES)X.snapshot_max_bytes=Number(process.env.ORC_SNAPSHOT_MAX_BYTES);if(process.env.ORC_LAYER1_TASKS)X.layer1_task_limit=Number(process.env.ORC_LAYER1_TASKS);if(process.env.ORC_LAYER1_MEMORIES)X.layer1_memory_limit=Number(process.env.ORC_LAYER1_MEMORIES);if(Object.keys(X).length)$.context=X;let G={};if(process.env.ORC_TELEGRAM_TOKEN)G.telegram={token:process.env.ORC_TELEGRAM_TOKEN,enabled:!0};if(process.env.ORC_SLACK_BOT_TOKEN||process.env.ORC_SLACK_APP_TOKEN)G.slack={bot_token:process.env.ORC_SLACK_BOT_TOKEN,app_token:process.env.ORC_SLACK_APP_TOKEN,enabled:!0};if(Object.keys(G).length)$.gateway=G;let J={};if(process.env.ORC_SPEECH_PROVIDER)J.provider=process.env.ORC_SPEECH_PROVIDER;if(process.env.ORC_SPEECH_LANGUAGE)J.language=process.env.ORC_SPEECH_LANGUAGE;if(process.env.ORC_OPENAI_API_KEY)J.openai={api_key:process.env.ORC_OPENAI_API_KEY};if(process.env.ORC_GROQ_API_KEY)J.groq={api_key:process.env.ORC_GROQ_API_KEY};if(process.env.ORC_QWEN_API_KEY)J.qwen={api_key:process.env.ORC_QWEN_API_KEY};if(Object.keys(J).length)J.enabled=!0,$.speech=J;let A={};if(process.env.ORC_TTS_PROVIDER)A.provider=process.env.ORC_TTS_PROVIDER;if(process.env.ORC_TTS_VOICE)A.voice=process.env.ORC_TTS_VOICE;if(process.env.ORC_TTS_MODE)A.mode=process.env.ORC_TTS_MODE;if(Object.keys(A).length)A.enabled=!0,$.tts=A;return $}function O0($){if(LJ&&!$)return LJ;let w=SD(lO(),".orc","config.json"),E=SD(process.cwd(),".orc","config.json"),X={};if(tO(w))X=UG(X,dO(w));if(tO(E))X=UG(X,dO(E));if(X=UG(X,eP()),$)X=UG(X,$);if(X.bridge&&!X.gateway)X.gateway=X.bridge;delete X.bridge;let G=sP.safeParse(X);if(!G.success)throw Error(`Invalid orc config:
|
|
4
|
+
${G.error.message}`);return G.data.db.path=aP(G.data.db.path),LJ=G.data,LJ}var iP,iO,YG,dP,lP,sP,LJ=null;var C$=R(()=>{OG();iP=U.enum(["direct","agent:claude","agent:codex","agent:cursor","multi"]).or(U.string().startsWith("job:")).default("direct"),iO=U.object({enabled:U.boolean().default(!1),token:U.string().optional(),bot_token:U.string().optional(),app_token:U.string().optional(),authorized_users:U.array(U.union([U.string(),U.number()])).default([]),default_chat_id:U.string().optional(),mode:iP,allow_channel_mentions:U.boolean().default(!0),share_session_in_channel:U.boolean().default(!1),streaming_preview:U.boolean().default(!0)}),YG=U.object({api_key:U.string().optional(),base_url:U.string().optional(),model:U.string().optional()}),dP=U.object({enabled:U.boolean().default(!1),provider:U.enum(["openai","groq","qwen"]).default("openai"),language:U.string().default(""),openai:YG.default({}),groq:YG.default({}),qwen:YG.default({})}),lP=U.object({enabled:U.boolean().default(!1),provider:U.enum(["openai","qwen"]).default("openai"),voice:U.string().default("alloy"),mode:U.enum(["voice_only","always"]).default("voice_only"),max_text_len:U.number().int().min(0).default(0),openai:YG.default({}),qwen:YG.default({})}),sP=U.object({db:U.object({path:U.string().default("~/.orc/orc.db")}).default({}),api:U.object({port:U.number().int().default(7700),host:U.string().default("127.0.0.1"),secret:U.string().optional()}).default({}),mcp:U.object({transport:U.enum(["stdio","http"]).default("stdio"),port:U.number().int().default(7701)}).default({}),gateway:U.object({telegram:iO.default({}),slack:iO.default({})}).default({}),runner:U.object({default_timeout_secs:U.number().int().default(300),max_concurrent_jobs:U.number().int().default(5),log_retention_days:U.number().int().default(30)}).default({}),context:U.object({snapshot_max_bytes:U.number().int().default(2048),layer1_task_limit:U.number().int().default(10),layer1_memory_limit:U.number().int().default(5)}).default({}),speech:dP.default({}),tts:lP.default({}),activeProject:U.string().optional()})});import{readFileSync as $q}from"fs";import{dirname as wq,join as Eq}from"path";import{fileURLToPath as Xq}from"url";var kD,lE;var FJ=R(()=>{try{let $=wq(Xq(import.meta.url));kD=JSON.parse($q(Eq($,"..","package.json"),"utf-8")).version}catch{kD=process.env.ORC_VERSION??"0.0.0"}lE=kD});var HG=Z((Gq)=>{class bD extends Error{constructor($,w,E){super(E);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=w,this.exitCode=$,this.nestedError=void 0}}class sO extends bD{constructor($){super(1,"commander.invalidArgument",$);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}Gq.CommanderError=bD;Gq.InvalidArgumentError=sO});var jJ=Z((Wq)=>{var{InvalidArgumentError:Dq}=HG();class aO{constructor($,w){switch(this.description=w||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,$[0]){case"<":this.required=!0,this._name=$.slice(1,-1);break;case"[":this.required=!1,this._name=$.slice(1,-1);break;default:this.required=!0,this._name=$;break}if(this._name.length>3&&this._name.slice(-3)==="...")this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_concatValue($,w){if(w===this.defaultValue||!Array.isArray(w))return[$];return w.concat($)}default($,w){return this.defaultValue=$,this.defaultValueDescription=w,this}argParser($){return this.parseArg=$,this}choices($){return this.argChoices=$.slice(),this.parseArg=(w,E)=>{if(!this.argChoices.includes(w))throw new Dq(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue(w,E);return w},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function Nq($){let w=$.name()+($.variadic===!0?"...":"");return $.required?"<"+w+">":"["+w+"]"}Wq.Argument=aO;Wq.humanReadableArgName=Nq});var ZD=Z((Hq)=>{var{humanReadableArgName:Yq}=jJ();class eO{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext($){this.helpWidth=this.helpWidth??$.helpWidth??80}visibleCommands($){let w=$.commands.filter((X)=>!X._hidden),E=$._getHelpCommand();if(E&&!E._hidden)w.push(E);if(this.sortSubcommands)w.sort((X,G)=>{return X.name().localeCompare(G.name())});return w}compareOptions($,w){let E=(X)=>{return X.short?X.short.replace(/^-/,""):X.long.replace(/^--/,"")};return E($).localeCompare(E(w))}visibleOptions($){let w=$.options.filter((X)=>!X.hidden),E=$._getHelpOption();if(E&&!E.hidden){let X=E.short&&$._findOption(E.short),G=E.long&&$._findOption(E.long);if(!X&&!G)w.push(E);else if(E.long&&!G)w.push($.createOption(E.long,E.description));else if(E.short&&!X)w.push($.createOption(E.short,E.description))}if(this.sortOptions)w.sort(this.compareOptions);return w}visibleGlobalOptions($){if(!this.showGlobalOptions)return[];let w=[];for(let E=$.parent;E;E=E.parent){let X=E.options.filter((G)=>!G.hidden);w.push(...X)}if(this.sortOptions)w.sort(this.compareOptions);return w}visibleArguments($){if($._argsDescription)$.registeredArguments.forEach((w)=>{w.description=w.description||$._argsDescription[w.name()]||""});if($.registeredArguments.find((w)=>w.description))return $.registeredArguments;return[]}subcommandTerm($){let w=$.registeredArguments.map((E)=>Yq(E)).join(" ");return $._name+($._aliases[0]?"|"+$._aliases[0]:"")+($.options.length?" [options]":"")+(w?" "+w:"")}optionTerm($){return $.flags}argumentTerm($){return $.name()}longestSubcommandTermLength($,w){return w.visibleCommands($).reduce((E,X)=>{return Math.max(E,this.displayWidth(w.styleSubcommandTerm(w.subcommandTerm(X))))},0)}longestOptionTermLength($,w){return w.visibleOptions($).reduce((E,X)=>{return Math.max(E,this.displayWidth(w.styleOptionTerm(w.optionTerm(X))))},0)}longestGlobalOptionTermLength($,w){return w.visibleGlobalOptions($).reduce((E,X)=>{return Math.max(E,this.displayWidth(w.styleOptionTerm(w.optionTerm(X))))},0)}longestArgumentTermLength($,w){return w.visibleArguments($).reduce((E,X)=>{return Math.max(E,this.displayWidth(w.styleArgumentTerm(w.argumentTerm(X))))},0)}commandUsage($){let w=$._name;if($._aliases[0])w=w+"|"+$._aliases[0];let E="";for(let X=$.parent;X;X=X.parent)E=X.name()+" "+E;return E+w+" "+$.usage()}commandDescription($){return $.description()}subcommandDescription($){return $.summary()||$.description()}optionDescription($){let w=[];if($.argChoices)w.push(`choices: ${$.argChoices.map((E)=>JSON.stringify(E)).join(", ")}`);if($.defaultValue!==void 0){if($.required||$.optional||$.isBoolean()&&typeof $.defaultValue==="boolean")w.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`)}if($.presetArg!==void 0&&$.optional)w.push(`preset: ${JSON.stringify($.presetArg)}`);if($.envVar!==void 0)w.push(`env: ${$.envVar}`);if(w.length>0)return`${$.description} (${w.join(", ")})`;return $.description}argumentDescription($){let w=[];if($.argChoices)w.push(`choices: ${$.argChoices.map((E)=>JSON.stringify(E)).join(", ")}`);if($.defaultValue!==void 0)w.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`);if(w.length>0){let E=`(${w.join(", ")})`;if($.description)return`${$.description} ${E}`;return E}return $.description}formatHelp($,w){let E=w.padWidth($,w),X=w.helpWidth??80;function G(O,Y){return w.formatItem(O,E,Y,w)}let J=[`${w.styleTitle("Usage:")} ${w.styleUsage(w.commandUsage($))}`,""],A=w.commandDescription($);if(A.length>0)J=J.concat([w.boxWrap(w.styleCommandDescription(A),X),""]);let D=w.visibleArguments($).map((O)=>{return G(w.styleArgumentTerm(w.argumentTerm(O)),w.styleArgumentDescription(w.argumentDescription(O)))});if(D.length>0)J=J.concat([w.styleTitle("Arguments:"),...D,""]);let N=w.visibleOptions($).map((O)=>{return G(w.styleOptionTerm(w.optionTerm(O)),w.styleOptionDescription(w.optionDescription(O)))});if(N.length>0)J=J.concat([w.styleTitle("Options:"),...N,""]);if(w.showGlobalOptions){let O=w.visibleGlobalOptions($).map((Y)=>{return G(w.styleOptionTerm(w.optionTerm(Y)),w.styleOptionDescription(w.optionDescription(Y)))});if(O.length>0)J=J.concat([w.styleTitle("Global Options:"),...O,""])}let W=w.visibleCommands($).map((O)=>{return G(w.styleSubcommandTerm(w.subcommandTerm(O)),w.styleSubcommandDescription(w.subcommandDescription(O)))});if(W.length>0)J=J.concat([w.styleTitle("Commands:"),...W,""]);return J.join(`
|
|
5
|
+
`)}displayWidth($){return $U($).length}styleTitle($){return $}styleUsage($){return $.split(" ").map((w)=>{if(w==="[options]")return this.styleOptionText(w);if(w==="[command]")return this.styleSubcommandText(w);if(w[0]==="["||w[0]==="<")return this.styleArgumentText(w);return this.styleCommandText(w)}).join(" ")}styleCommandDescription($){return this.styleDescriptionText($)}styleOptionDescription($){return this.styleDescriptionText($)}styleSubcommandDescription($){return this.styleDescriptionText($)}styleArgumentDescription($){return this.styleDescriptionText($)}styleDescriptionText($){return $}styleOptionTerm($){return this.styleOptionText($)}styleSubcommandTerm($){return $.split(" ").map((w)=>{if(w==="[options]")return this.styleOptionText(w);if(w[0]==="["||w[0]==="<")return this.styleArgumentText(w);return this.styleSubcommandText(w)}).join(" ")}styleArgumentTerm($){return this.styleArgumentText($)}styleOptionText($){return $}styleArgumentText($){return $}styleSubcommandText($){return $}styleCommandText($){return $}padWidth($,w){return Math.max(w.longestOptionTermLength($,w),w.longestGlobalOptionTermLength($,w),w.longestSubcommandTermLength($,w),w.longestArgumentTermLength($,w))}preformatted($){return/\n[^\S\r\n]/.test($)}formatItem($,w,E,X){let J=" ".repeat(2);if(!E)return J+$;let A=$.padEnd(w+$.length-X.displayWidth($)),D=2,W=(this.helpWidth??80)-w-D-2,O;if(W<this.minWidthToWrap||X.preformatted(E))O=E;else O=X.boxWrap(E,W).replace(/\n/g,`
|
|
6
6
|
`+" ".repeat(w+D));return J+A+" ".repeat(D)+O.replace(/\n/g,`
|
|
7
7
|
${J}`)}boxWrap($,w){if(w<this.minWidthToWrap)return $;let E=$.split(/\r\n|\n/),X=/[\s]*[^\s]+/g,G=[];return E.forEach((J)=>{let A=J.match(X);if(A===null){G.push("");return}let D=[A.shift()],N=this.displayWidth(D[0]);A.forEach((W)=>{let O=this.displayWidth(W);if(N+O<=w){D.push(W),N+=O;return}G.push(D.join(""));let Y=W.trimStart();D=[Y],N=this.displayWidth(Y)}),G.push(D.join(""))}),G.join(`
|
|
8
|
-
`)}}function
|
|
8
|
+
`)}}function $U($){let w=/\x1b\[\d*(;\d*)*m/g;return $.replace(w,"")}Hq.Help=eO;Hq.stripColor=$U});var CD=Z((Rq)=>{var{InvalidArgumentError:jq}=HG();class EU{constructor($,w){this.flags=$,this.description=w||"",this.required=$.includes("<"),this.optional=$.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test($),this.mandatory=!1;let E=Mq($);if(this.short=E.shortFlag,this.long=E.longFlag,this.negate=!1,this.long)this.negate=this.long.startsWith("--no-");this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default($,w){return this.defaultValue=$,this.defaultValueDescription=w,this}preset($){return this.presetArg=$,this}conflicts($){return this.conflictsWith=this.conflictsWith.concat($),this}implies($){let w=$;if(typeof $==="string")w={[$]:!0};return this.implied=Object.assign(this.implied||{},w),this}env($){return this.envVar=$,this}argParser($){return this.parseArg=$,this}makeOptionMandatory($=!0){return this.mandatory=!!$,this}hideHelp($=!0){return this.hidden=!!$,this}_concatValue($,w){if(w===this.defaultValue||!Array.isArray(w))return[$];return w.concat($)}choices($){return this.argChoices=$.slice(),this.parseArg=(w,E)=>{if(!this.argChoices.includes(w))throw new jq(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue(w,E);return w},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return wU(this.name().replace(/^no-/,""));return wU(this.name())}is($){return this.short===$||this.long===$}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class XU{constructor($){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,$.forEach((w)=>{if(w.negate)this.negativeOptions.set(w.attributeName(),w);else this.positiveOptions.set(w.attributeName(),w)}),this.negativeOptions.forEach((w,E)=>{if(this.positiveOptions.has(E))this.dualOptions.add(E)})}valueFromOption($,w){let E=w.attributeName();if(!this.dualOptions.has(E))return!0;let X=this.negativeOptions.get(E).presetArg,G=X!==void 0?X:!1;return w.negate===(G===$)}}function wU($){return $.split("-").reduce((w,E)=>{return w+E[0].toUpperCase()+E.slice(1)})}function Mq($){let w,E,X=/^-[^-]$/,G=/^--[^-]/,J=$.split(/[ |,]+/).concat("guard");if(X.test(J[0]))w=J.shift();if(G.test(J[0]))E=J.shift();if(!w&&X.test(J[0]))w=J.shift();if(!w&&G.test(J[0]))w=E,E=J.shift();if(J[0].startsWith("-")){let A=J[0],D=`option creation failed due to '${A}' in option flags '${$}'`;if(/^-[^-][^-]/.test(A))throw Error(`${D}
|
|
9
9
|
- a short flag is a single dash and a single character
|
|
10
10
|
- either use a single dash and a single character (for a short flag)
|
|
11
11
|
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(X.test(A))throw Error(`${D}
|
|
12
12
|
- too many short flags`);if(G.test(A))throw Error(`${D}
|
|
13
13
|
- too many long flags`);throw Error(`${D}
|
|
14
|
-
- unrecognised flag format`)}if(w===void 0&&E===void 0)throw Error(`option creation failed due to no flags found in '${$}'.`);return{shortFlag:w,longFlag:E}}
|
|
14
|
+
- unrecognised flag format`)}if(w===void 0&&E===void 0)throw Error(`option creation failed due to no flags found in '${$}'.`);return{shortFlag:w,longFlag:E}}Rq.Option=EU;Rq.DualOptions=XU});var GU=Z((Iq)=>{function Bq($,w){if(Math.abs($.length-w.length)>3)return Math.max($.length,w.length);let E=[];for(let X=0;X<=$.length;X++)E[X]=[X];for(let X=0;X<=w.length;X++)E[0][X]=X;for(let X=1;X<=w.length;X++)for(let G=1;G<=$.length;G++){let J=1;if($[G-1]===w[X-1])J=0;else J=1;if(E[G][X]=Math.min(E[G-1][X]+1,E[G][X-1]+1,E[G-1][X-1]+J),G>1&&X>1&&$[G-1]===w[X-2]&&$[G-2]===w[X-1])E[G][X]=Math.min(E[G][X],E[G-2][X-2]+1)}return E[$.length][w.length]}function Qq($,w){if(!w||w.length===0)return"";w=Array.from(new Set(w));let E=$.startsWith("--");if(E)$=$.slice(2),w=w.map((A)=>A.slice(2));let X=[],G=3,J=0.4;if(w.forEach((A)=>{if(A.length<=1)return;let D=Bq($,A),N=Math.max($.length,A.length);if((N-D)/N>J){if(D<G)G=D,X=[A];else if(D===G)X.push(A)}}),X.sort((A,D)=>A.localeCompare(D)),E)X=X.map((A)=>`--${A}`);if(X.length>1)return`
|
|
15
15
|
(Did you mean one of ${X.join(", ")}?)`;if(X.length===1)return`
|
|
16
|
-
(Did you mean ${X[0]}?)`;return""}
|
|
17
|
-
- specify the name in Command constructor or using .name()`);if(w=w||{},w.isDefault)this._defaultCommandName=$._name;if(w.noHelp||w.hidden)$._hidden=!0;return this._registerCommand($),$.parent=this,$._checkForBrokenPassThrough(),this}createArgument($,w){return new
|
|
18
|
-
Expecting one of '${E.join("', '")}'`);if(this._lifeCycleHooks[$])this._lifeCycleHooks[$].push(w);else this._lifeCycleHooks[$]=[w];return this}exitOverride($){if($)this._exitCallback=$;else this._exitCallback=(w)=>{if(w.code!=="commander.executeSubCommandAsync")throw w};return this}_exit($,w,E){if(this._exitCallback)this._exitCallback(new
|
|
19
|
-
- already used by option '${w.flags}'`)}this.options.push($)}_registerCommand($){let w=(X)=>{return[X.name()].concat(X.aliases())},E=w($).find((X)=>this._findCommand(X));if(E){let X=w(this._findCommand(E)).join("|"),G=w($).join("|");throw Error(`cannot add command '${G}' as already have command '${X}'`)}this.commands.push($)}addOption($){this._registerOption($);let w=$.name(),E=$.attributeName();if($.negate){let G=$.long.replace(/^--no-/,"--");if(!this._findOption(G))this.setOptionValueWithSource(E,$.defaultValue===void 0?!0:$.defaultValue,"default")}else if($.defaultValue!==void 0)this.setOptionValueWithSource(E,$.defaultValue,"default");let X=(G,J,A)=>{if(G==null&&$.presetArg!==void 0)G=$.presetArg;let D=this.getOptionValue(E);if(G!==null&&$.parseArg)G=this._callParseArg($,G,D,J);else if(G!==null&&$.variadic)G=$._concatValue(G,D);if(G==null)if($.negate)G=!1;else if($.isBoolean()||$.optional)G=!0;else G="";this.setOptionValueWithSource(E,G,A)};if(this.on("option:"+w,(G)=>{let J=`error: option '${$.flags}' argument '${G}' is invalid.`;X(G,J,"cli")}),$.envVar)this.on("optionEnv:"+w,(G)=>{let J=`error: option '${$.flags}' value '${G}' from env '${$.envVar}' is invalid.`;X(G,J,"env")});return this}_optionEx($,w,E,X,G){if(typeof w==="object"&&w instanceof
|
|
20
|
-
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable($,w,E){if(
|
|
16
|
+
(Did you mean ${X[0]}?)`;return""}Iq.suggestSimilar=Qq});var NU=Z((Zq)=>{var Vq=V$("events").EventEmitter,_D=V$("child_process"),Hw=V$("path"),MJ=V$("fs"),Q0=V$("process"),{Argument:Pq,humanReadableArgName:qq}=jJ(),{CommanderError:vD}=HG(),{Help:Sq,stripColor:kq}=ZD(),{Option:JU,DualOptions:bq}=CD(),{suggestSimilar:AU}=GU();class xD extends Vq{constructor($){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=$||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:(w)=>Q0.stdout.write(w),writeErr:(w)=>Q0.stderr.write(w),outputError:(w,E)=>E(w),getOutHelpWidth:()=>Q0.stdout.isTTY?Q0.stdout.columns:void 0,getErrHelpWidth:()=>Q0.stderr.isTTY?Q0.stderr.columns:void 0,getOutHasColors:()=>fD()??(Q0.stdout.isTTY&&Q0.stdout.hasColors?.()),getErrHasColors:()=>fD()??(Q0.stderr.isTTY&&Q0.stderr.hasColors?.()),stripColor:(w)=>kq(w)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings($){return this._outputConfiguration=$._outputConfiguration,this._helpOption=$._helpOption,this._helpCommand=$._helpCommand,this._helpConfiguration=$._helpConfiguration,this._exitCallback=$._exitCallback,this._storeOptionsAsProperties=$._storeOptionsAsProperties,this._combineFlagAndOptionalValue=$._combineFlagAndOptionalValue,this._allowExcessArguments=$._allowExcessArguments,this._enablePositionalOptions=$._enablePositionalOptions,this._showHelpAfterError=$._showHelpAfterError,this._showSuggestionAfterError=$._showSuggestionAfterError,this}_getCommandAndAncestors(){let $=[];for(let w=this;w;w=w.parent)$.push(w);return $}command($,w,E){let X=w,G=E;if(typeof X==="object"&&X!==null)G=X,X=null;G=G||{};let[,J,A]=$.match(/([^ ]+) *(.*)/),D=this.createCommand(J);if(X)D.description(X),D._executableHandler=!0;if(G.isDefault)this._defaultCommandName=D._name;if(D._hidden=!!(G.noHelp||G.hidden),D._executableFile=G.executableFile||null,A)D.arguments(A);if(this._registerCommand(D),D.parent=this,D.copyInheritedSettings(this),X)return this;return D}createCommand($){return new xD($)}createHelp(){return Object.assign(new Sq,this.configureHelp())}configureHelp($){if($===void 0)return this._helpConfiguration;return this._helpConfiguration=$,this}configureOutput($){if($===void 0)return this._outputConfiguration;return Object.assign(this._outputConfiguration,$),this}showHelpAfterError($=!0){if(typeof $!=="string")$=!!$;return this._showHelpAfterError=$,this}showSuggestionAfterError($=!0){return this._showSuggestionAfterError=!!$,this}addCommand($,w){if(!$._name)throw Error(`Command passed to .addCommand() must have a name
|
|
17
|
+
- specify the name in Command constructor or using .name()`);if(w=w||{},w.isDefault)this._defaultCommandName=$._name;if(w.noHelp||w.hidden)$._hidden=!0;return this._registerCommand($),$.parent=this,$._checkForBrokenPassThrough(),this}createArgument($,w){return new Pq($,w)}argument($,w,E,X){let G=this.createArgument($,w);if(typeof E==="function")G.default(X).argParser(E);else G.default(E);return this.addArgument(G),this}arguments($){return $.trim().split(/ +/).forEach((w)=>{this.argument(w)}),this}addArgument($){let w=this.registeredArguments.slice(-1)[0];if(w&&w.variadic)throw Error(`only the last argument can be variadic '${w.name()}'`);if($.required&&$.defaultValue!==void 0&&$.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${$.name()}'`);return this.registeredArguments.push($),this}helpCommand($,w){if(typeof $==="boolean")return this._addImplicitHelpCommand=$,this;$=$??"help [command]";let[,E,X]=$.match(/([^ ]+) *(.*)/),G=w??"display help for command",J=this.createCommand(E);if(J.helpOption(!1),X)J.arguments(X);if(G)J.description(G);return this._addImplicitHelpCommand=!0,this._helpCommand=J,this}addHelpCommand($,w){if(typeof $!=="object")return this.helpCommand($,w),this;return this._addImplicitHelpCommand=!0,this._helpCommand=$,this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook($,w){let E=["preSubcommand","preAction","postAction"];if(!E.includes($))throw Error(`Unexpected value for event passed to hook : '${$}'.
|
|
18
|
+
Expecting one of '${E.join("', '")}'`);if(this._lifeCycleHooks[$])this._lifeCycleHooks[$].push(w);else this._lifeCycleHooks[$]=[w];return this}exitOverride($){if($)this._exitCallback=$;else this._exitCallback=(w)=>{if(w.code!=="commander.executeSubCommandAsync")throw w};return this}_exit($,w,E){if(this._exitCallback)this._exitCallback(new vD($,w,E));Q0.exit($)}action($){let w=(E)=>{let X=this.registeredArguments.length,G=E.slice(0,X);if(this._storeOptionsAsProperties)G[X]=this;else G[X]=this.opts();return G.push(this),$.apply(this,G)};return this._actionHandler=w,this}createOption($,w){return new JU($,w)}_callParseArg($,w,E,X){try{return $.parseArg(w,E)}catch(G){if(G.code==="commander.invalidArgument"){let J=`${X} ${G.message}`;this.error(J,{exitCode:G.exitCode,code:G.code})}throw G}}_registerOption($){let w=$.short&&this._findOption($.short)||$.long&&this._findOption($.long);if(w){let E=$.long&&this._findOption($.long)?$.long:$.short;throw Error(`Cannot add option '${$.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${E}'
|
|
19
|
+
- already used by option '${w.flags}'`)}this.options.push($)}_registerCommand($){let w=(X)=>{return[X.name()].concat(X.aliases())},E=w($).find((X)=>this._findCommand(X));if(E){let X=w(this._findCommand(E)).join("|"),G=w($).join("|");throw Error(`cannot add command '${G}' as already have command '${X}'`)}this.commands.push($)}addOption($){this._registerOption($);let w=$.name(),E=$.attributeName();if($.negate){let G=$.long.replace(/^--no-/,"--");if(!this._findOption(G))this.setOptionValueWithSource(E,$.defaultValue===void 0?!0:$.defaultValue,"default")}else if($.defaultValue!==void 0)this.setOptionValueWithSource(E,$.defaultValue,"default");let X=(G,J,A)=>{if(G==null&&$.presetArg!==void 0)G=$.presetArg;let D=this.getOptionValue(E);if(G!==null&&$.parseArg)G=this._callParseArg($,G,D,J);else if(G!==null&&$.variadic)G=$._concatValue(G,D);if(G==null)if($.negate)G=!1;else if($.isBoolean()||$.optional)G=!0;else G="";this.setOptionValueWithSource(E,G,A)};if(this.on("option:"+w,(G)=>{let J=`error: option '${$.flags}' argument '${G}' is invalid.`;X(G,J,"cli")}),$.envVar)this.on("optionEnv:"+w,(G)=>{let J=`error: option '${$.flags}' value '${G}' from env '${$.envVar}' is invalid.`;X(G,J,"env")});return this}_optionEx($,w,E,X,G){if(typeof w==="object"&&w instanceof JU)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let J=this.createOption(w,E);if(J.makeOptionMandatory(!!$.mandatory),typeof X==="function")J.default(G).argParser(X);else if(X instanceof RegExp){let A=X;X=(D,N)=>{let W=A.exec(D);return W?W[0]:N},J.default(G).argParser(X)}else J.default(X);return this.addOption(J)}option($,w,E,X){return this._optionEx({},$,w,E,X)}requiredOption($,w,E,X){return this._optionEx({mandatory:!0},$,w,E,X)}combineFlagAndOptionalValue($=!0){return this._combineFlagAndOptionalValue=!!$,this}allowUnknownOption($=!0){return this._allowUnknownOption=!!$,this}allowExcessArguments($=!0){return this._allowExcessArguments=!!$,this}enablePositionalOptions($=!0){return this._enablePositionalOptions=!!$,this}passThroughOptions($=!0){return this._passThroughOptions=!!$,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties($=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!$,this}getOptionValue($){if(this._storeOptionsAsProperties)return this[$];return this._optionValues[$]}setOptionValue($,w){return this.setOptionValueWithSource($,w,void 0)}setOptionValueWithSource($,w,E){if(this._storeOptionsAsProperties)this[$]=w;else this._optionValues[$]=w;return this._optionValueSources[$]=E,this}getOptionValueSource($){return this._optionValueSources[$]}getOptionValueSourceWithGlobals($){let w;return this._getCommandAndAncestors().forEach((E)=>{if(E.getOptionValueSource($)!==void 0)w=E.getOptionValueSource($)}),w}_prepareUserArgs($,w){if($!==void 0&&!Array.isArray($))throw Error("first parameter to parse must be array or undefined");if(w=w||{},$===void 0&&w.from===void 0){if(Q0.versions?.electron)w.from="electron";let X=Q0.execArgv??[];if(X.includes("-e")||X.includes("--eval")||X.includes("-p")||X.includes("--print"))w.from="eval"}if($===void 0)$=Q0.argv;this.rawArgs=$.slice();let E;switch(w.from){case void 0:case"node":this._scriptPath=$[1],E=$.slice(2);break;case"electron":if(Q0.defaultApp)this._scriptPath=$[1],E=$.slice(2);else E=$.slice(1);break;case"user":E=$.slice(0);break;case"eval":E=$.slice(1);break;default:throw Error(`unexpected parse option { from: '${w.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",E}parse($,w){this._prepareForParse();let E=this._prepareUserArgs($,w);return this._parseCommand([],E),this}async parseAsync($,w){this._prepareForParse();let E=this._prepareUserArgs($,w);return await this._parseCommand([],E),this}_prepareForParse(){if(this._savedState===null)this.saveStateBeforeParse();else this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
20
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable($,w,E){if(MJ.existsSync($))return;let X=w?`searched for local subcommand relative to directory '${w}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",G=`'${$}' does not exist
|
|
21
21
|
- if '${E}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
22
22
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
23
|
-
- ${X}`;throw Error(G)}_executeSubCommand($,w){w=w.slice();let E=!1,X=[".js",".ts",".tsx",".mjs",".cjs"];function G(W,O){let Y=Hw.resolve(W,O);if(
|
|
23
|
+
- ${X}`;throw Error(G)}_executeSubCommand($,w){w=w.slice();let E=!1,X=[".js",".ts",".tsx",".mjs",".cjs"];function G(W,O){let Y=Hw.resolve(W,O);if(MJ.existsSync(Y))return Y;if(X.includes(Hw.extname(O)))return;let H=X.find((L)=>MJ.existsSync(`${Y}${L}`));if(H)return`${Y}${H}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let J=$._executableFile||`${this._name}-${$._name}`,A=this._executableDir||"";if(this._scriptPath){let W;try{W=MJ.realpathSync(this._scriptPath)}catch{W=this._scriptPath}A=Hw.resolve(Hw.dirname(W),A)}if(A){let W=G(A,J);if(!W&&!$._executableFile&&this._scriptPath){let O=Hw.basename(this._scriptPath,Hw.extname(this._scriptPath));if(O!==this._name)W=G(A,`${O}-${$._name}`)}J=W||J}E=X.includes(Hw.extname(J));let D;if(Q0.platform!=="win32")if(E)w.unshift(J),w=DU(Q0.execArgv).concat(w),D=_D.spawn(Q0.argv[0],w,{stdio:"inherit"});else D=_D.spawn(J,w,{stdio:"inherit"});else this._checkForMissingExecutable(J,A,$._name),w.unshift(J),w=DU(Q0.execArgv).concat(w),D=_D.spawn(Q0.execPath,w,{stdio:"inherit"});if(!D.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((O)=>{Q0.on(O,()=>{if(D.killed===!1&&D.exitCode===null)D.kill(O)})});let N=this._exitCallback;D.on("close",(W)=>{if(W=W??1,!N)Q0.exit(W);else N(new vD(W,"commander.executeSubCommandAsync","(close)"))}),D.on("error",(W)=>{if(W.code==="ENOENT")this._checkForMissingExecutable(J,A,$._name);else if(W.code==="EACCES")throw Error(`'${J}' not executable`);if(!N)Q0.exit(1);else{let O=new vD(1,"commander.executeSubCommandAsync","(error)");O.nestedError=W,N(O)}}),this.runningCommand=D}_dispatchSubcommand($,w,E){let X=this._findCommand($);if(!X)this.help({error:!0});X._prepareForParse();let G;return G=this._chainOrCallSubCommandHook(G,X,"preSubcommand"),G=this._chainOrCall(G,()=>{if(X._executableHandler)this._executeSubCommand(X,w.concat(E));else return X._parseCommand(w,E)}),G}_dispatchHelpCommand($){if(!$)this.help();let w=this._findCommand($);if(w&&!w._executableHandler)w.help();return this._dispatchSubcommand($,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach(($,w)=>{if($.required&&this.args[w]==null)this.missingArgument($.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let $=(E,X,G)=>{let J=X;if(X!==null&&E.parseArg){let A=`error: command-argument value '${X}' is invalid for argument '${E.name()}'.`;J=this._callParseArg(E,X,G,A)}return J};this._checkNumberOfArguments();let w=[];this.registeredArguments.forEach((E,X)=>{let G=E.defaultValue;if(E.variadic){if(X<this.args.length){if(G=this.args.slice(X),E.parseArg)G=G.reduce((J,A)=>{return $(E,A,J)},E.defaultValue)}else if(G===void 0)G=[]}else if(X<this.args.length){if(G=this.args[X],E.parseArg)G=$(E,G,E.defaultValue)}w[X]=G}),this.processedArgs=w}_chainOrCall($,w){if($&&$.then&&typeof $.then==="function")return $.then(()=>w());return w()}_chainOrCallHooks($,w){let E=$,X=[];if(this._getCommandAndAncestors().reverse().filter((G)=>G._lifeCycleHooks[w]!==void 0).forEach((G)=>{G._lifeCycleHooks[w].forEach((J)=>{X.push({hookedCommand:G,callback:J})})}),w==="postAction")X.reverse();return X.forEach((G)=>{E=this._chainOrCall(E,()=>{return G.callback(G.hookedCommand,this)})}),E}_chainOrCallSubCommandHook($,w,E){let X=$;if(this._lifeCycleHooks[E]!==void 0)this._lifeCycleHooks[E].forEach((G)=>{X=this._chainOrCall(X,()=>{return G(this,w)})});return X}_parseCommand($,w){let E=this.parseOptions(w);if(this._parseOptionsEnv(),this._parseOptionsImplied(),$=$.concat(E.operands),w=E.unknown,this.args=$.concat(w),$&&this._findCommand($[0]))return this._dispatchSubcommand($[0],$.slice(1),w);if(this._getHelpCommand()&&$[0]===this._getHelpCommand().name())return this._dispatchHelpCommand($[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(w),this._dispatchSubcommand(this._defaultCommandName,$,w);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(E.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let X=()=>{if(E.unknown.length>0)this.unknownOption(E.unknown[0])},G=`command:${this.name()}`;if(this._actionHandler){X(),this._processArguments();let J;if(J=this._chainOrCallHooks(J,"preAction"),J=this._chainOrCall(J,()=>this._actionHandler(this.processedArgs)),this.parent)J=this._chainOrCall(J,()=>{this.parent.emit(G,$,w)});return J=this._chainOrCallHooks(J,"postAction"),J}if(this.parent&&this.parent.listenerCount(G))X(),this._processArguments(),this.parent.emit(G,$,w);else if($.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",$,w);if(this.listenerCount("command:*"))this.emit("command:*",$,w);else if(this.commands.length)this.unknownCommand();else X(),this._processArguments()}else if(this.commands.length)X(),this.help({error:!0});else X(),this._processArguments()}_findCommand($){if(!$)return;return this.commands.find((w)=>w._name===$||w._aliases.includes($))}_findOption($){return this.options.find((w)=>w.is($))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(($)=>{$.options.forEach((w)=>{if(w.mandatory&&$.getOptionValue(w.attributeName())===void 0)$.missingMandatoryOptionValue(w)})})}_checkForConflictingLocalOptions(){let $=this.options.filter((E)=>{let X=E.attributeName();if(this.getOptionValue(X)===void 0)return!1;return this.getOptionValueSource(X)!=="default"});$.filter((E)=>E.conflictsWith.length>0).forEach((E)=>{let X=$.find((G)=>E.conflictsWith.includes(G.attributeName()));if(X)this._conflictingOption(E,X)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(($)=>{$._checkForConflictingLocalOptions()})}parseOptions($){let w=[],E=[],X=w,G=$.slice();function J(D){return D.length>1&&D[0]==="-"}let A=null;while(G.length){let D=G.shift();if(D==="--"){if(X===E)X.push(D);X.push(...G);break}if(A&&!J(D)){this.emit(`option:${A.name()}`,D);continue}if(A=null,J(D)){let N=this._findOption(D);if(N){if(N.required){let W=G.shift();if(W===void 0)this.optionMissingArgument(N);this.emit(`option:${N.name()}`,W)}else if(N.optional){let W=null;if(G.length>0&&!J(G[0]))W=G.shift();this.emit(`option:${N.name()}`,W)}else this.emit(`option:${N.name()}`);A=N.variadic?N:null;continue}}if(D.length>2&&D[0]==="-"&&D[1]!=="-"){let N=this._findOption(`-${D[1]}`);if(N){if(N.required||N.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${N.name()}`,D.slice(2));else this.emit(`option:${N.name()}`),G.unshift(`-${D.slice(2)}`);continue}}if(/^--[^=]+=/.test(D)){let N=D.indexOf("="),W=this._findOption(D.slice(0,N));if(W&&(W.required||W.optional)){this.emit(`option:${W.name()}`,D.slice(N+1));continue}}if(J(D))X=E;if((this._enablePositionalOptions||this._passThroughOptions)&&w.length===0&&E.length===0){if(this._findCommand(D)){if(w.push(D),G.length>0)E.push(...G);break}else if(this._getHelpCommand()&&D===this._getHelpCommand().name()){if(w.push(D),G.length>0)w.push(...G);break}else if(this._defaultCommandName){if(E.push(D),G.length>0)E.push(...G);break}}if(this._passThroughOptions){if(X.push(D),G.length>0)X.push(...G);break}X.push(D)}return{operands:w,unknown:E}}opts(){if(this._storeOptionsAsProperties){let $={},w=this.options.length;for(let E=0;E<w;E++){let X=this.options[E].attributeName();$[X]=X===this._versionOptionName?this._version:this[X]}return $}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce(($,w)=>Object.assign($,w.opts()),{})}error($,w){if(this._outputConfiguration.outputError(`${$}
|
|
24
24
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
25
25
|
`);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(`
|
|
26
|
-
`),this.outputHelp({error:!0});let E=w||{},X=E.exitCode||1,G=E.code||"commander.error";this._exit(X,G,$)}_parseOptionsEnv(){this.options.forEach(($)=>{if($.envVar&&$.envVar in Q0.env){let w=$.attributeName();if(this.getOptionValue(w)===void 0||["default","config","env"].includes(this.getOptionValueSource(w)))if($.required||$.optional)this.emit(`optionEnv:${$.name()}`,Q0.env[$.envVar]);else this.emit(`optionEnv:${$.name()}`)}})}_parseOptionsImplied(){let $=new
|
|
27
|
-
`),this._exit(0,"commander.version",$)}),this}description($,w){if($===void 0&&w===void 0)return this._description;if(this._description=$,w)this._argsDescription=w;return this}summary($){if($===void 0)return this._summary;return this._summary=$,this}alias($){if($===void 0)return this._aliases[0];let w=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)w=this.commands[this.commands.length-1];if($===w._name)throw Error("Command alias can't be the same as its name");let E=this.parent?._findCommand($);if(E){let X=[E.name()].concat(E.aliases()).join("|");throw Error(`cannot add alias '${$}' to command '${this.name()}' as already have command '${X}'`)}return w._aliases.push($),this}aliases($){if($===void 0)return this._aliases;return $.forEach((w)=>this.alias(w)),this}usage($){if($===void 0){if(this._usage)return this._usage;let w=this.registeredArguments.map((E)=>{return
|
|
26
|
+
`),this.outputHelp({error:!0});let E=w||{},X=E.exitCode||1,G=E.code||"commander.error";this._exit(X,G,$)}_parseOptionsEnv(){this.options.forEach(($)=>{if($.envVar&&$.envVar in Q0.env){let w=$.attributeName();if(this.getOptionValue(w)===void 0||["default","config","env"].includes(this.getOptionValueSource(w)))if($.required||$.optional)this.emit(`optionEnv:${$.name()}`,Q0.env[$.envVar]);else this.emit(`optionEnv:${$.name()}`)}})}_parseOptionsImplied(){let $=new bq(this.options),w=(E)=>{return this.getOptionValue(E)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(E))};this.options.filter((E)=>E.implied!==void 0&&w(E.attributeName())&&$.valueFromOption(this.getOptionValue(E.attributeName()),E)).forEach((E)=>{Object.keys(E.implied).filter((X)=>!w(X)).forEach((X)=>{this.setOptionValueWithSource(X,E.implied[X],"implied")})})}missingArgument($){let w=`error: missing required argument '${$}'`;this.error(w,{code:"commander.missingArgument"})}optionMissingArgument($){let w=`error: option '${$.flags}' argument missing`;this.error(w,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue($){let w=`error: required option '${$.flags}' not specified`;this.error(w,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption($,w){let E=(J)=>{let A=J.attributeName(),D=this.getOptionValue(A),N=this.options.find((O)=>O.negate&&A===O.attributeName()),W=this.options.find((O)=>!O.negate&&A===O.attributeName());if(N&&(N.presetArg===void 0&&D===!1||N.presetArg!==void 0&&D===N.presetArg))return N;return W||J},X=(J)=>{let A=E(J),D=A.attributeName();if(this.getOptionValueSource(D)==="env")return`environment variable '${A.envVar}'`;return`option '${A.flags}'`},G=`error: ${X($)} cannot be used with ${X(w)}`;this.error(G,{code:"commander.conflictingOption"})}unknownOption($){if(this._allowUnknownOption)return;let w="";if($.startsWith("--")&&this._showSuggestionAfterError){let X=[],G=this;do{let J=G.createHelp().visibleOptions(G).filter((A)=>A.long).map((A)=>A.long);X=X.concat(J),G=G.parent}while(G&&!G._enablePositionalOptions);w=AU($,X)}let E=`error: unknown option '${$}'${w}`;this.error(E,{code:"commander.unknownOption"})}_excessArguments($){if(this._allowExcessArguments)return;let w=this.registeredArguments.length,E=w===1?"":"s",G=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${w} argument${E} but got ${$.length}.`;this.error(G,{code:"commander.excessArguments"})}unknownCommand(){let $=this.args[0],w="";if(this._showSuggestionAfterError){let X=[];this.createHelp().visibleCommands(this).forEach((G)=>{if(X.push(G.name()),G.alias())X.push(G.alias())}),w=AU($,X)}let E=`error: unknown command '${$}'${w}`;this.error(E,{code:"commander.unknownCommand"})}version($,w,E){if($===void 0)return this._version;this._version=$,w=w||"-V, --version",E=E||"output the version number";let X=this.createOption(w,E);return this._versionOptionName=X.attributeName(),this._registerOption(X),this.on("option:"+X.name(),()=>{this._outputConfiguration.writeOut(`${$}
|
|
27
|
+
`),this._exit(0,"commander.version",$)}),this}description($,w){if($===void 0&&w===void 0)return this._description;if(this._description=$,w)this._argsDescription=w;return this}summary($){if($===void 0)return this._summary;return this._summary=$,this}alias($){if($===void 0)return this._aliases[0];let w=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)w=this.commands[this.commands.length-1];if($===w._name)throw Error("Command alias can't be the same as its name");let E=this.parent?._findCommand($);if(E){let X=[E.name()].concat(E.aliases()).join("|");throw Error(`cannot add alias '${$}' to command '${this.name()}' as already have command '${X}'`)}return w._aliases.push($),this}aliases($){if($===void 0)return this._aliases;return $.forEach((w)=>this.alias(w)),this}usage($){if($===void 0){if(this._usage)return this._usage;let w=this.registeredArguments.map((E)=>{return qq(E)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?w:[]).join(" ")}return this._usage=$,this}name($){if($===void 0)return this._name;return this._name=$,this}nameFromFilename($){return this._name=Hw.basename($,Hw.extname($)),this}executableDir($){if($===void 0)return this._executableDir;return this._executableDir=$,this}helpInformation($){let w=this.createHelp(),E=this._getOutputContext($);w.prepareContext({error:E.error,helpWidth:E.helpWidth,outputHasColors:E.hasColors});let X=w.formatHelp(this,w);if(E.hasColors)return X;return this._outputConfiguration.stripColor(X)}_getOutputContext($){$=$||{};let w=!!$.error,E,X,G;if(w)E=(A)=>this._outputConfiguration.writeErr(A),X=this._outputConfiguration.getErrHasColors(),G=this._outputConfiguration.getErrHelpWidth();else E=(A)=>this._outputConfiguration.writeOut(A),X=this._outputConfiguration.getOutHasColors(),G=this._outputConfiguration.getOutHelpWidth();return{error:w,write:(A)=>{if(!X)A=this._outputConfiguration.stripColor(A);return E(A)},hasColors:X,helpWidth:G}}outputHelp($){let w;if(typeof $==="function")w=$,$=void 0;let E=this._getOutputContext($),X={error:E.error,write:E.write,command:this};this._getCommandAndAncestors().reverse().forEach((J)=>J.emit("beforeAllHelp",X)),this.emit("beforeHelp",X);let G=this.helpInformation({error:E.error});if(w){if(G=w(G),typeof G!=="string"&&!Buffer.isBuffer(G))throw Error("outputHelp callback must return a string or a Buffer")}if(E.write(G),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",X),this._getCommandAndAncestors().forEach((J)=>J.emit("afterAllHelp",X))}helpOption($,w){if(typeof $==="boolean"){if($)this._helpOption=this._helpOption??void 0;else this._helpOption=null;return this}return $=$??"-h, --help",w=w??"display help for command",this._helpOption=this.createOption($,w),this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption($){return this._helpOption=$,this}help($){this.outputHelp($);let w=Number(Q0.exitCode??0);if(w===0&&$&&typeof $!=="function"&&$.error)w=1;this._exit(w,"commander.help","(outputHelp)")}addHelpText($,w){let E=["beforeAll","before","after","afterAll"];if(!E.includes($))throw Error(`Unexpected value for position to addHelpText.
|
|
28
28
|
Expecting one of '${E.join("', '")}'`);let X=`${$}Help`;return this.on(X,(G)=>{let J;if(typeof w==="function")J=w({error:G.error,command:G.command});else J=w;if(J)G.write(`${J}
|
|
29
|
-
`)}),this}_outputHelpIfRequested($){let w=this._getHelpOption();if(w&&$.find((X)=>w.is(X)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function GU($){return $.map((w)=>{if(!w.startsWith("--inspect"))return w;let E,X="127.0.0.1",G="9229",J;if((J=w.match(/^(--inspect(-brk)?)$/))!==null)E=J[1];else if((J=w.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(E=J[1],/^\d+$/.test(J[3]))G=J[3];else X=J[3];else if((J=w.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)E=J[1],X=J[3],G=J[4];if(E&&G!=="0")return`${E}=${X}:${parseInt(G)+1}`;return w})}function CD(){if(Q0.env.NO_COLOR||Q0.env.FORCE_COLOR==="0"||Q0.env.FORCE_COLOR==="false")return!1;if(Q0.env.FORCE_COLOR||Q0.env.CLICOLOR_FORCE!==void 0)return!0;return}Kq.Command=_D;Kq.useColor=CD});var WU=Z((kq)=>{var{Argument:AU}=LJ(),{Command:vD}=JU(),{CommanderError:qq,InvalidArgumentError:DU}=YG(),{Help:Sq}=SD(),{Option:NU}=kD();kq.program=new vD;kq.createCommand=($)=>new vD($);kq.createOption=($,w)=>new NU($,w);kq.createArgument=($,w)=>new AU($,w);kq.Command=vD;kq.Option=NU;kq.Argument=AU;kq.Help=Sq;kq.CommanderError=qq;kq.InvalidArgumentError=DU;kq.InvalidOptionArgumentError=DU});function jJ($,w,E,X){if(UU[$]<UU[nq])return;let G=new Date().toISOString(),A=`${cq[$]}[${$.toUpperCase()}]\x1B[0m ${G} [${w}]`;if(X!==void 0)console.error(`${A} ${E}`,X);else console.error(`${A} ${E}`)}function Z0($){return{debug:(w,E)=>jJ("debug",$,w,E),info:(w,E)=>jJ("info",$,w,E),warn:(w,E)=>jJ("warn",$,w,E),error:(w,E)=>jJ("error",$,w,E)}}var UU,cq,nq;var p$=R(()=>{UU={debug:0,info:1,warn:2,error:3},cq={debug:"\x1B[36m",info:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m"},nq=process.env.ORC_LOG_LEVEL??"info"});import{randomBytes as mq}from"crypto";function oq($,w){let E="";for(let X=w-1;X>=0;X--){let G=$%fD;E=xD[G]+E,$=Math.floor($/fD)}return E}function tq($){let w=mq($),E="";for(let X=0;X<$;X++)E+=xD[(w[X]??0)%fD];return E}function i(){return oq(Date.now(),rq)+tq(pq)}var xD="0123456789ABCDEFGHJKMNPQRSTVWXYZ",fD,rq=10,pq=16;var X1=R(()=>{fD=xD.length});function b($,w){if(!$||typeof $!=="object")return!1;if($ instanceof w)return!0;if(!Object.prototype.hasOwnProperty.call(w,K))throw Error(`Class "${w.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 E=Object.getPrototypeOf($).constructor;if(E)while(E){if(K in E&&E[K]===w[K])return!0;E=Object.getPrototypeOf(E)}return!1}var K;var E0=R(()=>{K=Symbol.for("drizzle:entityKind")});var YU,yD,gD;var MJ=R(()=>{E0();YU=class YU{static[K]="ConsoleLogWriter";write($){console.log($)}};yD=class yD{static[K]="DefaultLogger";writer;constructor($){this.writer=$?.writer??new YU}logQuery($,w){let E=w.map((G)=>{try{return JSON.stringify(G)}catch{return String(G)}}),X=E.length?` -- params: [${E.join(", ")}]`:"";this.writer.write(`Query: ${$}${X}`)}};gD=class gD{static[K]="NoopLogger";logQuery(){}}});var G1;var HG=R(()=>{G1=Symbol.for("drizzle:Name")});function xw($){return $[G1]}function UE($){return`${$[RJ]??"public"}.${$[G1]}`}var RJ,zJ,HU,uD,hD,LG,LU,iq,y;var _$=R(()=>{E0();HG();RJ=Symbol.for("drizzle:Schema"),zJ=Symbol.for("drizzle:Columns"),HU=Symbol.for("drizzle:ExtraConfigColumns"),uD=Symbol.for("drizzle:OriginalName"),hD=Symbol.for("drizzle:BaseName"),LG=Symbol.for("drizzle:IsAlias"),LU=Symbol.for("drizzle:ExtraConfigBuilder"),iq=Symbol.for("drizzle:IsDrizzleTable");y=class y{static[K]="Table";static Symbol={Name:G1,Schema:RJ,OriginalName:uD,Columns:zJ,ExtraConfigColumns:HU,BaseName:hD,IsAlias:LG,ExtraConfigBuilder:LU};[G1];[uD];[RJ];[zJ];[HU];[hD];[LG]=!1;[iq]=!0;[LU]=void 0;constructor($,w,E){this[G1]=this[uD]=$,this[RJ]=w,this[hD]=E}}});var V0;var b1=R(()=>{E0();V0=class V0{constructor($,w){this.table=$,this.config=w,this.name=w.name,this.keyAsName=w.keyAsName,this.notNull=w.notNull,this.default=w.default,this.defaultFn=w.defaultFn,this.onUpdateFn=w.onUpdateFn,this.hasDefault=w.hasDefault,this.primary=w.primaryKey,this.isUnique=w.isUnique,this.uniqueName=w.uniqueName,this.uniqueType=w.uniqueType,this.dataType=w.dataType,this.columnType=w.columnType,this.generated=w.generated,this.generatedIdentity=w.generatedIdentity}static[K]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue($){return $}mapToDriverValue($){return $}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}});var cD;var nD=R(()=>{E0();cD=class cD{static[K]="ColumnBuilder";config;constructor($,w,E){this.config={name:$,keyAsName:$==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:w,columnType:E,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default($){return this.config.default=$,this.config.hasDefault=!0,this}$defaultFn($){return this.config.defaultFn=$,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn($){return this.config.onUpdateFn=$,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName($){if(this.config.name!=="")return;this.config.name=$}}});function FU($,...w){return $(...w)}var jU=()=>{};function MU($,w){return`${$[G1]}_${w.join("_")}_unique`}var RU=R(()=>{HG()});var TJ,dq;var zU=R(()=>{b1();E0();RU();TJ=class TJ extends V0{constructor($,w){if(!w.uniqueName)w.uniqueName=MU($,[w.name]);super($,w);this.table=$}static[K]="PgColumn"};dq=class dq extends TJ{static[K]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op($){return this.indexConfig.opClass=$,this}}});function BU($){return!!$&&typeof $==="function"&&TU in $&&$[TU]===!0}var TU,lq;var QU=R(()=>{E0();zU();TU=Symbol.for("drizzle:isPgEnum");lq=class lq extends TJ{static[K]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor($,w){super($,w);this.enum=w.enum}getSQLType(){return this.enum.enumName}}});var Y$,FG;var d1=R(()=>{E0();Y$=class Y${static[K]="Subquery";constructor($,w,E,X=!1){this._={brand:"Subquery",sql:$,selectedFields:w,alias:E,isWith:X}}};FG=class FG extends Y${static[K]="WithSubquery"}});var IU="0.41.0";var KU=()=>{};var mD,rD,VU;var PU=R(()=>{jU();KU();VU={startActiveSpan($,w){if(!mD)return w();if(!rD)rD=mD.trace.getTracer("drizzle-orm",IU);return FU((E,X)=>X.startActiveSpan($,(G)=>{try{return w(G)}catch(J){throw G.setStatus({code:E.SpanStatusCode.ERROR,message:J instanceof Error?J.message:"Unknown error"}),J}finally{G.end()}}),mD,rD)}}});var s0;var Lw=R(()=>{s0=Symbol.for("drizzle:ViewBaseConfig")});function pD($){return $!==null&&$!==void 0&&typeof $.getSQL==="function"}function sq($){let w={sql:"",params:[]};for(let E of $)if(w.sql+=E.sql,w.params.push(...E.params),E.typings?.length){if(!w.typings)w.typings=[];w.typings.push(...E.typings)}return w}function qU($){return typeof $==="object"&&$!==null&&"mapToDriverValue"in $&&typeof $.mapToDriverValue==="function"}function T($,...w){let E=[];if(w.length>0||$.length>0&&$[0]!=="")E.push(new W$($[0]));for(let[X,G]of w.entries())E.push(G,new W$($[X+1]));return new h(E)}function jG($,w){return $.map((E)=>{if(b(E,yw)){if(!(E.name in w))throw Error(`No value for placeholder "${E.name}" was provided`);return w[E.name]}if(b(E,J1)&&b(E.value,yw)){if(!(E.value.name in w))throw Error(`No value for placeholder "${E.value.name}" was provided`);return E.encoder.mapToDriverValue(w[E.value.name])}return E})}var W$,h,BJ,SU,kU,vt,J1,yw,aq,U1;var q$=R(()=>{E0();QU();d1();PU();Lw();b1();_$();W$=class W${static[K]="StringChunk";value;constructor($){this.value=Array.isArray($)?$:[$]}getSQL(){return new h([this])}};h=class h{constructor($){this.queryChunks=$}static[K]="SQL";decoder=SU;shouldInlineParams=!1;append($){return this.queryChunks.push(...$.queryChunks),this}toQuery($){return VU.startActiveSpan("drizzle.buildSQL",(w)=>{let E=this.buildQueryFromSourceParams(this.queryChunks,$);return w?.setAttributes({"drizzle.query.text":E.sql,"drizzle.query.params":JSON.stringify(E.params)}),E})}buildQueryFromSourceParams($,w){let E=Object.assign({},w,{inlineParams:w.inlineParams||this.shouldInlineParams,paramStartIndex:w.paramStartIndex||{value:0}}),{casing:X,escapeName:G,escapeParam:J,prepareTyping:A,inlineParams:D,paramStartIndex:N}=E;return sq($.map((W)=>{if(b(W,W$))return{sql:W.value.join(""),params:[]};if(b(W,BJ))return{sql:G(W.value),params:[]};if(W===void 0)return{sql:"",params:[]};if(Array.isArray(W)){let O=[new W$("(")];for(let[Y,H]of W.entries())if(O.push(H),Y<W.length-1)O.push(new W$(", "));return O.push(new W$(")")),this.buildQueryFromSourceParams(O,E)}if(b(W,h))return this.buildQueryFromSourceParams(W.queryChunks,{...E,inlineParams:D||W.shouldInlineParams});if(b(W,y)){let O=W[y.Symbol.Schema],Y=W[y.Symbol.Name];return{sql:O===void 0||W[LG]?G(Y):G(O)+"."+G(Y),params:[]}}if(b(W,V0)){let O=X.getColumnCasing(W);if(w.invokeSource==="indexes")return{sql:G(O),params:[]};let Y=W.table[y.Symbol.Schema];return{sql:W.table[LG]||Y===void 0?G(W.table[y.Symbol.Name])+"."+G(O):G(Y)+"."+G(W.table[y.Symbol.Name])+"."+G(O),params:[]}}if(b(W,U1)){let O=W[s0].schema,Y=W[s0].name;return{sql:O===void 0||W[s0].isAlias?G(Y):G(O)+"."+G(Y),params:[]}}if(b(W,J1)){if(b(W.value,yw))return{sql:J(N.value++,W),params:[W],typings:["none"]};let O=W.value===null?null:W.encoder.mapToDriverValue(W.value);if(b(O,h))return this.buildQueryFromSourceParams([O],E);if(D)return{sql:this.mapInlineParam(O,E),params:[]};let Y=["none"];if(A)Y=[A(W.encoder)];return{sql:J(N.value++,O),params:[O],typings:Y}}if(b(W,yw))return{sql:J(N.value++,W),params:[W],typings:["none"]};if(b(W,h.Aliased)&&W.fieldAlias!==void 0)return{sql:G(W.fieldAlias),params:[]};if(b(W,Y$)){if(W._.isWith)return{sql:G(W._.alias),params:[]};return this.buildQueryFromSourceParams([new W$("("),W._.sql,new W$(") "),new BJ(W._.alias)],E)}if(BU(W)){if(W.schema)return{sql:G(W.schema)+"."+G(W.enumName),params:[]};return{sql:G(W.enumName),params:[]}}if(pD(W)){if(W.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([W.getSQL()],E);return this.buildQueryFromSourceParams([new W$("("),W.getSQL(),new W$(")")],E)}if(D)return{sql:this.mapInlineParam(W,E),params:[]};return{sql:J(N.value++,W),params:[W],typings:["none"]}}))}mapInlineParam($,{escapeString:w}){if($===null)return"null";if(typeof $==="number"||typeof $==="boolean")return $.toString();if(typeof $==="string")return w($);if(typeof $==="object"){let E=$.toString();if(E==="[object Object]")return w(JSON.stringify($));return w(E)}throw Error("Unexpected param value: "+$)}getSQL(){return this}as($){if($===void 0)return this;return new h.Aliased(this,$)}mapWith($){return this.decoder=typeof $==="function"?{mapFromDriverValue:$}:$,this}inlineParams(){return this.shouldInlineParams=!0,this}if($){return $?this:void 0}};BJ=class BJ{constructor($){this.value=$}static[K]="Name";brand;getSQL(){return new h([this])}};SU={mapFromDriverValue:($)=>$},kU={mapToDriverValue:($)=>$},vt={...SU,...kU};J1=class J1{constructor($,w=kU){this.value=$,this.encoder=w}static[K]="Param";brand;getSQL(){return new h([this])}};(($)=>{function w(){return new h([])}$.empty=w;function E(N){return new h(N)}$.fromList=E;function X(N){return new h([new W$(N)])}$.raw=X;function G(N,W){let O=[];for(let[Y,H]of N.entries()){if(Y>0&&W!==void 0)O.push(W);O.push(H)}return new h(O)}$.join=G;function J(N){return new BJ(N)}$.identifier=J;function A(N){return new yw(N)}$.placeholder=A;function D(N,W){return new J1(N,W)}$.param=D})(T||(T={}));(($)=>{class w{constructor(E,X){this.sql=E,this.fieldAlias=X}static[K]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new w(this.sql,this.fieldAlias)}}$.Aliased=w})(h||(h={}));yw=class yw{constructor($){this.name=$}static[K]="Placeholder";getSQL(){return new h([this])}};aq=Symbol.for("drizzle:IsDrizzleView");U1=class U1{static[K]="View";[s0];[aq]=!0;constructor({name:$,schema:w,selectedFields:E,query:X}){this[s0]={name:$,originalName:$,schema:w,selectedFields:E,query:X,isExisting:!X,isAlias:!1}}getSQL(){return new h([this])}};V0.prototype.getSQL=function(){return new h([this])};y.prototype.getSQL=function(){return new h([this])};Y$.prototype.getSQL=function(){return new h([this])}});function oD($,w,E){let X={},G=$.reduce((J,{path:A,field:D},N)=>{let W;if(b(D,V0))W=D;else if(b(D,h))W=D.decoder;else W=D.sql.decoder;let O=J;for(let[Y,H]of A.entries())if(Y<A.length-1){if(!(H in O))O[H]={};O=O[H]}else{let L=w[N],F=O[H]=L===null?null:W.mapFromDriverValue(L);if(E&&b(D,V0)&&A.length===2){let j=A[0];if(!(j in X))X[j]=F===null?xw(D.table):!1;else if(typeof X[j]==="string"&&X[j]!==xw(D.table))X[j]=!1}}return J},{});if(E&&Object.keys(X).length>0){for(let[J,A]of Object.entries(X))if(typeof A==="string"&&!E[A])G[J]=null}return G}function Y1($,w){return Object.entries($).reduce((E,[X,G])=>{if(typeof X!=="string")return E;let J=w?[...w,X]:[X];if(b(G,V0)||b(G,h)||b(G,h.Aliased))E.push({path:J,field:G});else if(b(G,y))E.push(...Y1(G[y.Symbol.Columns],J));else E.push(...Y1(G,J));return E},[])}function MG($,w){let E=Object.keys($),X=Object.keys(w);if(E.length!==X.length)return!1;for(let[G,J]of E.entries())if(J!==X[G])return!1;return!0}function QJ($,w){let E=Object.entries(w).filter(([,X])=>X!==void 0).map(([X,G])=>{if(b(G,h)||b(G,V0))return[X,G];else return[X,new J1(G,$[y.Symbol.Columns][X])]});if(E.length===0)throw Error("No values to set");return Object.fromEntries(E)}function bU($,w){for(let E of w)for(let X of Object.getOwnPropertyNames(E.prototype)){if(X==="constructor")continue;Object.defineProperty($.prototype,X,Object.getOwnPropertyDescriptor(E.prototype,X)||Object.create(null))}}function ZU($){return $[y.Symbol.Columns]}function RG($){return b($,Y$)?$._.alias:b($,U1)?$[s0].name:b($,h)?void 0:$[y.Symbol.IsAlias]?$[y.Symbol.Name]:$[y.Symbol.BaseName]}function l1($,w){return{name:typeof $==="string"&&$.length>0?$:"",config:typeof $==="object"?$:w}}function CU($){if(typeof $!=="object"||$===null)return!1;if($.constructor.name!=="Object")return!1;if("logger"in $){let w=typeof $.logger;if(w!=="boolean"&&(w!=="object"||typeof $.logger.logQuery!=="function")&&w!=="undefined")return!1;return!0}if("schema"in $){let w=typeof $.schema;if(w!=="object"&&w!=="undefined")return!1;return!0}if("casing"in $){let w=typeof $.casing;if(w!=="string"&&w!=="undefined")return!1;return!0}if("mode"in $){if($.mode!=="default"||$.mode!=="planetscale"||$.mode!==void 0)return!1;return!0}if("connection"in $){let w=typeof $.connection;if(w!=="string"&&w!=="object"&&w!=="undefined")return!1;return!0}if("client"in $){let w=typeof $.client;if(w!=="object"&&w!=="function"&&w!=="undefined")return!1;return!0}if(Object.keys($).length===0)return!0;return!1}var o$=R(()=>{b1();E0();q$();d1();_$();Lw()});var _U,vU,tD;var fU=R(()=>{E0();_$();_U=Symbol.for("drizzle:PgInlineForeignKeys"),vU=Symbol.for("drizzle:EnableRLS");tD=class tD extends y{static[K]="PgTable";static Symbol=Object.assign({},y.Symbol,{InlineForeignKeys:_U,EnableRLS:vU});[_U]=[];[vU]=!1;[y.Symbol.ExtraConfigBuilder]=void 0;[y.Symbol.ExtraConfigColumns]={}}});var iD,xU;var yU=R(()=>{E0();fU();iD=class iD{static[K]="PgPrimaryKeyBuilder";columns;name;constructor($,w){this.columns=$,this.name=w}build($){return new xU($,this.columns,this.name)}};xU=class xU{constructor($,w,E){this.table=$,this.columns=w,this.name=E}static[K]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[tD.Symbol.Name]}_${this.columns.map(($)=>$.name).join("_")}_pk`}}});function t$($,w){if(qU(w)&&!pD($)&&!b($,J1)&&!b($,yw)&&!b($,V0)&&!b($,y)&&!b($,U1))return new J1($,w);return $}function S0(...$){let w=$.filter((E)=>E!==void 0);if(w.length===0)return;if(w.length===1)return new h(w);return new h([new W$("("),T.join(w,new W$(" and ")),new W$(")")])}function IJ(...$){let w=$.filter((E)=>E!==void 0);if(w.length===0)return;if(w.length===1)return new h(w);return new h([new W$("("),T.join(w,new W$(" or ")),new W$(")")])}function uU($){return T`not ${$}`}function KJ($,w){if(Array.isArray(w)){if(w.length===0)return T`false`;return T`${$} in ${w.map((E)=>t$(E,$))}`}return T`${$} in ${t$(w,$)}`}function rU($,w){if(Array.isArray(w)){if(w.length===0)return T`true`;return T`${$} not in ${w.map((E)=>t$(E,$))}`}return T`${$} not in ${t$(w,$)}`}function pU($){return T`${$} is null`}function oU($){return T`${$} is not null`}function tU($){return T`exists ${$}`}function iU($){return T`not exists ${$}`}function dU($,w,E){return T`${$} between ${t$(w,$)} and ${t$(E,$)}`}function lU($,w,E){return T`${$} not between ${t$(w,$)} and ${t$(E,$)}`}function sU($,w){return T`${$} like ${w}`}function aU($,w){return T`${$} not like ${w}`}function eU($,w){return T`${$} ilike ${w}`}function $7($,w){return T`${$} not ilike ${w}`}var V=($,w)=>{return T`${$} = ${t$(w,$)}`},gU=($,w)=>{return T`${$} <> ${t$(w,$)}`},hU=($,w)=>{return T`${$} > ${t$(w,$)}`},cU=($,w)=>{return T`${$} >= ${t$(w,$)}`},nU=($,w)=>{return T`${$} < ${t$(w,$)}`},mU=($,w)=>{return T`${$} <= ${t$(w,$)}`};var w7=R(()=>{b1();E0();_$();q$()});function VJ($){return T`${$} asc`}function x0($){return T`${$} desc`}var E7=R(()=>{q$()});var PJ=R(()=>{w7();E7()});function G7(){return{and:S0,between:dU,eq:V,exists:tU,gt:hU,gte:cU,ilike:eU,inArray:KJ,isNull:pU,isNotNull:oU,like:sU,lt:nU,lte:mU,ne:gU,not:uU,notBetween:lU,notExists:iU,notLike:aU,notIlike:$7,notInArray:rU,or:IJ,sql:T}}function J7(){return{sql:T,asc:VJ,desc:x0}}function A7($,w){if(Object.keys($).length===1&&"default"in $&&!b($.default,y))$=$.default;let E={},X={},G={};for(let[J,A]of Object.entries($))if(b(A,y)){let D=UE(A),N=X[D];E[D]=J,G[J]={tsName:J,dbName:A[y.Symbol.Name],schema:A[y.Symbol.Schema],columns:A[y.Symbol.Columns],relations:N?.relations??{},primaryKey:N?.primaryKey??[]};for(let O of Object.values(A[y.Symbol.Columns]))if(O.primary)G[J].primaryKey.push(O);let W=A[y.Symbol.ExtraConfigBuilder]?.(A[y.Symbol.ExtraConfigColumns]);if(W){for(let O of Object.values(W))if(b(O,iD))G[J].primaryKey.push(...O.columns)}}else if(b(A,X7)){let D=UE(A.table),N=E[D],W=A.config(w(A.table)),O;for(let[Y,H]of Object.entries(W))if(N){let L=G[N];if(L.relations[Y]=H,O)L.primaryKey.push(...O)}else{if(!(D in X))X[D]={relations:{},primaryKey:O};X[D].relations[Y]=H}}return{tables:G,tableNamesMap:E}}function eq($){return function(E,X){return new gw($,E,X,X?.fields.reduce((G,J)=>G&&J.notNull,!0)??!1)}}function $2($){return function(E,X){return new zG($,E,X)}}function D7($,w,E){if(b(E,gw)&&E.config)return{fields:E.config.fields,references:E.config.references};let X=w[UE(E.referencedTable)];if(!X)throw Error(`Table "${E.referencedTable[y.Symbol.Name]}" not found in schema`);let G=$[X];if(!G)throw Error(`Table "${X}" not found in schema`);let J=E.sourceTable,A=w[UE(J)];if(!A)throw Error(`Table "${J[y.Symbol.Name]}" not found in schema`);let D=[];for(let N of Object.values(G.relations))if(E.relationName&&E!==N&&N.relationName===E.relationName||!E.relationName&&N.referencedTable===E.sourceTable)D.push(N);if(D.length>1)throw E.relationName?Error(`There are multiple relations with name "${E.relationName}" in table "${X}"`):Error(`There are multiple relations between "${X}" and "${E.sourceTable[y.Symbol.Name]}". Please specify relation name`);if(D[0]&&b(D[0],gw)&&D[0].config)return{fields:D[0].config.references,references:D[0].config.fields};throw Error(`There is not enough information to infer relation "${A}.${E.fieldName}"`)}function N7($){return{one:eq($),many:$2($)}}function qJ($,w,E,X,G=(J)=>J){let J={};for(let[A,D]of X.entries())if(D.isJson){let N=w.relations[D.tsKey],W=E[A],O=typeof W==="string"?JSON.parse(W):W;J[D.tsKey]=b(N,gw)?O&&qJ($,$[D.relationTableTsKey],O,D.selection,G):O.map((Y)=>qJ($,$[D.relationTableTsKey],Y,D.selection,G))}else{let N=G(E[A]),W=D.field,O;if(b(W,V0))O=W;else if(b(W,h))O=W.decoder;else O=W.sql.decoder;J[D.tsKey]=N===null?null:O.mapFromDriverValue(N)}return J}var dD,X7,gw,zG;var TG=R(()=>{_$();b1();E0();yU();PJ();q$();dD=class dD{constructor($,w,E){this.sourceTable=$,this.referencedTable=w,this.relationName=E,this.referencedTableName=w[y.Symbol.Name]}static[K]="Relation";referencedTableName;fieldName};X7=class X7{constructor($,w){this.table=$,this.config=w}static[K]="Relations"};gw=class gw extends dD{constructor($,w,E,X){super($,w,E?.relationName);this.config=E,this.isNullable=X}static[K]="One";withFieldName($){let w=new gw(this.sourceTable,this.referencedTable,this.config,this.isNullable);return w.fieldName=$,w}};zG=class zG extends dD{constructor($,w,E){super($,w,E?.relationName);this.config=E}static[K]="Many";withFieldName($){let w=new zG(this.sourceTable,this.referencedTable,this.config);return w.fieldName=$,w}}});function SJ($,w){return new Proxy($,new BG(w,!1))}function s1($,w){return new Proxy($,new lE(new Proxy($.table,new BG(w,!1))))}function lD($,w){return new h.Aliased(QG($.sql,w),$.fieldAlias)}function QG($,w){return T.join($.queryChunks.map((E)=>{if(b(E,V0))return s1(E,w);if(b(E,h))return QG(E,w);if(b(E,h.Aliased))return lD(E,w);return E}))}var lE,BG;var kJ=R(()=>{b1();E0();q$();_$();Lw();lE=class lE{constructor($){this.table=$}static[K]="ColumnAliasProxyHandler";get($,w){if(w==="table")return this.table;return $[w]}};BG=class BG{constructor($,w){this.alias=$,this.replaceOriginalName=w}static[K]="TableAliasProxyHandler";get($,w){if(w===y.Symbol.IsAlias)return!0;if(w===y.Symbol.Name)return this.alias;if(this.replaceOriginalName&&w===y.Symbol.OriginalName)return this.alias;if(w===s0)return{...$[s0],name:this.alias,isAlias:!0};if(w===y.Symbol.Columns){let X=$[y.Symbol.Columns];if(!X)return X;let G={};return Object.keys(X).map((J)=>{G[J]=new Proxy(X[J],new lE(new Proxy($,this)))}),G}let E=$[w];if(b(E,V0))return new Proxy(E,new lE(new Proxy($,this)));return E}}});var A$;var sE=R(()=>{kJ();b1();E0();q$();d1();Lw();A$=class A${static[K]="SelectionProxyHandler";config;constructor($){this.config={...$}}get($,w){if(w==="_")return{...$._,selectedFields:new Proxy($._.selectedFields,this)};if(w===s0)return{...$[s0],selectedFields:new Proxy($[s0].selectedFields,this)};if(typeof w==="symbol")return $[w];let X=(b($,Y$)?$._.selectedFields:b($,U1)?$[s0].selectedFields:$)[w];if(b(X,h.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!X.isSelectionField)return X.sql;let G=X.clone();return G.isSelectionField=!0,G}if(b(X,h)){if(this.config.sqlBehavior==="sql")return X;throw Error(`You tried to reference "${w}" 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(b(X,V0)){if(this.config.alias)return new Proxy(X,new lE(new Proxy(X.table,new BG(this.config.alias,this.config.replaceOriginalName??!1))));return X}if(typeof X!=="object"||X===null)return X;return new Proxy(X,new A$(this.config))}}});var v$;var Fw=R(()=>{E0();v$=class v${static[K]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch($){return this.then(void 0,$)}finally($){return this.then((w)=>{return $?.(),w},(w)=>{throw $?.(),w})}then($,w){return this.execute().then($,w)}}});var sD,W7;var aD=R(()=>{E0();HG();sD=class sD{static[K]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor($,w){if(this.reference=()=>{let{name:E,columns:X,foreignColumns:G}=$();return{name:E,columns:X,foreignTable:G[0].table,foreignColumns:G}},w)this._onUpdate=w.onUpdate,this._onDelete=w.onDelete}onUpdate($){return this._onUpdate=$,this}onDelete($){return this._onDelete=$,this}build($){return new W7($,this)}};W7=class W7{constructor($,w){this.table=$,this.reference=w.reference,this.onUpdate=w._onUpdate,this.onDelete=w._onDelete}static[K]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:$,columns:w,foreignColumns:E}=this.reference(),X=w.map((A)=>A.name),G=E.map((A)=>A.name),J=[this.table[G1],...X,E[0].table[G1],...G];return $??`${J.join("_")}_fk`}}});function O7($,w){return`${$[G1]}_${w.join("_")}_unique`}var eD=R(()=>{HG()});var H$,w$;var uw=R(()=>{nD();b1();E0();aD();eD();H$=class H$ extends cD{static[K]="SQLiteColumnBuilder";foreignKeyConfigs=[];references($,w={}){return this.foreignKeyConfigs.push({ref:$,actions:w}),this}unique($){return this.config.isUnique=!0,this.config.uniqueName=$,this}generatedAlwaysAs($,w){return this.config.generated={as:$,type:"always",mode:w?.mode??"virtual"},this}buildForeignKeys($,w){return this.foreignKeyConfigs.map(({ref:E,actions:X})=>{return((G,J)=>{let A=new sD(()=>{let D=G();return{columns:[$],foreignColumns:[D]}});if(J.onUpdate)A.onUpdate(J.onUpdate);if(J.onDelete)A.onDelete(J.onDelete);return A.build(w)})(E,X)})}};w$=class w$ extends V0{constructor($,w){if(!w.uniqueName)w.uniqueName=O7($,[w.name]);super($,w);this.table=$}static[K]="SQLiteColumn"}});function M7($,w){let{name:E,config:X}=l1($,w);if(X?.mode==="json")return new H7(E);if(X?.mode==="bigint")return new U7(E);return new F7(E)}var U7,Y7,H7,L7,F7,j7;var $8=R(()=>{E0();o$();uw();U7=class U7 extends H${static[K]="SQLiteBigIntBuilder";constructor($){super($,"bigint","SQLiteBigInt")}build($){return new Y7($,this.config)}};Y7=class Y7 extends w${static[K]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue($){if(Buffer.isBuffer($))return BigInt($.toString());if($ instanceof ArrayBuffer)return BigInt(new TextDecoder().decode($));return BigInt(String.fromCodePoint(...$))}mapToDriverValue($){return Buffer.from($.toString())}};H7=class H7 extends H${static[K]="SQLiteBlobJsonBuilder";constructor($){super($,"json","SQLiteBlobJson")}build($){return new L7($,this.config)}};L7=class L7 extends w${static[K]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue($){if(Buffer.isBuffer($))return JSON.parse($.toString());if($ instanceof ArrayBuffer)return JSON.parse(new TextDecoder().decode($));return JSON.parse(String.fromCodePoint(...$))}mapToDriverValue($){return Buffer.from(JSON.stringify($))}};F7=class F7 extends H${static[K]="SQLiteBlobBufferBuilder";constructor($){super($,"buffer","SQLiteBlobBuffer")}build($){return new j7($,this.config)}};j7=class j7 extends w${static[K]="SQLiteBlobBuffer";mapFromDriverValue($){if(Buffer.isBuffer($))return $;return Buffer.from($)}getSQLType(){return"blob"}}});function T7($){return(w,E)=>{let{name:X,config:G}=l1(w,E);return new R7(X,G,$)}}var R7,z7;var w8=R(()=>{E0();o$();uw();R7=class R7 extends H${static[K]="SQLiteCustomColumnBuilder";constructor($,w,E){super($,"custom","SQLiteCustomColumn");this.config.fieldConfig=w,this.config.customTypeParams=E}build($){return new z7($,this.config)}};z7=class z7 extends w${static[K]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;constructor($,w){super($,w);this.sqlName=w.customTypeParams.dataType(w.fieldConfig),this.mapTo=w.customTypeParams.toDriver,this.mapFrom=w.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue($){return typeof this.mapFrom==="function"?this.mapFrom($):$}mapToDriverValue($){return typeof this.mapTo==="function"?this.mapTo($):$}}});function s($,w){let{name:E,config:X}=l1($,w);if(X?.mode==="timestamp"||X?.mode==="timestamp_ms")return new I7(E,X.mode);if(X?.mode==="boolean")return new V7(E,X.mode);return new B7(E)}var bJ,ZJ,B7,Q7,I7,K7,V7,P7;var E8=R(()=>{E0();q$();o$();uw();bJ=class bJ extends H${static[K]="SQLiteBaseIntegerBuilder";constructor($,w,E){super($,w,E);this.config.autoIncrement=!1}primaryKey($){if($?.autoIncrement)this.config.autoIncrement=!0;return this.config.hasDefault=!0,super.primaryKey()}};ZJ=class ZJ extends w${static[K]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}};B7=class B7 extends bJ{static[K]="SQLiteIntegerBuilder";constructor($){super($,"number","SQLiteInteger")}build($){return new Q7($,this.config)}};Q7=class Q7 extends ZJ{static[K]="SQLiteInteger"};I7=class I7 extends bJ{static[K]="SQLiteTimestampBuilder";constructor($,w){super($,"date","SQLiteTimestamp");this.config.mode=w}defaultNow(){return this.default(T`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build($){return new K7($,this.config)}};K7=class K7 extends ZJ{static[K]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue($){if(this.config.mode==="timestamp")return new Date($*1000);return new Date($)}mapToDriverValue($){let w=$.getTime();if(this.config.mode==="timestamp")return Math.floor(w/1000);return w}};V7=class V7 extends bJ{static[K]="SQLiteBooleanBuilder";constructor($,w){super($,"boolean","SQLiteBoolean");this.config.mode=w}build($){return new P7($,this.config)}};P7=class P7 extends ZJ{static[K]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue($){return Number($)===1}mapToDriverValue($){return $?1:0}}});function _7($,w){let{name:E,config:X}=l1($,w),G=X?.mode;return G==="number"?new k7(E):G==="bigint"?new Z7(E):new q7(E)}var q7,S7,k7,b7,Z7,C7;var X8=R(()=>{E0();o$();uw();q7=class q7 extends H${static[K]="SQLiteNumericBuilder";constructor($){super($,"string","SQLiteNumeric")}build($){return new S7($,this.config)}};S7=class S7 extends w${static[K]="SQLiteNumeric";mapFromDriverValue($){if(typeof $==="string")return $;return String($)}getSQLType(){return"numeric"}};k7=class k7 extends H${static[K]="SQLiteNumericNumberBuilder";constructor($){super($,"number","SQLiteNumericNumber")}build($){return new b7($,this.config)}};b7=class b7 extends w${static[K]="SQLiteNumericNumber";mapFromDriverValue($){if(typeof $==="number")return $;return Number($)}mapToDriverValue=String;getSQLType(){return"numeric"}};Z7=class Z7 extends H${static[K]="SQLiteNumericBigIntBuilder";constructor($){super($,"bigint","SQLiteNumericBigInt")}build($){return new C7($,this.config)}};C7=class C7 extends w${static[K]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}});function x7($){return new v7($??"")}var v7,f7;var G8=R(()=>{E0();uw();v7=class v7 extends H${static[K]="SQLiteRealBuilder";constructor($){super($,"number","SQLiteReal")}build($){return new f7($,this.config)}};f7=class f7 extends w${static[K]="SQLiteReal";getSQLType(){return"real"}}});function q($,w={}){let{name:E,config:X}=l1($,w);if(X.mode==="json")return new u7(E);return new y7(E,X)}var y7,g7,u7,h7;var J8=R(()=>{E0();o$();uw();y7=class y7 extends H${static[K]="SQLiteTextBuilder";constructor($,w){super($,"string","SQLiteText");this.config.enumValues=w.enum,this.config.length=w.length}build($){return new g7($,this.config)}};g7=class g7 extends w${static[K]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor($,w){super($,w)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}};u7=class u7 extends H${static[K]="SQLiteTextJsonBuilder";constructor($){super($,"json","SQLiteTextJson")}build($){return new h7($,this.config)}};h7=class h7 extends w${static[K]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue($){return JSON.parse($)}mapToDriverValue($){return JSON.stringify($)}}});function c7(){return{blob:M7,customType:T7,integer:s,numeric:_7,real:x7,text:q}}var n7=R(()=>{$8();w8();E8();X8();G8();J8()});function w2($,w,E,X,G=$){let J=new S$($,X,G),A=typeof w==="function"?w(c7()):w,D=Object.fromEntries(Object.entries(A).map(([W,O])=>{let Y=O;Y.setName(W);let H=Y.build(J);return J[A8].push(...Y.buildForeignKeys(H,J)),[W,H]})),N=Object.assign(J,D);if(N[y.Symbol.Columns]=D,N[y.Symbol.ExtraConfigColumns]=D,E)N[S$.Symbol.ExtraConfigBuilder]=E;return N}var A8,S$,M$=($,w,E)=>{return w2($,w,E)};var aE=R(()=>{E0();_$();n7();A8=Symbol.for("drizzle:SQLiteInlineForeignKeys");S$=class S$ extends y{static[K]="SQLiteTable";static Symbol=Object.assign({},y.Symbol,{InlineForeignKeys:A8});[y.Symbol.Columns];[A8]=[];[y.Symbol.ExtraConfigBuilder]=void 0}});var CJ;var m7=R(()=>{E0();Fw();sE();aE();_$();o$();CJ=class CJ extends v${constructor($,w,E,X){super();this.table=$,this.session=w,this.dialect=E,this.config={table:$,withList:X}}static[K]="SQLiteDelete";config;where($){return this.config.where=$,this}orderBy(...$){if(typeof $[0]==="function"){let w=$[0](new Proxy(this.config.table[y.Symbol.Columns],new A$({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),E=Array.isArray(w)?w:[w];this.config.orderBy=E}else{let w=$;this.config.orderBy=w}return this}limit($){return this.config.limit=$,this}returning($=this.table[S$.Symbol.Columns]){return this.config.returning=Y1($),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:$,...w}=this.dialect.sqlToQuery(this.getSQL());return w}_prepare($=!0){return this.session[$?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0)}prepare(){return this._prepare(!1)}run=($)=>{return this._prepare().run($)};all=($)=>{return this._prepare().all($)};get=($)=>{return this._prepare().get($)};values=($)=>{return this._prepare().values($)};async execute($){return this._prepare().execute($)}$dynamic(){return this}}});function E2($){return($.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((E)=>E.toLowerCase()).join("_")}function X2($){return($.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((E,X,G)=>{let J=G===0?X.toLowerCase():`${X[0].toUpperCase()}${X.slice(1)}`;return E+J},"")}function G2($){return $}var D8;var r7=R(()=>{E0();_$();D8=class D8{static[K]="CasingCache";cache={};cachedTables={};convert;constructor($){this.convert=$==="snake_case"?E2:$==="camelCase"?X2:G2}getColumnCasing($){if(!$.keyAsName)return $.name;let w=$.table[y.Symbol.Schema]??"public",E=$.table[y.Symbol.OriginalName],X=`${w}.${E}.${$.name}`;if(!this.cache[X])this.cacheTable($.table);return this.cache[X]}cacheTable($){let w=$[y.Symbol.Schema]??"public",E=$[y.Symbol.OriginalName],X=`${w}.${E}`;if(!this.cachedTables[X]){for(let G of Object.values($[y.Symbol.Columns])){let J=`${X}.${G.name}`;this.cache[J]=this.convert(G.name)}this.cachedTables[X]=!0}}clearCache(){this.cache={},this.cachedTables={}}}});var eE,N8;var _J=R(()=>{E0();eE=class eE extends Error{static[K]="DrizzleError";constructor({message:$,cause:w}){super($);this.name="DrizzleError",this.cause=w}};N8=class N8 extends eE{static[K]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}});var p7=()=>{};var o7=()=>{};var t7=R(()=>{p7();o7()});var W8=R(()=>{PJ();t7();q$()});var O8=R(()=>{$8();uw();w8();E8();X8();G8();J8()});var YE;var vJ=R(()=>{E0();q$();YE=class YE extends U1{static[K]="SQLiteViewBase"}});var IG,KG;var fJ=R(()=>{kJ();r7();b1();E0();_J();TG();W8();q$();O8();aE();d1();_$();o$();Lw();vJ();IG=class IG{static[K]="SQLiteDialect";casing;constructor($){this.casing=new D8($?.casing)}escapeName($){return`"${$}"`}escapeParam($){return"?"}escapeString($){return`'${$.replace(/'/g,"''")}'`}buildWithCTE($){if(!$?.length)return;let w=[T`with `];for(let[E,X]of $.entries())if(w.push(T`${T.identifier(X._.alias)} as (${X._.sql})`),E<$.length-1)w.push(T`, `);return w.push(T` `),T.join(w)}buildDeleteQuery({table:$,where:w,returning:E,withList:X,limit:G,orderBy:J}){let A=this.buildWithCTE(X),D=E?T` returning ${this.buildSelection(E,{isSingleTable:!0})}`:void 0,N=w?T` where ${w}`:void 0,W=this.buildOrderBy(J),O=this.buildLimit(G);return T`${A}delete from ${$}${N}${D}${W}${O}`}buildUpdateSet($,w){let E=$[y.Symbol.Columns],X=Object.keys(E).filter((J)=>w[J]!==void 0||E[J]?.onUpdateFn!==void 0),G=X.length;return T.join(X.flatMap((J,A)=>{let D=E[J],N=w[J]??T.param(D.onUpdateFn(),D),W=T`${T.identifier(this.casing.getColumnCasing(D))} = ${N}`;if(A<G-1)return[W,T.raw(", ")];return[W]}))}buildUpdateQuery({table:$,set:w,where:E,returning:X,withList:G,joins:J,from:A,limit:D,orderBy:N}){let W=this.buildWithCTE(G),O=this.buildUpdateSet($,w),Y=A&&T.join([T.raw(" from "),this.buildFromTable(A)]),H=this.buildJoins(J),L=X?T` returning ${this.buildSelection(X,{isSingleTable:!0})}`:void 0,F=E?T` where ${E}`:void 0,j=this.buildOrderBy(N),M=this.buildLimit(D);return T`${W}update ${$} set ${O}${Y}${H}${F}${L}${j}${M}`}buildSelection($,{isSingleTable:w=!1}={}){let E=$.length,X=$.flatMap(({field:G},J)=>{let A=[];if(b(G,h.Aliased)&&G.isSelectionField)A.push(T.identifier(G.fieldAlias));else if(b(G,h.Aliased)||b(G,h)){let D=b(G,h.Aliased)?G.sql:G;if(w)A.push(new h(D.queryChunks.map((N)=>{if(b(N,V0))return T.identifier(this.casing.getColumnCasing(N));return N})));else A.push(D);if(b(G,h.Aliased))A.push(T` as ${T.identifier(G.fieldAlias)}`)}else if(b(G,V0)){let D=G.table[y.Symbol.Name];if(G.columnType==="SQLiteNumericBigInt")if(w)A.push(T`cast(${T.identifier(this.casing.getColumnCasing(G))} as text)`);else A.push(T`cast(${T.identifier(D)}.${T.identifier(this.casing.getColumnCasing(G))} as text)`);else if(w)A.push(T.identifier(this.casing.getColumnCasing(G)));else A.push(T`${T.identifier(D)}.${T.identifier(this.casing.getColumnCasing(G))}`)}if(J<E-1)A.push(T`, `);return A});return T.join(X)}buildJoins($){if(!$||$.length===0)return;let w=[];if($)for(let[E,X]of $.entries()){if(E===0)w.push(T` `);let G=X.table;if(b(G,S$)){let J=G[S$.Symbol.Name],A=G[S$.Symbol.Schema],D=G[S$.Symbol.OriginalName],N=J===D?void 0:X.alias;w.push(T`${T.raw(X.joinType)} join ${A?T`${T.identifier(A)}.`:void 0}${T.identifier(D)}${N&&T` ${T.identifier(N)}`} on ${X.on}`)}else w.push(T`${T.raw(X.joinType)} join ${G} on ${X.on}`);if(E<$.length-1)w.push(T` `)}return T.join(w)}buildLimit($){return typeof $==="object"||typeof $==="number"&&$>=0?T` limit ${$}`:void 0}buildOrderBy($){let w=[];if($){for(let[E,X]of $.entries())if(w.push(X),E<$.length-1)w.push(T`, `)}return w.length>0?T` order by ${T.join(w)}`:void 0}buildFromTable($){if(b($,y)&&$[y.Symbol.IsAlias])return T`${T`${T.identifier($[y.Symbol.Schema]??"")}.`.if($[y.Symbol.Schema])}${T.identifier($[y.Symbol.OriginalName])} ${T.identifier($[y.Symbol.Name])}`;return $}buildSelectQuery({withList:$,fields:w,fieldsFlat:E,where:X,having:G,table:J,joins:A,orderBy:D,groupBy:N,limit:W,offset:O,distinct:Y,setOperators:H}){let L=E??Y1(w);for(let K0 of L)if(b(K0.field,V0)&&xw(K0.field.table)!==(b(J,Y$)?J._.alias:b(J,YE)?J[s0].name:b(J,h)?void 0:xw(J))&&!((U$)=>A?.some(({alias:O1})=>O1===(U$[y.Symbol.IsAlias]?xw(U$):U$[y.Symbol.BaseName])))(K0.field.table)){let U$=xw(K0.field.table);throw Error(`Your "${K0.path.join("->")}" field references a column "${U$}"."${K0.field.name}", but the table "${U$}" is not part of the query! Did you forget to join it?`)}let F=!A||A.length===0,j=this.buildWithCTE($),M=Y?T` distinct`:void 0,z=this.buildSelection(L,{isSingleTable:F}),B=this.buildFromTable(J),Q=this.buildJoins(A),k=X?T` where ${X}`:void 0,v=G?T` having ${G}`:void 0,C=[];if(N){for(let[K0,U$]of N.entries())if(C.push(U$),K0<N.length-1)C.push(T`, `)}let n=C.length>0?T` group by ${T.join(C)}`:void 0,T0=this.buildOrderBy(D),f0=this.buildLimit(W),c0=O?T` offset ${O}`:void 0,d0=T`${j}select${M} ${z} from ${B}${Q}${k}${n}${v}${T0}${f0}${c0}`;if(H.length>0)return this.buildSetOperations(d0,H);return d0}buildSetOperations($,w){let[E,...X]=w;if(!E)throw Error("Cannot pass undefined values to any set operator");if(X.length===0)return this.buildSetOperationQuery({leftSelect:$,setOperator:E});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:$,setOperator:E}),X)}buildSetOperationQuery({leftSelect:$,setOperator:{type:w,isAll:E,rightSelect:X,limit:G,orderBy:J,offset:A}}){let D=T`${$.getSQL()} `,N=T`${X.getSQL()}`,W;if(J&&J.length>0){let L=[];for(let F of J)if(b(F,w$))L.push(T.identifier(F.name));else if(b(F,h)){for(let j=0;j<F.queryChunks.length;j++){let M=F.queryChunks[j];if(b(M,w$))F.queryChunks[j]=T.identifier(this.casing.getColumnCasing(M))}L.push(T`${F}`)}else L.push(T`${F}`);W=T` order by ${T.join(L,T`, `)}`}let O=typeof G==="object"||typeof G==="number"&&G>=0?T` limit ${G}`:void 0,Y=T.raw(`${w} ${E?"all ":""}`),H=A?T` offset ${A}`:void 0;return T`${D}${Y}${N}${W}${O}${H}`}buildInsertQuery({table:$,values:w,onConflict:E,returning:X,withList:G,select:J}){let A=[],D=$[y.Symbol.Columns],N=Object.entries(D).filter(([F,j])=>!j.shouldDisableInsert()),W=N.map(([,F])=>T.identifier(this.casing.getColumnCasing(F)));if(J){let F=w;if(b(F,h))A.push(F);else A.push(F.getSQL())}else{let F=w;A.push(T.raw("values "));for(let[j,M]of F.entries()){let z=[];for(let[B,Q]of N){let k=M[B];if(k===void 0||b(k,J1)&&k.value===void 0){let v;if(Q.default!==null&&Q.default!==void 0)v=b(Q.default,h)?Q.default:T.param(Q.default,Q);else if(Q.defaultFn!==void 0){let C=Q.defaultFn();v=b(C,h)?C:T.param(C,Q)}else if(!Q.default&&Q.onUpdateFn!==void 0){let C=Q.onUpdateFn();v=b(C,h)?C:T.param(C,Q)}else v=T`null`;z.push(v)}else z.push(k)}if(A.push(z),j<F.length-1)A.push(T`, `)}}let O=this.buildWithCTE(G),Y=T.join(A),H=X?T` returning ${this.buildSelection(X,{isSingleTable:!0})}`:void 0,L=E?.length?T.join(E):void 0;return T`${O}insert into ${$} ${W} ${Y}${L}${H}`}sqlToQuery($,w){return $.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,invokeSource:w})}buildRelationalQuery({fullSchema:$,schema:w,tableNamesMap:E,table:X,tableConfig:G,queryConfig:J,tableAlias:A,nestedQueryRelation:D,joinOn:N}){let W=[],O,Y,H=[],L,F=[];if(J===!0)W=Object.entries(G.columns).map(([z,B])=>({dbKey:B.name,tsKey:z,field:s1(B,A),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let M=Object.fromEntries(Object.entries(G.columns).map(([C,n])=>[C,s1(n,A)]));if(J.where){let C=typeof J.where==="function"?J.where(M,G7()):J.where;L=C&&QG(C,A)}let z=[],B=[];if(J.columns){let C=!1;for(let[n,T0]of Object.entries(J.columns)){if(T0===void 0)continue;if(n in G.columns){if(!C&&T0===!0)C=!0;B.push(n)}}if(B.length>0)B=C?B.filter((n)=>J.columns?.[n]===!0):Object.keys(G.columns).filter((n)=>!B.includes(n))}else B=Object.keys(G.columns);for(let C of B){let n=G.columns[C];z.push({tsKey:C,value:n})}let Q=[];if(J.with)Q=Object.entries(J.with).filter((C)=>!!C[1]).map(([C,n])=>({tsKey:C,queryConfig:n,relation:G.relations[C]}));let k;if(J.extras){k=typeof J.extras==="function"?J.extras(M,{sql:T}):J.extras;for(let[C,n]of Object.entries(k))z.push({tsKey:C,value:lD(n,A)})}for(let{tsKey:C,value:n}of z)W.push({dbKey:b(n,h.Aliased)?n.fieldAlias:G.columns[C].name,tsKey:C,field:b(n,V0)?s1(n,A):n,relationTableTsKey:void 0,isJson:!1,selection:[]});let v=typeof J.orderBy==="function"?J.orderBy(M,J7()):J.orderBy??[];if(!Array.isArray(v))v=[v];H=v.map((C)=>{if(b(C,V0))return s1(C,A);return QG(C,A)}),O=J.limit,Y=J.offset;for(let{tsKey:C,queryConfig:n,relation:T0}of Q){let f0=D7(w,E,T0),c0=UE(T0.referencedTable),d0=E[c0],K0=`${A}_${C}`,U$=S0(...f0.fields.map((VV,PV)=>V(s1(f0.references[PV],K0),s1(VV,A)))),O1=this.buildRelationalQuery({fullSchema:$,schema:w,tableNamesMap:E,table:$[d0],tableConfig:w[d0],queryConfig:b(T0,gw)?n===!0?{limit:1}:{...n,limit:1}:n,tableAlias:K0,joinOn:U$,nestedQueryRelation:T0}),KV=T`(${O1.sql})`.as(C);W.push({dbKey:C,tsKey:C,field:KV,relationTableTsKey:d0,isJson:!0,selection:O1.selection})}}if(W.length===0)throw new eE({message:`No fields selected for table "${G.tsName}" ("${A}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.`});let j;if(L=S0(N,L),D){let M=T`json_array(${T.join(W.map(({field:Q})=>b(Q,w$)?T.identifier(this.casing.getColumnCasing(Q)):b(Q,h.Aliased)?Q.sql:Q),T`, `)})`;if(b(D,zG))M=T`coalesce(json_group_array(${M}), json_array())`;let z=[{dbKey:"data",tsKey:"data",field:M.as("data"),isJson:!0,relationTableTsKey:G.tsName,selection:W}];if(O!==void 0||Y!==void 0||H.length>0)j=this.buildSelectQuery({table:SJ(X,A),fields:{},fieldsFlat:[{path:[],field:T.raw("*")}],where:L,limit:O,offset:Y,orderBy:H,setOperators:[]}),L=void 0,O=void 0,Y=void 0,H=void 0;else j=SJ(X,A);j=this.buildSelectQuery({table:b(j,S$)?j:new Y$(j,{},A),fields:{},fieldsFlat:z.map(({field:Q})=>({path:[],field:b(Q,V0)?s1(Q,A):Q})),joins:F,where:L,limit:O,offset:Y,orderBy:H,setOperators:[]})}else j=this.buildSelectQuery({table:SJ(X,A),fields:{},fieldsFlat:W.map(({field:M})=>({path:[],field:b(M,V0)?s1(M,A):M})),joins:F,where:L,limit:O,offset:Y,orderBy:H,setOperators:[]});return{tableTsKey:G.tsName,sql:j,selection:W}}};KG=class KG extends IG{static[K]="SQLiteSyncDialect";migrate($,w,E){let X=E===void 0?"__drizzle_migrations":typeof E==="string"?"__drizzle_migrations":E.migrationsTable??"__drizzle_migrations",G=T`
|
|
29
|
+
`)}),this}_outputHelpIfRequested($){let w=this._getHelpOption();if(w&&$.find((X)=>w.is(X)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function DU($){return $.map((w)=>{if(!w.startsWith("--inspect"))return w;let E,X="127.0.0.1",G="9229",J;if((J=w.match(/^(--inspect(-brk)?)$/))!==null)E=J[1];else if((J=w.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(E=J[1],/^\d+$/.test(J[3]))G=J[3];else X=J[3];else if((J=w.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)E=J[1],X=J[3],G=J[4];if(E&&G!=="0")return`${E}=${X}:${parseInt(G)+1}`;return w})}function fD(){if(Q0.env.NO_COLOR||Q0.env.FORCE_COLOR==="0"||Q0.env.FORCE_COLOR==="false")return!1;if(Q0.env.FORCE_COLOR||Q0.env.CLICOLOR_FORCE!==void 0)return!0;return}Zq.Command=xD;Zq.useColor=fD});var YU=Z((xq)=>{var{Argument:WU}=jJ(),{Command:yD}=NU(),{CommanderError:vq,InvalidArgumentError:OU}=HG(),{Help:fq}=ZD(),{Option:UU}=CD();xq.program=new yD;xq.createCommand=($)=>new yD($);xq.createOption=($,w)=>new UU($,w);xq.createArgument=($,w)=>new WU($,w);xq.Command=yD;xq.Option=UU;xq.Argument=WU;xq.Help=fq;xq.CommanderError=vq;xq.InvalidArgumentError=OU;xq.InvalidOptionArgumentError=OU});function RJ($,w,E,X){if(LU[$]<LU[dq])return;let G=new Date().toISOString(),A=`${iq[$]}[${$.toUpperCase()}]\x1B[0m ${G} [${w}]`;if(X!==void 0)console.error(`${A} ${E}`,X);else console.error(`${A} ${E}`)}function Z0($){return{debug:(w,E)=>RJ("debug",$,w,E),info:(w,E)=>RJ("info",$,w,E),warn:(w,E)=>RJ("warn",$,w,E),error:(w,E)=>RJ("error",$,w,E)}}var LU,iq,dq;var p$=R(()=>{LU={debug:0,info:1,warn:2,error:3},iq={debug:"\x1B[36m",info:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m"},dq=process.env.ORC_LOG_LEVEL??"info"});import{randomBytes as lq}from"crypto";function eq($,w){let E="";for(let X=w-1;X>=0;X--){let G=$%gD;E=uD[G]+E,$=Math.floor($/gD)}return E}function $2($){let w=lq($),E="";for(let X=0;X<$;X++)E+=uD[(w[X]??0)%gD];return E}function i(){return eq(Date.now(),sq)+$2(aq)}var uD="0123456789ABCDEFGHJKMNPQRSTVWXYZ",gD,sq=10,aq=16;var X1=R(()=>{gD=uD.length});function b($,w){if(!$||typeof $!=="object")return!1;if($ instanceof w)return!0;if(!Object.prototype.hasOwnProperty.call(w,K))throw Error(`Class "${w.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 E=Object.getPrototypeOf($).constructor;if(E)while(E){if(K in E&&E[K]===w[K])return!0;E=Object.getPrototypeOf(E)}return!1}var K;var E0=R(()=>{K=Symbol.for("drizzle:entityKind")});var FU,hD,cD;var zJ=R(()=>{E0();FU=class FU{static[K]="ConsoleLogWriter";write($){console.log($)}};hD=class hD{static[K]="DefaultLogger";writer;constructor($){this.writer=$?.writer??new FU}logQuery($,w){let E=w.map((G)=>{try{return JSON.stringify(G)}catch{return String(G)}}),X=E.length?` -- params: [${E.join(", ")}]`:"";this.writer.write(`Query: ${$}${X}`)}};cD=class cD{static[K]="NoopLogger";logQuery(){}}});var G1;var LG=R(()=>{G1=Symbol.for("drizzle:Name")});function xw($){return $[G1]}function UE($){return`${$[TJ]??"public"}.${$[G1]}`}var TJ,BJ,jU,nD,mD,FG,MU,w2,y;var _$=R(()=>{E0();LG();TJ=Symbol.for("drizzle:Schema"),BJ=Symbol.for("drizzle:Columns"),jU=Symbol.for("drizzle:ExtraConfigColumns"),nD=Symbol.for("drizzle:OriginalName"),mD=Symbol.for("drizzle:BaseName"),FG=Symbol.for("drizzle:IsAlias"),MU=Symbol.for("drizzle:ExtraConfigBuilder"),w2=Symbol.for("drizzle:IsDrizzleTable");y=class y{static[K]="Table";static Symbol={Name:G1,Schema:TJ,OriginalName:nD,Columns:BJ,ExtraConfigColumns:jU,BaseName:mD,IsAlias:FG,ExtraConfigBuilder:MU};[G1];[nD];[TJ];[BJ];[jU];[mD];[FG]=!1;[w2]=!0;[MU]=void 0;constructor($,w,E){this[G1]=this[nD]=$,this[TJ]=w,this[mD]=E}}});var V0;var b1=R(()=>{E0();V0=class V0{constructor($,w){this.table=$,this.config=w,this.name=w.name,this.keyAsName=w.keyAsName,this.notNull=w.notNull,this.default=w.default,this.defaultFn=w.defaultFn,this.onUpdateFn=w.onUpdateFn,this.hasDefault=w.hasDefault,this.primary=w.primaryKey,this.isUnique=w.isUnique,this.uniqueName=w.uniqueName,this.uniqueType=w.uniqueType,this.dataType=w.dataType,this.columnType=w.columnType,this.generated=w.generated,this.generatedIdentity=w.generatedIdentity}static[K]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue($){return $}mapToDriverValue($){return $}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}});var rD;var pD=R(()=>{E0();rD=class rD{static[K]="ColumnBuilder";config;constructor($,w,E){this.config={name:$,keyAsName:$==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:w,columnType:E,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default($){return this.config.default=$,this.config.hasDefault=!0,this}$defaultFn($){return this.config.defaultFn=$,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn($){return this.config.onUpdateFn=$,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName($){if(this.config.name!=="")return;this.config.name=$}}});function RU($,...w){return $(...w)}var zU=()=>{};function TU($,w){return`${$[G1]}_${w.join("_")}_unique`}var BU=R(()=>{LG()});var QJ,E2;var QU=R(()=>{b1();E0();BU();QJ=class QJ extends V0{constructor($,w){if(!w.uniqueName)w.uniqueName=TU($,[w.name]);super($,w);this.table=$}static[K]="PgColumn"};E2=class E2 extends QJ{static[K]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op($){return this.indexConfig.opClass=$,this}}});function KU($){return!!$&&typeof $==="function"&&IU in $&&$[IU]===!0}var IU,X2;var VU=R(()=>{E0();QU();IU=Symbol.for("drizzle:isPgEnum");X2=class X2 extends QJ{static[K]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor($,w){super($,w);this.enum=w.enum}getSQLType(){return this.enum.enumName}}});var Y$,jG;var d1=R(()=>{E0();Y$=class Y${static[K]="Subquery";constructor($,w,E,X=!1){this._={brand:"Subquery",sql:$,selectedFields:w,alias:E,isWith:X}}};jG=class jG extends Y${static[K]="WithSubquery"}});var PU="0.41.0";var qU=()=>{};var oD,tD,SU;var kU=R(()=>{zU();qU();SU={startActiveSpan($,w){if(!oD)return w();if(!tD)tD=oD.trace.getTracer("drizzle-orm",PU);return RU((E,X)=>X.startActiveSpan($,(G)=>{try{return w(G)}catch(J){throw G.setStatus({code:E.SpanStatusCode.ERROR,message:J instanceof Error?J.message:"Unknown error"}),J}finally{G.end()}}),oD,tD)}}});var s0;var Lw=R(()=>{s0=Symbol.for("drizzle:ViewBaseConfig")});function iD($){return $!==null&&$!==void 0&&typeof $.getSQL==="function"}function G2($){let w={sql:"",params:[]};for(let E of $)if(w.sql+=E.sql,w.params.push(...E.params),E.typings?.length){if(!w.typings)w.typings=[];w.typings.push(...E.typings)}return w}function bU($){return typeof $==="object"&&$!==null&&"mapToDriverValue"in $&&typeof $.mapToDriverValue==="function"}function T($,...w){let E=[];if(w.length>0||$.length>0&&$[0]!=="")E.push(new W$($[0]));for(let[X,G]of w.entries())E.push(G,new W$($[X+1]));return new h(E)}function MG($,w){return $.map((E)=>{if(b(E,yw)){if(!(E.name in w))throw Error(`No value for placeholder "${E.name}" was provided`);return w[E.name]}if(b(E,J1)&&b(E.value,yw)){if(!(E.value.name in w))throw Error(`No value for placeholder "${E.value.name}" was provided`);return E.encoder.mapToDriverValue(w[E.value.name])}return E})}var W$,h,IJ,ZU,CU,ut,J1,yw,J2,U1;var q$=R(()=>{E0();VU();d1();kU();Lw();b1();_$();W$=class W${static[K]="StringChunk";value;constructor($){this.value=Array.isArray($)?$:[$]}getSQL(){return new h([this])}};h=class h{constructor($){this.queryChunks=$}static[K]="SQL";decoder=ZU;shouldInlineParams=!1;append($){return this.queryChunks.push(...$.queryChunks),this}toQuery($){return SU.startActiveSpan("drizzle.buildSQL",(w)=>{let E=this.buildQueryFromSourceParams(this.queryChunks,$);return w?.setAttributes({"drizzle.query.text":E.sql,"drizzle.query.params":JSON.stringify(E.params)}),E})}buildQueryFromSourceParams($,w){let E=Object.assign({},w,{inlineParams:w.inlineParams||this.shouldInlineParams,paramStartIndex:w.paramStartIndex||{value:0}}),{casing:X,escapeName:G,escapeParam:J,prepareTyping:A,inlineParams:D,paramStartIndex:N}=E;return G2($.map((W)=>{if(b(W,W$))return{sql:W.value.join(""),params:[]};if(b(W,IJ))return{sql:G(W.value),params:[]};if(W===void 0)return{sql:"",params:[]};if(Array.isArray(W)){let O=[new W$("(")];for(let[Y,H]of W.entries())if(O.push(H),Y<W.length-1)O.push(new W$(", "));return O.push(new W$(")")),this.buildQueryFromSourceParams(O,E)}if(b(W,h))return this.buildQueryFromSourceParams(W.queryChunks,{...E,inlineParams:D||W.shouldInlineParams});if(b(W,y)){let O=W[y.Symbol.Schema],Y=W[y.Symbol.Name];return{sql:O===void 0||W[FG]?G(Y):G(O)+"."+G(Y),params:[]}}if(b(W,V0)){let O=X.getColumnCasing(W);if(w.invokeSource==="indexes")return{sql:G(O),params:[]};let Y=W.table[y.Symbol.Schema];return{sql:W.table[FG]||Y===void 0?G(W.table[y.Symbol.Name])+"."+G(O):G(Y)+"."+G(W.table[y.Symbol.Name])+"."+G(O),params:[]}}if(b(W,U1)){let O=W[s0].schema,Y=W[s0].name;return{sql:O===void 0||W[s0].isAlias?G(Y):G(O)+"."+G(Y),params:[]}}if(b(W,J1)){if(b(W.value,yw))return{sql:J(N.value++,W),params:[W],typings:["none"]};let O=W.value===null?null:W.encoder.mapToDriverValue(W.value);if(b(O,h))return this.buildQueryFromSourceParams([O],E);if(D)return{sql:this.mapInlineParam(O,E),params:[]};let Y=["none"];if(A)Y=[A(W.encoder)];return{sql:J(N.value++,O),params:[O],typings:Y}}if(b(W,yw))return{sql:J(N.value++,W),params:[W],typings:["none"]};if(b(W,h.Aliased)&&W.fieldAlias!==void 0)return{sql:G(W.fieldAlias),params:[]};if(b(W,Y$)){if(W._.isWith)return{sql:G(W._.alias),params:[]};return this.buildQueryFromSourceParams([new W$("("),W._.sql,new W$(") "),new IJ(W._.alias)],E)}if(KU(W)){if(W.schema)return{sql:G(W.schema)+"."+G(W.enumName),params:[]};return{sql:G(W.enumName),params:[]}}if(iD(W)){if(W.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([W.getSQL()],E);return this.buildQueryFromSourceParams([new W$("("),W.getSQL(),new W$(")")],E)}if(D)return{sql:this.mapInlineParam(W,E),params:[]};return{sql:J(N.value++,W),params:[W],typings:["none"]}}))}mapInlineParam($,{escapeString:w}){if($===null)return"null";if(typeof $==="number"||typeof $==="boolean")return $.toString();if(typeof $==="string")return w($);if(typeof $==="object"){let E=$.toString();if(E==="[object Object]")return w(JSON.stringify($));return w(E)}throw Error("Unexpected param value: "+$)}getSQL(){return this}as($){if($===void 0)return this;return new h.Aliased(this,$)}mapWith($){return this.decoder=typeof $==="function"?{mapFromDriverValue:$}:$,this}inlineParams(){return this.shouldInlineParams=!0,this}if($){return $?this:void 0}};IJ=class IJ{constructor($){this.value=$}static[K]="Name";brand;getSQL(){return new h([this])}};ZU={mapFromDriverValue:($)=>$},CU={mapToDriverValue:($)=>$},ut={...ZU,...CU};J1=class J1{constructor($,w=CU){this.value=$,this.encoder=w}static[K]="Param";brand;getSQL(){return new h([this])}};(($)=>{function w(){return new h([])}$.empty=w;function E(N){return new h(N)}$.fromList=E;function X(N){return new h([new W$(N)])}$.raw=X;function G(N,W){let O=[];for(let[Y,H]of N.entries()){if(Y>0&&W!==void 0)O.push(W);O.push(H)}return new h(O)}$.join=G;function J(N){return new IJ(N)}$.identifier=J;function A(N){return new yw(N)}$.placeholder=A;function D(N,W){return new J1(N,W)}$.param=D})(T||(T={}));(($)=>{class w{constructor(E,X){this.sql=E,this.fieldAlias=X}static[K]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new w(this.sql,this.fieldAlias)}}$.Aliased=w})(h||(h={}));yw=class yw{constructor($){this.name=$}static[K]="Placeholder";getSQL(){return new h([this])}};J2=Symbol.for("drizzle:IsDrizzleView");U1=class U1{static[K]="View";[s0];[J2]=!0;constructor({name:$,schema:w,selectedFields:E,query:X}){this[s0]={name:$,originalName:$,schema:w,selectedFields:E,query:X,isExisting:!X,isAlias:!1}}getSQL(){return new h([this])}};V0.prototype.getSQL=function(){return new h([this])};y.prototype.getSQL=function(){return new h([this])};Y$.prototype.getSQL=function(){return new h([this])}});function dD($,w,E){let X={},G=$.reduce((J,{path:A,field:D},N)=>{let W;if(b(D,V0))W=D;else if(b(D,h))W=D.decoder;else W=D.sql.decoder;let O=J;for(let[Y,H]of A.entries())if(Y<A.length-1){if(!(H in O))O[H]={};O=O[H]}else{let L=w[N],F=O[H]=L===null?null:W.mapFromDriverValue(L);if(E&&b(D,V0)&&A.length===2){let j=A[0];if(!(j in X))X[j]=F===null?xw(D.table):!1;else if(typeof X[j]==="string"&&X[j]!==xw(D.table))X[j]=!1}}return J},{});if(E&&Object.keys(X).length>0){for(let[J,A]of Object.entries(X))if(typeof A==="string"&&!E[A])G[J]=null}return G}function Y1($,w){return Object.entries($).reduce((E,[X,G])=>{if(typeof X!=="string")return E;let J=w?[...w,X]:[X];if(b(G,V0)||b(G,h)||b(G,h.Aliased))E.push({path:J,field:G});else if(b(G,y))E.push(...Y1(G[y.Symbol.Columns],J));else E.push(...Y1(G,J));return E},[])}function RG($,w){let E=Object.keys($),X=Object.keys(w);if(E.length!==X.length)return!1;for(let[G,J]of E.entries())if(J!==X[G])return!1;return!0}function KJ($,w){let E=Object.entries(w).filter(([,X])=>X!==void 0).map(([X,G])=>{if(b(G,h)||b(G,V0))return[X,G];else return[X,new J1(G,$[y.Symbol.Columns][X])]});if(E.length===0)throw Error("No values to set");return Object.fromEntries(E)}function _U($,w){for(let E of w)for(let X of Object.getOwnPropertyNames(E.prototype)){if(X==="constructor")continue;Object.defineProperty($.prototype,X,Object.getOwnPropertyDescriptor(E.prototype,X)||Object.create(null))}}function vU($){return $[y.Symbol.Columns]}function zG($){return b($,Y$)?$._.alias:b($,U1)?$[s0].name:b($,h)?void 0:$[y.Symbol.IsAlias]?$[y.Symbol.Name]:$[y.Symbol.BaseName]}function l1($,w){return{name:typeof $==="string"&&$.length>0?$:"",config:typeof $==="object"?$:w}}function fU($){if(typeof $!=="object"||$===null)return!1;if($.constructor.name!=="Object")return!1;if("logger"in $){let w=typeof $.logger;if(w!=="boolean"&&(w!=="object"||typeof $.logger.logQuery!=="function")&&w!=="undefined")return!1;return!0}if("schema"in $){let w=typeof $.schema;if(w!=="object"&&w!=="undefined")return!1;return!0}if("casing"in $){let w=typeof $.casing;if(w!=="string"&&w!=="undefined")return!1;return!0}if("mode"in $){if($.mode!=="default"||$.mode!=="planetscale"||$.mode!==void 0)return!1;return!0}if("connection"in $){let w=typeof $.connection;if(w!=="string"&&w!=="object"&&w!=="undefined")return!1;return!0}if("client"in $){let w=typeof $.client;if(w!=="object"&&w!=="function"&&w!=="undefined")return!1;return!0}if(Object.keys($).length===0)return!0;return!1}var o$=R(()=>{b1();E0();q$();d1();_$();Lw()});var xU,yU,lD;var gU=R(()=>{E0();_$();xU=Symbol.for("drizzle:PgInlineForeignKeys"),yU=Symbol.for("drizzle:EnableRLS");lD=class lD extends y{static[K]="PgTable";static Symbol=Object.assign({},y.Symbol,{InlineForeignKeys:xU,EnableRLS:yU});[xU]=[];[yU]=!1;[y.Symbol.ExtraConfigBuilder]=void 0;[y.Symbol.ExtraConfigColumns]={}}});var sD,uU;var hU=R(()=>{E0();gU();sD=class sD{static[K]="PgPrimaryKeyBuilder";columns;name;constructor($,w){this.columns=$,this.name=w}build($){return new uU($,this.columns,this.name)}};uU=class uU{constructor($,w,E){this.table=$,this.columns=w,this.name=E}static[K]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[lD.Symbol.Name]}_${this.columns.map(($)=>$.name).join("_")}_pk`}}});function t$($,w){if(bU(w)&&!iD($)&&!b($,J1)&&!b($,yw)&&!b($,V0)&&!b($,y)&&!b($,U1))return new J1($,w);return $}function S0(...$){let w=$.filter((E)=>E!==void 0);if(w.length===0)return;if(w.length===1)return new h(w);return new h([new W$("("),T.join(w,new W$(" and ")),new W$(")")])}function VJ(...$){let w=$.filter((E)=>E!==void 0);if(w.length===0)return;if(w.length===1)return new h(w);return new h([new W$("("),T.join(w,new W$(" or ")),new W$(")")])}function nU($){return T`not ${$}`}function PJ($,w){if(Array.isArray(w)){if(w.length===0)return T`false`;return T`${$} in ${w.map((E)=>t$(E,$))}`}return T`${$} in ${t$(w,$)}`}function tU($,w){if(Array.isArray(w)){if(w.length===0)return T`true`;return T`${$} not in ${w.map((E)=>t$(E,$))}`}return T`${$} not in ${t$(w,$)}`}function iU($){return T`${$} is null`}function dU($){return T`${$} is not null`}function lU($){return T`exists ${$}`}function sU($){return T`not exists ${$}`}function aU($,w,E){return T`${$} between ${t$(w,$)} and ${t$(E,$)}`}function eU($,w,E){return T`${$} not between ${t$(w,$)} and ${t$(E,$)}`}function $7($,w){return T`${$} like ${w}`}function w7($,w){return T`${$} not like ${w}`}function E7($,w){return T`${$} ilike ${w}`}function X7($,w){return T`${$} not ilike ${w}`}var V=($,w)=>{return T`${$} = ${t$(w,$)}`},cU=($,w)=>{return T`${$} <> ${t$(w,$)}`},mU=($,w)=>{return T`${$} > ${t$(w,$)}`},rU=($,w)=>{return T`${$} >= ${t$(w,$)}`},pU=($,w)=>{return T`${$} < ${t$(w,$)}`},oU=($,w)=>{return T`${$} <= ${t$(w,$)}`};var G7=R(()=>{b1();E0();_$();q$()});function qJ($){return T`${$} asc`}function x0($){return T`${$} desc`}var J7=R(()=>{q$()});var SJ=R(()=>{G7();J7()});function D7(){return{and:S0,between:aU,eq:V,exists:lU,gt:mU,gte:rU,ilike:E7,inArray:PJ,isNull:iU,isNotNull:dU,like:$7,lt:pU,lte:oU,ne:cU,not:nU,notBetween:eU,notExists:sU,notLike:w7,notIlike:X7,notInArray:tU,or:VJ,sql:T}}function N7(){return{sql:T,asc:qJ,desc:x0}}function W7($,w){if(Object.keys($).length===1&&"default"in $&&!b($.default,y))$=$.default;let E={},X={},G={};for(let[J,A]of Object.entries($))if(b(A,y)){let D=UE(A),N=X[D];E[D]=J,G[J]={tsName:J,dbName:A[y.Symbol.Name],schema:A[y.Symbol.Schema],columns:A[y.Symbol.Columns],relations:N?.relations??{},primaryKey:N?.primaryKey??[]};for(let O of Object.values(A[y.Symbol.Columns]))if(O.primary)G[J].primaryKey.push(O);let W=A[y.Symbol.ExtraConfigBuilder]?.(A[y.Symbol.ExtraConfigColumns]);if(W){for(let O of Object.values(W))if(b(O,sD))G[J].primaryKey.push(...O.columns)}}else if(b(A,A7)){let D=UE(A.table),N=E[D],W=A.config(w(A.table)),O;for(let[Y,H]of Object.entries(W))if(N){let L=G[N];if(L.relations[Y]=H,O)L.primaryKey.push(...O)}else{if(!(D in X))X[D]={relations:{},primaryKey:O};X[D].relations[Y]=H}}return{tables:G,tableNamesMap:E}}function A2($){return function(E,X){return new gw($,E,X,X?.fields.reduce((G,J)=>G&&J.notNull,!0)??!1)}}function D2($){return function(E,X){return new TG($,E,X)}}function O7($,w,E){if(b(E,gw)&&E.config)return{fields:E.config.fields,references:E.config.references};let X=w[UE(E.referencedTable)];if(!X)throw Error(`Table "${E.referencedTable[y.Symbol.Name]}" not found in schema`);let G=$[X];if(!G)throw Error(`Table "${X}" not found in schema`);let J=E.sourceTable,A=w[UE(J)];if(!A)throw Error(`Table "${J[y.Symbol.Name]}" not found in schema`);let D=[];for(let N of Object.values(G.relations))if(E.relationName&&E!==N&&N.relationName===E.relationName||!E.relationName&&N.referencedTable===E.sourceTable)D.push(N);if(D.length>1)throw E.relationName?Error(`There are multiple relations with name "${E.relationName}" in table "${X}"`):Error(`There are multiple relations between "${X}" and "${E.sourceTable[y.Symbol.Name]}". Please specify relation name`);if(D[0]&&b(D[0],gw)&&D[0].config)return{fields:D[0].config.references,references:D[0].config.fields};throw Error(`There is not enough information to infer relation "${A}.${E.fieldName}"`)}function U7($){return{one:A2($),many:D2($)}}function kJ($,w,E,X,G=(J)=>J){let J={};for(let[A,D]of X.entries())if(D.isJson){let N=w.relations[D.tsKey],W=E[A],O=typeof W==="string"?JSON.parse(W):W;J[D.tsKey]=b(N,gw)?O&&kJ($,$[D.relationTableTsKey],O,D.selection,G):O.map((Y)=>kJ($,$[D.relationTableTsKey],Y,D.selection,G))}else{let N=G(E[A]),W=D.field,O;if(b(W,V0))O=W;else if(b(W,h))O=W.decoder;else O=W.sql.decoder;J[D.tsKey]=N===null?null:O.mapFromDriverValue(N)}return J}var aD,A7,gw,TG;var BG=R(()=>{_$();b1();E0();hU();SJ();q$();aD=class aD{constructor($,w,E){this.sourceTable=$,this.referencedTable=w,this.relationName=E,this.referencedTableName=w[y.Symbol.Name]}static[K]="Relation";referencedTableName;fieldName};A7=class A7{constructor($,w){this.table=$,this.config=w}static[K]="Relations"};gw=class gw extends aD{constructor($,w,E,X){super($,w,E?.relationName);this.config=E,this.isNullable=X}static[K]="One";withFieldName($){let w=new gw(this.sourceTable,this.referencedTable,this.config,this.isNullable);return w.fieldName=$,w}};TG=class TG extends aD{constructor($,w,E){super($,w,E?.relationName);this.config=E}static[K]="Many";withFieldName($){let w=new TG(this.sourceTable,this.referencedTable,this.config);return w.fieldName=$,w}}});function bJ($,w){return new Proxy($,new QG(w,!1))}function s1($,w){return new Proxy($,new sE(new Proxy($.table,new QG(w,!1))))}function eD($,w){return new h.Aliased(IG($.sql,w),$.fieldAlias)}function IG($,w){return T.join($.queryChunks.map((E)=>{if(b(E,V0))return s1(E,w);if(b(E,h))return IG(E,w);if(b(E,h.Aliased))return eD(E,w);return E}))}var sE,QG;var ZJ=R(()=>{b1();E0();q$();_$();Lw();sE=class sE{constructor($){this.table=$}static[K]="ColumnAliasProxyHandler";get($,w){if(w==="table")return this.table;return $[w]}};QG=class QG{constructor($,w){this.alias=$,this.replaceOriginalName=w}static[K]="TableAliasProxyHandler";get($,w){if(w===y.Symbol.IsAlias)return!0;if(w===y.Symbol.Name)return this.alias;if(this.replaceOriginalName&&w===y.Symbol.OriginalName)return this.alias;if(w===s0)return{...$[s0],name:this.alias,isAlias:!0};if(w===y.Symbol.Columns){let X=$[y.Symbol.Columns];if(!X)return X;let G={};return Object.keys(X).map((J)=>{G[J]=new Proxy(X[J],new sE(new Proxy($,this)))}),G}let E=$[w];if(b(E,V0))return new Proxy(E,new sE(new Proxy($,this)));return E}}});var A$;var aE=R(()=>{ZJ();b1();E0();q$();d1();Lw();A$=class A${static[K]="SelectionProxyHandler";config;constructor($){this.config={...$}}get($,w){if(w==="_")return{...$._,selectedFields:new Proxy($._.selectedFields,this)};if(w===s0)return{...$[s0],selectedFields:new Proxy($[s0].selectedFields,this)};if(typeof w==="symbol")return $[w];let X=(b($,Y$)?$._.selectedFields:b($,U1)?$[s0].selectedFields:$)[w];if(b(X,h.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!X.isSelectionField)return X.sql;let G=X.clone();return G.isSelectionField=!0,G}if(b(X,h)){if(this.config.sqlBehavior==="sql")return X;throw Error(`You tried to reference "${w}" 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(b(X,V0)){if(this.config.alias)return new Proxy(X,new sE(new Proxy(X.table,new QG(this.config.alias,this.config.replaceOriginalName??!1))));return X}if(typeof X!=="object"||X===null)return X;return new Proxy(X,new A$(this.config))}}});var v$;var Fw=R(()=>{E0();v$=class v${static[K]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch($){return this.then(void 0,$)}finally($){return this.then((w)=>{return $?.(),w},(w)=>{throw $?.(),w})}then($,w){return this.execute().then($,w)}}});var $8,Y7;var w8=R(()=>{E0();LG();$8=class $8{static[K]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor($,w){if(this.reference=()=>{let{name:E,columns:X,foreignColumns:G}=$();return{name:E,columns:X,foreignTable:G[0].table,foreignColumns:G}},w)this._onUpdate=w.onUpdate,this._onDelete=w.onDelete}onUpdate($){return this._onUpdate=$,this}onDelete($){return this._onDelete=$,this}build($){return new Y7($,this)}};Y7=class Y7{constructor($,w){this.table=$,this.reference=w.reference,this.onUpdate=w._onUpdate,this.onDelete=w._onDelete}static[K]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:$,columns:w,foreignColumns:E}=this.reference(),X=w.map((A)=>A.name),G=E.map((A)=>A.name),J=[this.table[G1],...X,E[0].table[G1],...G];return $??`${J.join("_")}_fk`}}});function H7($,w){return`${$[G1]}_${w.join("_")}_unique`}var E8=R(()=>{LG()});var H$,w$;var uw=R(()=>{pD();b1();E0();w8();E8();H$=class H$ extends rD{static[K]="SQLiteColumnBuilder";foreignKeyConfigs=[];references($,w={}){return this.foreignKeyConfigs.push({ref:$,actions:w}),this}unique($){return this.config.isUnique=!0,this.config.uniqueName=$,this}generatedAlwaysAs($,w){return this.config.generated={as:$,type:"always",mode:w?.mode??"virtual"},this}buildForeignKeys($,w){return this.foreignKeyConfigs.map(({ref:E,actions:X})=>{return((G,J)=>{let A=new $8(()=>{let D=G();return{columns:[$],foreignColumns:[D]}});if(J.onUpdate)A.onUpdate(J.onUpdate);if(J.onDelete)A.onDelete(J.onDelete);return A.build(w)})(E,X)})}};w$=class w$ extends V0{constructor($,w){if(!w.uniqueName)w.uniqueName=H7($,[w.name]);super($,w);this.table=$}static[K]="SQLiteColumn"}});function T7($,w){let{name:E,config:X}=l1($,w);if(X?.mode==="json")return new j7(E);if(X?.mode==="bigint")return new L7(E);return new R7(E)}var L7,F7,j7,M7,R7,z7;var X8=R(()=>{E0();o$();uw();L7=class L7 extends H${static[K]="SQLiteBigIntBuilder";constructor($){super($,"bigint","SQLiteBigInt")}build($){return new F7($,this.config)}};F7=class F7 extends w${static[K]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue($){if(Buffer.isBuffer($))return BigInt($.toString());if($ instanceof ArrayBuffer)return BigInt(new TextDecoder().decode($));return BigInt(String.fromCodePoint(...$))}mapToDriverValue($){return Buffer.from($.toString())}};j7=class j7 extends H${static[K]="SQLiteBlobJsonBuilder";constructor($){super($,"json","SQLiteBlobJson")}build($){return new M7($,this.config)}};M7=class M7 extends w${static[K]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue($){if(Buffer.isBuffer($))return JSON.parse($.toString());if($ instanceof ArrayBuffer)return JSON.parse(new TextDecoder().decode($));return JSON.parse(String.fromCodePoint(...$))}mapToDriverValue($){return Buffer.from(JSON.stringify($))}};R7=class R7 extends H${static[K]="SQLiteBlobBufferBuilder";constructor($){super($,"buffer","SQLiteBlobBuffer")}build($){return new z7($,this.config)}};z7=class z7 extends w${static[K]="SQLiteBlobBuffer";mapFromDriverValue($){if(Buffer.isBuffer($))return $;return Buffer.from($)}getSQLType(){return"blob"}}});function I7($){return(w,E)=>{let{name:X,config:G}=l1(w,E);return new B7(X,G,$)}}var B7,Q7;var G8=R(()=>{E0();o$();uw();B7=class B7 extends H${static[K]="SQLiteCustomColumnBuilder";constructor($,w,E){super($,"custom","SQLiteCustomColumn");this.config.fieldConfig=w,this.config.customTypeParams=E}build($){return new Q7($,this.config)}};Q7=class Q7 extends w${static[K]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;constructor($,w){super($,w);this.sqlName=w.customTypeParams.dataType(w.fieldConfig),this.mapTo=w.customTypeParams.toDriver,this.mapFrom=w.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue($){return typeof this.mapFrom==="function"?this.mapFrom($):$}mapToDriverValue($){return typeof this.mapTo==="function"?this.mapTo($):$}}});function s($,w){let{name:E,config:X}=l1($,w);if(X?.mode==="timestamp"||X?.mode==="timestamp_ms")return new P7(E,X.mode);if(X?.mode==="boolean")return new S7(E,X.mode);return new K7(E)}var CJ,_J,K7,V7,P7,q7,S7,k7;var J8=R(()=>{E0();q$();o$();uw();CJ=class CJ extends H${static[K]="SQLiteBaseIntegerBuilder";constructor($,w,E){super($,w,E);this.config.autoIncrement=!1}primaryKey($){if($?.autoIncrement)this.config.autoIncrement=!0;return this.config.hasDefault=!0,super.primaryKey()}};_J=class _J extends w${static[K]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}};K7=class K7 extends CJ{static[K]="SQLiteIntegerBuilder";constructor($){super($,"number","SQLiteInteger")}build($){return new V7($,this.config)}};V7=class V7 extends _J{static[K]="SQLiteInteger"};P7=class P7 extends CJ{static[K]="SQLiteTimestampBuilder";constructor($,w){super($,"date","SQLiteTimestamp");this.config.mode=w}defaultNow(){return this.default(T`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build($){return new q7($,this.config)}};q7=class q7 extends _J{static[K]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue($){if(this.config.mode==="timestamp")return new Date($*1000);return new Date($)}mapToDriverValue($){let w=$.getTime();if(this.config.mode==="timestamp")return Math.floor(w/1000);return w}};S7=class S7 extends CJ{static[K]="SQLiteBooleanBuilder";constructor($,w){super($,"boolean","SQLiteBoolean");this.config.mode=w}build($){return new k7($,this.config)}};k7=class k7 extends _J{static[K]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue($){return Number($)===1}mapToDriverValue($){return $?1:0}}});function x7($,w){let{name:E,config:X}=l1($,w),G=X?.mode;return G==="number"?new C7(E):G==="bigint"?new v7(E):new b7(E)}var b7,Z7,C7,_7,v7,f7;var A8=R(()=>{E0();o$();uw();b7=class b7 extends H${static[K]="SQLiteNumericBuilder";constructor($){super($,"string","SQLiteNumeric")}build($){return new Z7($,this.config)}};Z7=class Z7 extends w${static[K]="SQLiteNumeric";mapFromDriverValue($){if(typeof $==="string")return $;return String($)}getSQLType(){return"numeric"}};C7=class C7 extends H${static[K]="SQLiteNumericNumberBuilder";constructor($){super($,"number","SQLiteNumericNumber")}build($){return new _7($,this.config)}};_7=class _7 extends w${static[K]="SQLiteNumericNumber";mapFromDriverValue($){if(typeof $==="number")return $;return Number($)}mapToDriverValue=String;getSQLType(){return"numeric"}};v7=class v7 extends H${static[K]="SQLiteNumericBigIntBuilder";constructor($){super($,"bigint","SQLiteNumericBigInt")}build($){return new f7($,this.config)}};f7=class f7 extends w${static[K]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}});function u7($){return new y7($??"")}var y7,g7;var D8=R(()=>{E0();uw();y7=class y7 extends H${static[K]="SQLiteRealBuilder";constructor($){super($,"number","SQLiteReal")}build($){return new g7($,this.config)}};g7=class g7 extends w${static[K]="SQLiteReal";getSQLType(){return"real"}}});function q($,w={}){let{name:E,config:X}=l1($,w);if(X.mode==="json")return new n7(E);return new h7(E,X)}var h7,c7,n7,m7;var N8=R(()=>{E0();o$();uw();h7=class h7 extends H${static[K]="SQLiteTextBuilder";constructor($,w){super($,"string","SQLiteText");this.config.enumValues=w.enum,this.config.length=w.length}build($){return new c7($,this.config)}};c7=class c7 extends w${static[K]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor($,w){super($,w)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}};n7=class n7 extends H${static[K]="SQLiteTextJsonBuilder";constructor($){super($,"json","SQLiteTextJson")}build($){return new m7($,this.config)}};m7=class m7 extends w${static[K]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue($){return JSON.parse($)}mapToDriverValue($){return JSON.stringify($)}}});function r7(){return{blob:T7,customType:I7,integer:s,numeric:x7,real:u7,text:q}}var p7=R(()=>{X8();G8();J8();A8();D8();N8()});function N2($,w,E,X,G=$){let J=new S$($,X,G),A=typeof w==="function"?w(r7()):w,D=Object.fromEntries(Object.entries(A).map(([W,O])=>{let Y=O;Y.setName(W);let H=Y.build(J);return J[W8].push(...Y.buildForeignKeys(H,J)),[W,H]})),N=Object.assign(J,D);if(N[y.Symbol.Columns]=D,N[y.Symbol.ExtraConfigColumns]=D,E)N[S$.Symbol.ExtraConfigBuilder]=E;return N}var W8,S$,M$=($,w,E)=>{return N2($,w,E)};var eE=R(()=>{E0();_$();p7();W8=Symbol.for("drizzle:SQLiteInlineForeignKeys");S$=class S$ extends y{static[K]="SQLiteTable";static Symbol=Object.assign({},y.Symbol,{InlineForeignKeys:W8});[y.Symbol.Columns];[W8]=[];[y.Symbol.ExtraConfigBuilder]=void 0}});var vJ;var o7=R(()=>{E0();Fw();aE();eE();_$();o$();vJ=class vJ extends v${constructor($,w,E,X){super();this.table=$,this.session=w,this.dialect=E,this.config={table:$,withList:X}}static[K]="SQLiteDelete";config;where($){return this.config.where=$,this}orderBy(...$){if(typeof $[0]==="function"){let w=$[0](new Proxy(this.config.table[y.Symbol.Columns],new A$({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),E=Array.isArray(w)?w:[w];this.config.orderBy=E}else{let w=$;this.config.orderBy=w}return this}limit($){return this.config.limit=$,this}returning($=this.table[S$.Symbol.Columns]){return this.config.returning=Y1($),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:$,...w}=this.dialect.sqlToQuery(this.getSQL());return w}_prepare($=!0){return this.session[$?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0)}prepare(){return this._prepare(!1)}run=($)=>{return this._prepare().run($)};all=($)=>{return this._prepare().all($)};get=($)=>{return this._prepare().get($)};values=($)=>{return this._prepare().values($)};async execute($){return this._prepare().execute($)}$dynamic(){return this}}});function W2($){return($.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((E)=>E.toLowerCase()).join("_")}function O2($){return($.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((E,X,G)=>{let J=G===0?X.toLowerCase():`${X[0].toUpperCase()}${X.slice(1)}`;return E+J},"")}function U2($){return $}var O8;var t7=R(()=>{E0();_$();O8=class O8{static[K]="CasingCache";cache={};cachedTables={};convert;constructor($){this.convert=$==="snake_case"?W2:$==="camelCase"?O2:U2}getColumnCasing($){if(!$.keyAsName)return $.name;let w=$.table[y.Symbol.Schema]??"public",E=$.table[y.Symbol.OriginalName],X=`${w}.${E}.${$.name}`;if(!this.cache[X])this.cacheTable($.table);return this.cache[X]}cacheTable($){let w=$[y.Symbol.Schema]??"public",E=$[y.Symbol.OriginalName],X=`${w}.${E}`;if(!this.cachedTables[X]){for(let G of Object.values($[y.Symbol.Columns])){let J=`${X}.${G.name}`;this.cache[J]=this.convert(G.name)}this.cachedTables[X]=!0}}clearCache(){this.cache={},this.cachedTables={}}}});var $X,U8;var fJ=R(()=>{E0();$X=class $X extends Error{static[K]="DrizzleError";constructor({message:$,cause:w}){super($);this.name="DrizzleError",this.cause=w}};U8=class U8 extends $X{static[K]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}});var i7=()=>{};var d7=()=>{};var l7=R(()=>{i7();d7()});var Y8=R(()=>{SJ();l7();q$()});var H8=R(()=>{X8();uw();G8();J8();A8();D8();N8()});var YE;var xJ=R(()=>{E0();q$();YE=class YE extends U1{static[K]="SQLiteViewBase"}});var KG,VG;var yJ=R(()=>{ZJ();t7();b1();E0();fJ();BG();Y8();q$();H8();eE();d1();_$();o$();Lw();xJ();KG=class KG{static[K]="SQLiteDialect";casing;constructor($){this.casing=new O8($?.casing)}escapeName($){return`"${$}"`}escapeParam($){return"?"}escapeString($){return`'${$.replace(/'/g,"''")}'`}buildWithCTE($){if(!$?.length)return;let w=[T`with `];for(let[E,X]of $.entries())if(w.push(T`${T.identifier(X._.alias)} as (${X._.sql})`),E<$.length-1)w.push(T`, `);return w.push(T` `),T.join(w)}buildDeleteQuery({table:$,where:w,returning:E,withList:X,limit:G,orderBy:J}){let A=this.buildWithCTE(X),D=E?T` returning ${this.buildSelection(E,{isSingleTable:!0})}`:void 0,N=w?T` where ${w}`:void 0,W=this.buildOrderBy(J),O=this.buildLimit(G);return T`${A}delete from ${$}${N}${D}${W}${O}`}buildUpdateSet($,w){let E=$[y.Symbol.Columns],X=Object.keys(E).filter((J)=>w[J]!==void 0||E[J]?.onUpdateFn!==void 0),G=X.length;return T.join(X.flatMap((J,A)=>{let D=E[J],N=w[J]??T.param(D.onUpdateFn(),D),W=T`${T.identifier(this.casing.getColumnCasing(D))} = ${N}`;if(A<G-1)return[W,T.raw(", ")];return[W]}))}buildUpdateQuery({table:$,set:w,where:E,returning:X,withList:G,joins:J,from:A,limit:D,orderBy:N}){let W=this.buildWithCTE(G),O=this.buildUpdateSet($,w),Y=A&&T.join([T.raw(" from "),this.buildFromTable(A)]),H=this.buildJoins(J),L=X?T` returning ${this.buildSelection(X,{isSingleTable:!0})}`:void 0,F=E?T` where ${E}`:void 0,j=this.buildOrderBy(N),M=this.buildLimit(D);return T`${W}update ${$} set ${O}${Y}${H}${F}${L}${j}${M}`}buildSelection($,{isSingleTable:w=!1}={}){let E=$.length,X=$.flatMap(({field:G},J)=>{let A=[];if(b(G,h.Aliased)&&G.isSelectionField)A.push(T.identifier(G.fieldAlias));else if(b(G,h.Aliased)||b(G,h)){let D=b(G,h.Aliased)?G.sql:G;if(w)A.push(new h(D.queryChunks.map((N)=>{if(b(N,V0))return T.identifier(this.casing.getColumnCasing(N));return N})));else A.push(D);if(b(G,h.Aliased))A.push(T` as ${T.identifier(G.fieldAlias)}`)}else if(b(G,V0)){let D=G.table[y.Symbol.Name];if(G.columnType==="SQLiteNumericBigInt")if(w)A.push(T`cast(${T.identifier(this.casing.getColumnCasing(G))} as text)`);else A.push(T`cast(${T.identifier(D)}.${T.identifier(this.casing.getColumnCasing(G))} as text)`);else if(w)A.push(T.identifier(this.casing.getColumnCasing(G)));else A.push(T`${T.identifier(D)}.${T.identifier(this.casing.getColumnCasing(G))}`)}if(J<E-1)A.push(T`, `);return A});return T.join(X)}buildJoins($){if(!$||$.length===0)return;let w=[];if($)for(let[E,X]of $.entries()){if(E===0)w.push(T` `);let G=X.table;if(b(G,S$)){let J=G[S$.Symbol.Name],A=G[S$.Symbol.Schema],D=G[S$.Symbol.OriginalName],N=J===D?void 0:X.alias;w.push(T`${T.raw(X.joinType)} join ${A?T`${T.identifier(A)}.`:void 0}${T.identifier(D)}${N&&T` ${T.identifier(N)}`} on ${X.on}`)}else w.push(T`${T.raw(X.joinType)} join ${G} on ${X.on}`);if(E<$.length-1)w.push(T` `)}return T.join(w)}buildLimit($){return typeof $==="object"||typeof $==="number"&&$>=0?T` limit ${$}`:void 0}buildOrderBy($){let w=[];if($){for(let[E,X]of $.entries())if(w.push(X),E<$.length-1)w.push(T`, `)}return w.length>0?T` order by ${T.join(w)}`:void 0}buildFromTable($){if(b($,y)&&$[y.Symbol.IsAlias])return T`${T`${T.identifier($[y.Symbol.Schema]??"")}.`.if($[y.Symbol.Schema])}${T.identifier($[y.Symbol.OriginalName])} ${T.identifier($[y.Symbol.Name])}`;return $}buildSelectQuery({withList:$,fields:w,fieldsFlat:E,where:X,having:G,table:J,joins:A,orderBy:D,groupBy:N,limit:W,offset:O,distinct:Y,setOperators:H}){let L=E??Y1(w);for(let K0 of L)if(b(K0.field,V0)&&xw(K0.field.table)!==(b(J,Y$)?J._.alias:b(J,YE)?J[s0].name:b(J,h)?void 0:xw(J))&&!((U$)=>A?.some(({alias:O1})=>O1===(U$[y.Symbol.IsAlias]?xw(U$):U$[y.Symbol.BaseName])))(K0.field.table)){let U$=xw(K0.field.table);throw Error(`Your "${K0.path.join("->")}" field references a column "${U$}"."${K0.field.name}", but the table "${U$}" is not part of the query! Did you forget to join it?`)}let F=!A||A.length===0,j=this.buildWithCTE($),M=Y?T` distinct`:void 0,z=this.buildSelection(L,{isSingleTable:F}),B=this.buildFromTable(J),Q=this.buildJoins(A),k=X?T` where ${X}`:void 0,v=G?T` having ${G}`:void 0,C=[];if(N){for(let[K0,U$]of N.entries())if(C.push(U$),K0<N.length-1)C.push(T`, `)}let n=C.length>0?T` group by ${T.join(C)}`:void 0,T0=this.buildOrderBy(D),f0=this.buildLimit(W),c0=O?T` offset ${O}`:void 0,d0=T`${j}select${M} ${z} from ${B}${Q}${k}${n}${v}${T0}${f0}${c0}`;if(H.length>0)return this.buildSetOperations(d0,H);return d0}buildSetOperations($,w){let[E,...X]=w;if(!E)throw Error("Cannot pass undefined values to any set operator");if(X.length===0)return this.buildSetOperationQuery({leftSelect:$,setOperator:E});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:$,setOperator:E}),X)}buildSetOperationQuery({leftSelect:$,setOperator:{type:w,isAll:E,rightSelect:X,limit:G,orderBy:J,offset:A}}){let D=T`${$.getSQL()} `,N=T`${X.getSQL()}`,W;if(J&&J.length>0){let L=[];for(let F of J)if(b(F,w$))L.push(T.identifier(F.name));else if(b(F,h)){for(let j=0;j<F.queryChunks.length;j++){let M=F.queryChunks[j];if(b(M,w$))F.queryChunks[j]=T.identifier(this.casing.getColumnCasing(M))}L.push(T`${F}`)}else L.push(T`${F}`);W=T` order by ${T.join(L,T`, `)}`}let O=typeof G==="object"||typeof G==="number"&&G>=0?T` limit ${G}`:void 0,Y=T.raw(`${w} ${E?"all ":""}`),H=A?T` offset ${A}`:void 0;return T`${D}${Y}${N}${W}${O}${H}`}buildInsertQuery({table:$,values:w,onConflict:E,returning:X,withList:G,select:J}){let A=[],D=$[y.Symbol.Columns],N=Object.entries(D).filter(([F,j])=>!j.shouldDisableInsert()),W=N.map(([,F])=>T.identifier(this.casing.getColumnCasing(F)));if(J){let F=w;if(b(F,h))A.push(F);else A.push(F.getSQL())}else{let F=w;A.push(T.raw("values "));for(let[j,M]of F.entries()){let z=[];for(let[B,Q]of N){let k=M[B];if(k===void 0||b(k,J1)&&k.value===void 0){let v;if(Q.default!==null&&Q.default!==void 0)v=b(Q.default,h)?Q.default:T.param(Q.default,Q);else if(Q.defaultFn!==void 0){let C=Q.defaultFn();v=b(C,h)?C:T.param(C,Q)}else if(!Q.default&&Q.onUpdateFn!==void 0){let C=Q.onUpdateFn();v=b(C,h)?C:T.param(C,Q)}else v=T`null`;z.push(v)}else z.push(k)}if(A.push(z),j<F.length-1)A.push(T`, `)}}let O=this.buildWithCTE(G),Y=T.join(A),H=X?T` returning ${this.buildSelection(X,{isSingleTable:!0})}`:void 0,L=E?.length?T.join(E):void 0;return T`${O}insert into ${$} ${W} ${Y}${L}${H}`}sqlToQuery($,w){return $.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,invokeSource:w})}buildRelationalQuery({fullSchema:$,schema:w,tableNamesMap:E,table:X,tableConfig:G,queryConfig:J,tableAlias:A,nestedQueryRelation:D,joinOn:N}){let W=[],O,Y,H=[],L,F=[];if(J===!0)W=Object.entries(G.columns).map(([z,B])=>({dbKey:B.name,tsKey:z,field:s1(B,A),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let M=Object.fromEntries(Object.entries(G.columns).map(([C,n])=>[C,s1(n,A)]));if(J.where){let C=typeof J.where==="function"?J.where(M,D7()):J.where;L=C&&IG(C,A)}let z=[],B=[];if(J.columns){let C=!1;for(let[n,T0]of Object.entries(J.columns)){if(T0===void 0)continue;if(n in G.columns){if(!C&&T0===!0)C=!0;B.push(n)}}if(B.length>0)B=C?B.filter((n)=>J.columns?.[n]===!0):Object.keys(G.columns).filter((n)=>!B.includes(n))}else B=Object.keys(G.columns);for(let C of B){let n=G.columns[C];z.push({tsKey:C,value:n})}let Q=[];if(J.with)Q=Object.entries(J.with).filter((C)=>!!C[1]).map(([C,n])=>({tsKey:C,queryConfig:n,relation:G.relations[C]}));let k;if(J.extras){k=typeof J.extras==="function"?J.extras(M,{sql:T}):J.extras;for(let[C,n]of Object.entries(k))z.push({tsKey:C,value:eD(n,A)})}for(let{tsKey:C,value:n}of z)W.push({dbKey:b(n,h.Aliased)?n.fieldAlias:G.columns[C].name,tsKey:C,field:b(n,V0)?s1(n,A):n,relationTableTsKey:void 0,isJson:!1,selection:[]});let v=typeof J.orderBy==="function"?J.orderBy(M,N7()):J.orderBy??[];if(!Array.isArray(v))v=[v];H=v.map((C)=>{if(b(C,V0))return s1(C,A);return IG(C,A)}),O=J.limit,Y=J.offset;for(let{tsKey:C,queryConfig:n,relation:T0}of Q){let f0=O7(w,E,T0),c0=UE(T0.referencedTable),d0=E[c0],K0=`${A}_${C}`,U$=S0(...f0.fields.map((SV,kV)=>V(s1(f0.references[kV],K0),s1(SV,A)))),O1=this.buildRelationalQuery({fullSchema:$,schema:w,tableNamesMap:E,table:$[d0],tableConfig:w[d0],queryConfig:b(T0,gw)?n===!0?{limit:1}:{...n,limit:1}:n,tableAlias:K0,joinOn:U$,nestedQueryRelation:T0}),qV=T`(${O1.sql})`.as(C);W.push({dbKey:C,tsKey:C,field:qV,relationTableTsKey:d0,isJson:!0,selection:O1.selection})}}if(W.length===0)throw new $X({message:`No fields selected for table "${G.tsName}" ("${A}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.`});let j;if(L=S0(N,L),D){let M=T`json_array(${T.join(W.map(({field:Q})=>b(Q,w$)?T.identifier(this.casing.getColumnCasing(Q)):b(Q,h.Aliased)?Q.sql:Q),T`, `)})`;if(b(D,TG))M=T`coalesce(json_group_array(${M}), json_array())`;let z=[{dbKey:"data",tsKey:"data",field:M.as("data"),isJson:!0,relationTableTsKey:G.tsName,selection:W}];if(O!==void 0||Y!==void 0||H.length>0)j=this.buildSelectQuery({table:bJ(X,A),fields:{},fieldsFlat:[{path:[],field:T.raw("*")}],where:L,limit:O,offset:Y,orderBy:H,setOperators:[]}),L=void 0,O=void 0,Y=void 0,H=void 0;else j=bJ(X,A);j=this.buildSelectQuery({table:b(j,S$)?j:new Y$(j,{},A),fields:{},fieldsFlat:z.map(({field:Q})=>({path:[],field:b(Q,V0)?s1(Q,A):Q})),joins:F,where:L,limit:O,offset:Y,orderBy:H,setOperators:[]})}else j=this.buildSelectQuery({table:bJ(X,A),fields:{},fieldsFlat:W.map(({field:M})=>({path:[],field:b(M,V0)?s1(M,A):M})),joins:F,where:L,limit:O,offset:Y,orderBy:H,setOperators:[]});return{tableTsKey:G.tsName,sql:j,selection:W}}};VG=class VG extends KG{static[K]="SQLiteSyncDialect";migrate($,w,E){let X=E===void 0?"__drizzle_migrations":typeof E==="string"?"__drizzle_migrations":E.migrationsTable??"__drizzle_migrations",G=T`
|
|
30
30
|
CREATE TABLE IF NOT EXISTS ${T.identifier(X)} (
|
|
31
31
|
id SERIAL PRIMARY KEY,
|
|
32
32
|
hash text NOT NULL,
|
|
33
33
|
created_at numeric
|
|
34
34
|
)
|
|
35
|
-
`;w.run(G);let A=w.values(T`SELECT id, hash, created_at FROM ${T.identifier(X)} ORDER BY created_at DESC LIMIT 1`)[0]??void 0;w.run(T`BEGIN`);try{for(let D of $)if(!A||Number(A[2])<D.folderMillis){for(let N of D.sql)w.run(T.raw(N));w.run(T`INSERT INTO ${T.identifier(X)} ("hash", "created_at") VALUES(${D.hash}, ${D.folderMillis})`)}w.run(T`COMMIT`)}catch(D){throw w.run(T`ROLLBACK`),D}}}});var U8;var i7=R(()=>{E0();U8=class U8{static[K]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}});function xJ($,w){return(E,X,...G)=>{let J=[X,...G].map((A)=>({type:$,isAll:w,rightSelect:A}));for(let A of J)if(!MG(E.getSelectedFields(),A.rightSelect.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return E.addSetOperators(J)}}var Z1,d7,Y8,J2=()=>({union:A2,unionAll:D2,intersect:N2,except:W2}),A2,D2,N2,W2;var H8=R(()=>{E0();i7();Fw();sE();q$();d1();_$();o$();Lw();vJ();Z1=class Z1{static[K]="SQLiteSelectBuilder";fields;session;dialect;withList;distinct;constructor($){this.fields=$.fields,this.session=$.session,this.dialect=$.dialect,this.withList=$.withList,this.distinct=$.distinct}from($){let w=!!this.fields,E;if(this.fields)E=this.fields;else if(b($,Y$))E=Object.fromEntries(Object.keys($._.selectedFields).map((X)=>[X,$[X]]));else if(b($,YE))E=$[s0].selectedFields;else if(b($,h))E={};else E=ZU($);return new Y8({table:$,fields:E,isPartialSelect:w,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}};d7=class d7 extends U8{static[K]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:$,fields:w,isPartialSelect:E,session:X,dialect:G,withList:J,distinct:A}){super();this.config={withList:J,table:$,fields:{...w},distinct:A,setOperators:[]},this.isPartialSelect=E,this.session=X,this.dialect=G,this._={selectedFields:w},this.tableName=RG($),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin($){return(w,E)=>{let X=this.tableName,G=RG(w);if(typeof G==="string"&&this.config.joins?.some((J)=>J.alias===G))throw Error(`Alias "${G}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof X==="string")this.config.fields={[X]:this.config.fields};if(typeof G==="string"&&!b(w,h)){let J=b(w,Y$)?w._.selectedFields:b(w,U1)?w[s0].selectedFields:w[y.Symbol.Columns];this.config.fields[G]=J}}if(typeof E==="function")E=E(new Proxy(this.config.fields,new A$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:E,table:w,joinType:$,alias:G}),typeof G==="string")switch($){case"left":{this.joinsNotNullableMap[G]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[G]=!0;break}case"inner":{this.joinsNotNullableMap[G]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[G]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");createSetOperator($,w){return(E)=>{let X=typeof E==="function"?E(J2()):E;if(!MG(this.getSelectedFields(),X.getSelectedFields()))throw 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:$,isAll:w,rightSelect:X}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);except=this.createSetOperator("except",!1);addSetOperators($){return this.config.setOperators.push(...$),this}where($){if(typeof $==="function")$=$(new Proxy(this.config.fields,new A$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=$,this}having($){if(typeof $==="function")$=$(new Proxy(this.config.fields,new A$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=$,this}groupBy(...$){if(typeof $[0]==="function"){let w=$[0](new Proxy(this.config.fields,new A$({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(w)?w:[w]}else this.config.groupBy=$;return this}orderBy(...$){if(typeof $[0]==="function"){let w=$[0](new Proxy(this.config.fields,new A$({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),E=Array.isArray(w)?w:[w];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=E;else this.config.orderBy=E}else{let w=$;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=w;else this.config.orderBy=w}return this}limit($){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=$;else this.config.limit=$;return this}offset($){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=$;else this.config.offset=$;return this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:$,...w}=this.dialect.sqlToQuery(this.getSQL());return w}as($){return new Proxy(new Y$(this.getSQL(),this.config.fields,$),new A$({alias:$,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new A$({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}};Y8=class Y8 extends d7{static[K]="SQLiteSelect";_prepare($=!0){if(!this.session)throw Error("Cannot execute a query on a query builder. Please use a database instance instead.");let w=Y1(this.config.fields),E=this.session[$?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),w,"all",!0);return E.joinsNotNullableMap=this.joinsNotNullableMap,E}prepare(){return this._prepare(!1)}run=($)=>{return this._prepare().run($)};all=($)=>{return this._prepare().all($)};get=($)=>{return this._prepare().get($)};values=($)=>{return this._prepare().values($)};async execute(){return this.all()}};bU(Y8,[v$]);A2=xJ("union",!1),D2=xJ("union",!0),N2=xJ("intersect",!1),W2=xJ("except",!1)});var VG;var L8=R(()=>{E0();sE();fJ();d1();H8();VG=class VG{static[K]="SQLiteQueryBuilder";dialect;dialectConfig;constructor($){this.dialect=b($,IG)?$:void 0,this.dialectConfig=b($,IG)?void 0:$}$with=($,w)=>{let E=this;return{as:(G)=>{if(typeof G==="function")G=G(E);return new Proxy(new FG(G.getSQL(),w??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),$,!0),new A$({alias:$,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...$){let w=this;function E(G){return new Z1({fields:G??void 0,session:void 0,dialect:w.getDialect(),withList:$})}function X(G){return new Z1({fields:G??void 0,session:void 0,dialect:w.getDialect(),withList:$,distinct:!0})}return{select:E,selectDistinct:X}}select($){return new Z1({fields:$??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct($){return new Z1({fields:$??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new KG(this.dialectConfig);return this.dialect}}});var yJ,F8;var l7=R(()=>{E0();Fw();q$();aE();_$();o$();L8();yJ=class yJ{constructor($,w,E,X){this.table=$,this.session=w,this.dialect=E,this.withList=X}static[K]="SQLiteInsertBuilder";values($){if($=Array.isArray($)?$:[$],$.length===0)throw Error("values() must be called with at least one value");let w=$.map((E)=>{let X={},G=this.table[y.Symbol.Columns];for(let J of Object.keys(E)){let A=E[J];X[J]=b(A,h)?A:new J1(A,G[J])}return X});return new F8(this.table,w,this.session,this.dialect,this.withList)}select($){let w=typeof $==="function"?$(new VG):$;if(!b(w,h)&&!MG(this.table[zJ],w._.selectedFields))throw Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new F8(this.table,w,this.session,this.dialect,this.withList,!0)}};F8=class F8 extends v${constructor($,w,E,X,G,J){super();this.session=E,this.dialect=X,this.config={table:$,values:w,withList:G,select:J}}static[K]="SQLiteInsert";config;returning($=this.config.table[S$.Symbol.Columns]){return this.config.returning=Y1($),this}onConflictDoNothing($={}){if(!this.config.onConflict)this.config.onConflict=[];if($.target===void 0)this.config.onConflict.push(T` on conflict do nothing`);else{let w=Array.isArray($.target)?T`${$.target}`:T`${[$.target]}`,E=$.where?T` where ${$.where}`:T``;this.config.onConflict.push(T` on conflict ${w} do nothing${E}`)}return this}onConflictDoUpdate($){if($.where&&($.targetWhere||$.setWhere))throw Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');if(!this.config.onConflict)this.config.onConflict=[];let w=$.where?T` where ${$.where}`:void 0,E=$.targetWhere?T` where ${$.targetWhere}`:void 0,X=$.setWhere?T` where ${$.setWhere}`:void 0,G=Array.isArray($.target)?T`${$.target}`:T`${[$.target]}`,J=this.dialect.buildUpdateSet(this.config.table,QJ(this.config.table,$.set));return this.config.onConflict.push(T` on conflict ${G}${E} do update set ${J}${w}${X}`),this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:$,...w}=this.dialect.sqlToQuery(this.getSQL());return w}_prepare($=!0){return this.session[$?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0)}prepare(){return this._prepare(!1)}run=($)=>{return this._prepare().run($)};all=($)=>{return this._prepare().all($)};get=($)=>{return this._prepare().get($)};values=($)=>{return this._prepare().values($)};async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var gJ,s7;var a7=R(()=>{E0();Fw();sE();aE();d1();_$();o$();Lw();vJ();gJ=class gJ{constructor($,w,E,X){this.table=$,this.session=w,this.dialect=E,this.withList=X}static[K]="SQLiteUpdateBuilder";set($){return new s7(this.table,QJ(this.table,$),this.session,this.dialect,this.withList)}};s7=class s7 extends v${constructor($,w,E,X,G){super();this.session=E,this.dialect=X,this.config={set:w,table:$,withList:G,joins:[]}}static[K]="SQLiteUpdate";config;from($){return this.config.from=$,this}createJoin($){return(w,E)=>{let X=RG(w);if(typeof X==="string"&&this.config.joins.some((G)=>G.alias===X))throw Error(`Alias "${X}" is already used in this query`);if(typeof E==="function"){let G=this.config.from?b(w,S$)?w[y.Symbol.Columns]:b(w,Y$)?w._.selectedFields:b(w,YE)?w[s0].selectedFields:void 0:void 0;E=E(new Proxy(this.config.table[y.Symbol.Columns],new A$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),G&&new Proxy(G,new A$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:E,table:w,joinType:$,alias:X}),this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where($){return this.config.where=$,this}orderBy(...$){if(typeof $[0]==="function"){let w=$[0](new Proxy(this.config.table[y.Symbol.Columns],new A$({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),E=Array.isArray(w)?w:[w];this.config.orderBy=E}else{let w=$;this.config.orderBy=w}return this}limit($){return this.config.limit=$,this}returning($=this.config.table[S$.Symbol.Columns]){return this.config.returning=Y1($),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:$,...w}=this.dialect.sqlToQuery(this.getSQL());return w}_prepare($=!0){return this.session[$?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0)}prepare(){return this._prepare(!1)}run=($)=>{return this._prepare().run($)};all=($)=>{return this._prepare().all($)};get=($)=>{return this._prepare().get($)};values=($)=>{return this._prepare().values($)};async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var j8=R(()=>{m7();l7();L8();H8();a7()});var PG;var e7=R(()=>{E0();q$();PG=class PG extends h{constructor($){super(PG.buildEmbeddedCount($.source,$.filters).queryChunks);this.params=$,this.session=$.session,this.sql=PG.buildCount($.source,$.filters)}sql;static[K]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount($,w){return T`(select count(*) from ${$}${T.raw(" where ").if(w)}${w})`}static buildCount($,w){return T`select count(*) from ${$}${T.raw(" where ").if(w)}${w}`}then($,w){return Promise.resolve(this.session.count(this.sql)).then($,w)}catch($){return this.then(void 0,$)}finally($){return this.then((w)=>{return $?.(),w},(w)=>{throw $?.(),w})}}});var R8,uJ,M8;var $Y=R(()=>{E0();Fw();TG();R8=class R8{constructor($,w,E,X,G,J,A,D){this.mode=$,this.fullSchema=w,this.schema=E,this.tableNamesMap=X,this.table=G,this.tableConfig=J,this.dialect=A,this.session=D}static[K]="SQLiteAsyncRelationalQueryBuilder";findMany($){return this.mode==="sync"?new M8(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,$?$:{},"many"):new uJ(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,$?$:{},"many")}findFirst($){return this.mode==="sync"?new M8(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,$?{...$,limit:1}:{limit:1},"first"):new uJ(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,$?{...$,limit:1}:{limit:1},"first")}};uJ=class uJ extends v${constructor($,w,E,X,G,J,A,D,N){super();this.fullSchema=$,this.schema=w,this.tableNamesMap=E,this.table=X,this.tableConfig=G,this.dialect=J,this.session=A,this.config=D,this.mode=N}static[K]="SQLiteAsyncRelationalQuery";mode;getSQL(){return this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}).sql}_prepare($=!1){let{query:w,builtQuery:E}=this._toSQL();return this.session[$?"prepareOneTimeQuery":"prepareQuery"](E,void 0,this.mode==="first"?"get":"all",!0,(X,G)=>{let J=X.map((A)=>qJ(this.schema,this.tableConfig,A,w.selection,G));if(this.mode==="first")return J[0];return J})}prepare(){return this._prepare(!1)}_toSQL(){let $=this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}),w=this.dialect.sqlToQuery($.sql);return{query:$,builtQuery:w}}toSQL(){return this._toSQL().builtQuery}executeRaw(){if(this.mode==="first")return this._prepare(!1).get();return this._prepare(!1).all()}async execute(){return this.executeRaw()}};M8=class M8 extends uJ{static[K]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}});var $X;var wY=R(()=>{E0();Fw();$X=class $X extends v${constructor($,w,E,X,G){super();this.execute=$,this.getSQL=w,this.dialect=X,this.mapBatchResult=G,this.config={action:E}}static[K]="SQLiteRaw";config;getQuery(){return{...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult($,w){return w?this.mapBatchResult($):$}_prepare(){return this}isResponseInArrayMode(){return!1}}});var qG;var hJ=R(()=>{E0();sE();q$();j8();d1();e7();$Y();wY();qG=class qG{constructor($,w,E,X){this.resultKind=$,this.dialect=w,this.session=E,this._=X?{schema:X.schema,fullSchema:X.fullSchema,tableNamesMap:X.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let G=this.query;if(this._.schema)for(let[J,A]of Object.entries(this._.schema))G[J]=new R8($,X.fullSchema,this._.schema,this._.tableNamesMap,X.fullSchema[J],A,w,E)}static[K]="BaseSQLiteDatabase";query;$with=($,w)=>{let E=this;return{as:(G)=>{if(typeof G==="function")G=G(new VG(E.dialect));return new Proxy(new FG(G.getSQL(),w??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),$,!0),new A$({alias:$,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count($,w){return new PG({source:$,filters:w,session:this.session})}with(...$){let w=this;function E(D){return new Z1({fields:D??void 0,session:w.session,dialect:w.dialect,withList:$})}function X(D){return new Z1({fields:D??void 0,session:w.session,dialect:w.dialect,withList:$,distinct:!0})}function G(D){return new gJ(D,w.session,w.dialect,$)}function J(D){return new yJ(D,w.session,w.dialect,$)}function A(D){return new CJ(D,w.session,w.dialect,$)}return{select:E,selectDistinct:X,update:G,insert:J,delete:A}}select($){return new Z1({fields:$??void 0,session:this.session,dialect:this.dialect})}selectDistinct($){return new Z1({fields:$??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update($){return new gJ($,this.session,this.dialect)}insert($){return new yJ($,this.session,this.dialect)}delete($){return new CJ($,this.session,this.dialect)}run($){let w=typeof $==="string"?T.raw($):$.getSQL();if(this.resultKind==="async")return new $X(async()=>this.session.run(w),()=>w,"run",this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session));return this.session.run(w)}all($){let w=typeof $==="string"?T.raw($):$.getSQL();if(this.resultKind==="async")return new $X(async()=>this.session.all(w),()=>w,"all",this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session));return this.session.all(w)}get($){let w=typeof $==="string"?T.raw($):$.getSQL();if(this.resultKind==="async")return new $X(async()=>this.session.get(w),()=>w,"get",this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session));return this.session.get(w)}values($){let w=typeof $==="string"?T.raw($):$.getSQL();if(this.resultKind==="async")return new $X(async()=>this.session.values(w),()=>w,"values",this.dialect,this.session.extractRawValuesValueFromBatchResult.bind(this.session));return this.session.values(w)}transaction($,w){return this.session.transaction($,w)}}});var EY=()=>{};var XY=()=>{};function hw($){return new z8($,!1)}function SG($){return new z8($,!0)}var z8,GY,JY;var AY=R(()=>{E0();z8=class z8{constructor($,w){this.name=$,this.unique=w}static[K]="SQLiteIndexBuilderOn";on(...$){return new GY(this.name,$,this.unique)}};GY=class GY{static[K]="SQLiteIndexBuilder";config;constructor($,w,E){this.config={name:$,columns:w,unique:E,where:void 0}}where($){return this.config.where=$,this}build($){return new JY(this.config,$)}};JY=class JY{static[K]="SQLiteIndex";config;constructor($,w){this.config={...$,table:w}}}});var DY=()=>{};var NY,T8,B8,Q8;var I8=R(()=>{E0();_J();Fw();hJ();NY=class NY extends v${constructor($){super();this.resultCb=$}static[K]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}};T8=class T8{constructor($,w,E){this.mode=$,this.executeMethod=w,this.query=E}static[K]="PreparedQuery";joinsNotNullableMap;getQuery(){return this.query}mapRunResult($,w){return $}mapAllResult($,w){throw Error("Not implemented")}mapGetResult($,w){throw Error("Not implemented")}execute($){if(this.mode==="async")return this[this.executeMethod]($);return new NY(()=>this[this.executeMethod]($))}mapResult($,w){switch(this.executeMethod){case"run":return this.mapRunResult($,w);case"all":return this.mapAllResult($,w);case"get":return this.mapGetResult($,w)}}};B8=class B8{constructor($){this.dialect=$}static[K]="SQLiteSession";prepareOneTimeQuery($,w,E,X){return this.prepareQuery($,w,E,X)}run($){let w=this.dialect.sqlToQuery($);try{return this.prepareOneTimeQuery(w,void 0,"run",!1).run()}catch(E){throw new eE({cause:E,message:`Failed to run the query '${w.sql}'`})}}extractRawRunValueFromBatchResult($){return $}all($){return this.prepareOneTimeQuery(this.dialect.sqlToQuery($),void 0,"run",!1).all()}extractRawAllValueFromBatchResult($){throw Error("Not implemented")}get($){return this.prepareOneTimeQuery(this.dialect.sqlToQuery($),void 0,"run",!1).get()}extractRawGetValueFromBatchResult($){throw Error("Not implemented")}values($){return this.prepareOneTimeQuery(this.dialect.sqlToQuery($),void 0,"run",!1).values()}async count($){return(await this.values($))[0][0]}extractRawValuesValueFromBatchResult($){throw Error("Not implemented")}};Q8=class Q8 extends qG{constructor($,w,E,X,G=0){super($,w,E,X);this.schema=X,this.nestedIndex=G}static[K]="SQLiteTransaction";rollback(){throw new N8}}});var WY=()=>{};var OY=()=>{};var K8=R(()=>{EY();XY();O8();hJ();fJ();aD();AY();DY();j8();I8();aE();eD();WY();OY()});var V8,P8,UY;var q8=R(()=>{E0();MJ();q$();K8();I8();o$();V8=class V8 extends B8{constructor($,w,E,X={}){super(w);this.client=$,this.schema=E,this.logger=X.logger??new gD}static[K]="SQLiteBunSession";logger;exec($){this.client.exec($)}prepareQuery($,w,E,X,G){let J=this.client.prepare($.sql);return new UY(J,$,this.logger,w,E,X,G)}transaction($,w={}){let E=new P8("sync",this.dialect,this,this.schema),X;return this.client.transaction(()=>{X=$(E)})[w.behavior??"deferred"](),X}};P8=class P8 extends Q8{static[K]="SQLiteBunTransaction";transaction($){let w=`sp${this.nestedIndex}`,E=new P8("sync",this.dialect,this.session,this.schema,this.nestedIndex+1);this.session.run(T.raw(`savepoint ${w}`));try{let X=$(E);return this.session.run(T.raw(`release savepoint ${w}`)),X}catch(X){throw this.session.run(T.raw(`rollback to savepoint ${w}`)),X}}};UY=class UY extends T8{constructor($,w,E,X,G,J,A){super("sync",G,w);this.stmt=$,this.logger=E,this.fields=X,this._isResponseInArrayMode=J,this.customResultMapper=A}static[K]="SQLiteBunPreparedQuery";run($){let w=jG(this.query.params,$??{});return this.logger.logQuery(this.query.sql,w),this.stmt.run(...w)}all($){let{fields:w,query:E,logger:X,joinsNotNullableMap:G,stmt:J,customResultMapper:A}=this;if(!w&&!A){let N=jG(E.params,$??{});return X.logQuery(E.sql,N),J.all(...N)}let D=this.values($);if(A)return A(D);return D.map((N)=>oD(w,N,G))}get($){let w=jG(this.query.params,$??{});this.logger.logQuery(this.query.sql,w);let E=this.stmt.values(...w)[0];if(!E)return;let{fields:X,joinsNotNullableMap:G,customResultMapper:J}=this;if(!X&&!J)return E;if(J)return J([E]);return oD(X,E,G)}values($){let w=jG(this.query.params,$??{});return this.logger.logQuery(this.query.sql,w),this.stmt.values(...w)}isResponseInArrayMode(){return this._isResponseInArrayMode}}});import{Database as cJ}from"bun:sqlite";function wX($,w={}){let E=new KG({casing:w.casing}),X;if(w.logger===!0)X=new yD;else if(w.logger!==!1)X=w.logger;let G;if(w.schema){let D=A7(w.schema,N7);G={fullSchema:w.schema,schema:D.tables,tableNamesMap:D.tableNamesMap}}let J=new V8($,E,G,{logger:X}),A=new YY("sync",E,J,G);return A.$client=$,A}function nJ(...$){if($[0]===void 0||typeof $[0]==="string"){let w=$[0]===void 0?new cJ:new cJ($[0]);return wX(w,$[1])}if(CU($[0])){let{connection:w,client:E,...X}=$[0];if(E)return wX(E,X);if(typeof w==="object"){let{source:J,...A}=w,D=Object.values(A).filter((W)=>W!==void 0).length?A:void 0,N=new cJ(J,D);return wX(N,X)}let G=new cJ(w);return wX(G,X)}return wX($[0],$[1])}var YY;var HY=R(()=>{E0();MJ();TG();hJ();fJ();o$();q8();YY=class YY extends qG{static[K]="BunSQLiteDatabase"};(($)=>{function w(E){return wX({},E)}$.mock=w})(nJ||(nJ={}))});var LY=R(()=>{HY();q8()});var FY=R(()=>{PJ()});var i$=R(()=>{kJ();nD();b1();E0();_J();FY();MJ();Fw();TG();W8();d1();_$();o$();Lw()});var k8={};Ww(k8,{webhooks:()=>O2,tasks:()=>r,task_links:()=>f$,sessions:()=>C1,prompts:()=>D$,prompt_history:()=>bG,projects:()=>n0,memories:()=>H1,jobs:()=>I0,job_runs:()=>E$,job_run_logs:()=>cw,gateway_sessions:()=>x$,comments:()=>G$,bridge_permissions:()=>EX,bridge_messages:()=>S8,bridge_chats:()=>X$});var kG,n0,r,G$,f$,H1,D$,bG,I0,E$,cw,C1,X$,S8,EX,x$,O2;var d$=R(()=>{i$();K8();kG={created_at:s("created_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`),updated_at:s("updated_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`)},n0=M$("projects",{id:q("id").primaryKey(),name:q("name").notNull(),description:q("description"),status:q("status",{enum:["active","archived","paused"]}).default("active").notNull(),scope:q("scope"),tags:q("tags",{mode:"json"}).$type(),obsidian_path:q("obsidian_path"),...kG},($)=>[SG("projects_name_idx").on($.name)]),r=M$("tasks",{id:q("id").primaryKey(),project_id:q("project_id").references(()=>n0.id),title:q("title").notNull(),body:q("body"),status:q("status",{enum:["todo","doing","review","changes_requested","blocked","done","cancelled"]}).default("todo").notNull(),priority:q("priority",{enum:["low","normal","high","critical"]}).default("normal").notNull(),progress:s("progress").default(0).notNull(),due_at:s("due_at",{mode:"timestamp"}),tags:q("tags",{mode:"json"}).$type(),author:q("author").default("human").notNull(),claimed_by:q("claimed_by"),claim_expires_at:s("claim_expires_at",{mode:"timestamp"}),...kG}),G$=M$("comments",{id:q("id").primaryKey(),resource_type:q("resource_type",{enum:["task","project","job","memory"]}).notNull(),resource_id:q("resource_id").notNull(),content:q("content").notNull(),author:q("author").default("human").notNull(),created_at:s("created_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`)},($)=>[hw("comments_resource_idx").on($.resource_type,$.resource_id)]),f$=M$("task_links",{id:q("id").primaryKey(),from_task_id:q("from_task_id").notNull().references(()=>r.id,{onDelete:"cascade"}),to_task_id:q("to_task_id").notNull().references(()=>r.id,{onDelete:"cascade"}),link_type:q("link_type",{enum:["blocks","blocked_by","relates_to","duplicates","clones","subtask_of","parent_of"]}).notNull(),created_at:s("created_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`)},($)=>[hw("task_links_from_idx").on($.from_task_id),hw("task_links_to_idx").on($.to_task_id)]),H1=M$("memories",{id:q("id").primaryKey(),project_id:q("project_id").references(()=>n0.id),title:q("title"),type:q("type",{enum:["fact","decision","event","rule","discovery"]}).default("fact").notNull(),content:q("content").notNull(),source:q("source"),scope:q("scope"),tags:q("tags",{mode:"json"}).$type(),importance:q("importance",{enum:["low","normal","high","critical"]}).default("normal").notNull(),expires_at:s("expires_at",{mode:"timestamp"}),access_count:s("access_count").notNull().default(0),last_accessed_at:s("last_accessed_at",{mode:"timestamp"}),...kG}),D$=M$("prompts",{id:q("id").primaryKey(),name:q("name").notNull(),description:q("description"),template:q("template").notNull(),is_skill:s("is_skill",{mode:"boolean"}).default(!1).notNull(),skill_dir:q("skill_dir"),skill_version:q("skill_version"),frontmatter:q("frontmatter",{mode:"json"}).$type(),tags:q("tags",{mode:"json"}).$type(),version:s("version").default(1).notNull(),pinned:s("pinned",{mode:"boolean"}).default(!1).notNull(),last_used_at:s("last_used_at",{mode:"timestamp"}),...kG},($)=>[SG("prompts_name_idx").on($.name)]),bG=M$("prompt_history",{id:q("id").primaryKey(),prompt_id:q("prompt_id").notNull().references(()=>D$.id,{onDelete:"cascade"}),version:s("version").notNull(),name:q("name").notNull(),description:q("description"),template:q("template").notNull(),tags:q("tags",{mode:"json"}).$type(),changed_by:q("changed_by").default("human").notNull(),changed_at:s("changed_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`)},($)=>[hw("prompt_history_prompt_id_idx").on($.prompt_id,$.version)]),I0=M$("jobs",{id:q("id").primaryKey(),project_id:q("project_id").references(()=>n0.id),name:q("name").notNull(),description:q("description"),command:q("command").notNull(),prompt_id:q("prompt_id").references(()=>D$.id),prompt_vars:q("prompt_vars",{mode:"json"}).$type(),inject_context:s("inject_context",{mode:"boolean"}).default(!0).notNull(),trigger_type:q("trigger_type",{enum:["one-shot","cron","watch","webhook","manual","bridge-msg"]}).notNull(),cron_expr:q("cron_expr"),watch_path:q("watch_path"),run_at:s("run_at",{mode:"timestamp"}),timeout_secs:s("timeout_secs").default(300).notNull(),max_retries:s("max_retries").default(0).notNull(),overlap:q("overlap",{enum:["skip","queue","kill"]}).default("skip").notNull(),env_vars:q("env_vars",{mode:"json"}).$type(),working_dir:q("working_dir"),notify_on:q("notify_on",{enum:["never","failure","always"]}).default("failure").notNull(),notify_channel:q("notify_channel").default("telegram").notNull(),os_installed:s("os_installed",{mode:"boolean"}).default(!1).notNull(),enabled:s("enabled",{mode:"boolean"}).default(!0).notNull(),last_run_at:s("last_run_at",{mode:"timestamp"}),next_run_at:s("next_run_at",{mode:"timestamp"}),run_count:s("run_count").default(0).notNull(),...kG},($)=>[SG("jobs_name_idx").on($.name)]),E$=M$("job_runs",{id:q("id").primaryKey(),job_id:q("job_id").notNull().references(()=>I0.id,{onDelete:"cascade"}),status:q("status",{enum:["pending","running","success","failed","cancelled","skipped"]}).notNull(),trigger_by:q("trigger_by"),started_at:s("started_at",{mode:"timestamp"}),ended_at:s("ended_at",{mode:"timestamp"}),exit_code:s("exit_code"),stdout:q("stdout"),stderr:q("stderr"),error_msg:q("error_msg"),retry_num:s("retry_num").default(0).notNull(),created_at:s("created_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`)},($)=>[hw("job_runs_job_id_idx").on($.job_id)]),cw=M$("job_run_logs",{id:s("id",{mode:"number"}).primaryKey({autoIncrement:!0}),run_id:q("run_id").notNull().references(()=>E$.id,{onDelete:"cascade"}),ts:s("ts",{mode:"timestamp"}).notNull(),stream:q("stream",{enum:["stdout","stderr"]}).notNull(),line:q("line").notNull()},($)=>[hw("job_run_logs_run_id_idx").on($.run_id,$.ts)]),C1=M$("sessions",{id:q("id").primaryKey(),agent:q("agent").notNull(),agent_version:q("agent_version"),project_id:q("project_id").references(()=>n0.id),job_run_id:q("job_run_id").references(()=>E$.id),summary:q("summary"),events:q("events",{mode:"json"}).$type(),snapshot:q("snapshot"),tokens_used:s("tokens_used"),created_at:s("created_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`)}),X$=M$("bridge_chats",{id:q("id").primaryKey(),platform:q("platform",{enum:["telegram","slack","discord","feishu"]}).notNull(),chat_id:q("chat_id").notNull(),username:q("username"),display_name:q("display_name"),mode:q("mode").default("direct").notNull(),authorized:s("authorized",{mode:"boolean"}).default(!1).notNull(),session_id:q("session_id"),thread_id:q("thread_id"),working_dir:q("working_dir"),updated_at:s("updated_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`),created_at:s("created_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`)},($)=>[SG("bridge_chats_platform_chat_idx").on($.platform,$.chat_id)]),S8=M$("bridge_messages",{id:q("id").primaryKey(),chat_id:q("chat_id").references(()=>X$.id),direction:q("direction",{enum:["in","out"]}).notNull(),role:q("role",{enum:["system","user","assistant"]}).default("user").notNull(),text:q("text"),job_run_id:q("job_run_id").references(()=>E$.id),gateway_session_id:q("gateway_session_id").references(()=>x$.id),platform_msg_id:q("platform_msg_id"),thread_id:q("thread_id"),metadata:q("metadata",{mode:"json"}).$type(),created_at:s("created_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`)}),EX=M$("bridge_permissions",{id:q("id").primaryKey(),chat_id:q("chat_id"),gateway_session_id:q("gateway_session_id").references(()=>x$.id),job_run_id:q("job_run_id").references(()=>E$.id),tool:q("tool").notNull(),command:q("command"),scope:q("scope",{enum:["once","session"]}).default("once").notNull(),message:q("message"),status:q("status",{enum:["pending","approved","denied","expired"]}).default("pending").notNull(),expires_at:s("expires_at",{mode:"timestamp"}),created_at:s("created_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`),resolved_at:s("resolved_at",{mode:"timestamp"})}),x$=M$("gateway_sessions",{id:q("id").primaryKey(),chat_id:q("chat_id").notNull().references(()=>X$.id,{onDelete:"cascade"}),backend:q("backend",{enum:["claude","codex","cursor"]}).notNull(),mode:q("mode").notNull(),runtime_session_id:q("runtime_session_id"),cwd:q("cwd"),title:q("title"),model:q("model"),status:q("status",{enum:["idle","running","stopped","error"]}).default("idle").notNull(),auto_approve:s("auto_approve",{mode:"boolean"}).default(!1).notNull(),task_id:q("task_id").references(()=>r.id,{onDelete:"set null"}),last_error:q("last_error"),last_activity_at:s("last_activity_at",{mode:"timestamp"}),created_at:s("created_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`),updated_at:s("updated_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`)},($)=>[hw("gateway_sessions_chat_idx").on($.chat_id,$.updated_at)]),O2=M$("webhooks",{id:q("id").primaryKey(),job_id:q("job_id").notNull().references(()=>I0.id,{onDelete:"cascade"}),token:q("token").notNull().unique(),enabled:s("enabled",{mode:"boolean"}).default(!0).notNull(),created_at:s("created_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`)})});import{Database as U2}from"bun:sqlite";import{mkdirSync as Y2}from"fs";import{dirname as H2}from"path";function L2($){$.exec(`
|
|
35
|
+
`;w.run(G);let A=w.values(T`SELECT id, hash, created_at FROM ${T.identifier(X)} ORDER BY created_at DESC LIMIT 1`)[0]??void 0;w.run(T`BEGIN`);try{for(let D of $)if(!A||Number(A[2])<D.folderMillis){for(let N of D.sql)w.run(T.raw(N));w.run(T`INSERT INTO ${T.identifier(X)} ("hash", "created_at") VALUES(${D.hash}, ${D.folderMillis})`)}w.run(T`COMMIT`)}catch(D){throw w.run(T`ROLLBACK`),D}}}});var L8;var s7=R(()=>{E0();L8=class L8{static[K]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}});function gJ($,w){return(E,X,...G)=>{let J=[X,...G].map((A)=>({type:$,isAll:w,rightSelect:A}));for(let A of J)if(!RG(E.getSelectedFields(),A.rightSelect.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return E.addSetOperators(J)}}var Z1,a7,F8,Y2=()=>({union:H2,unionAll:L2,intersect:F2,except:j2}),H2,L2,F2,j2;var j8=R(()=>{E0();s7();Fw();aE();q$();d1();_$();o$();Lw();xJ();Z1=class Z1{static[K]="SQLiteSelectBuilder";fields;session;dialect;withList;distinct;constructor($){this.fields=$.fields,this.session=$.session,this.dialect=$.dialect,this.withList=$.withList,this.distinct=$.distinct}from($){let w=!!this.fields,E;if(this.fields)E=this.fields;else if(b($,Y$))E=Object.fromEntries(Object.keys($._.selectedFields).map((X)=>[X,$[X]]));else if(b($,YE))E=$[s0].selectedFields;else if(b($,h))E={};else E=vU($);return new F8({table:$,fields:E,isPartialSelect:w,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}};a7=class a7 extends L8{static[K]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:$,fields:w,isPartialSelect:E,session:X,dialect:G,withList:J,distinct:A}){super();this.config={withList:J,table:$,fields:{...w},distinct:A,setOperators:[]},this.isPartialSelect=E,this.session=X,this.dialect=G,this._={selectedFields:w},this.tableName=zG($),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin($){return(w,E)=>{let X=this.tableName,G=zG(w);if(typeof G==="string"&&this.config.joins?.some((J)=>J.alias===G))throw Error(`Alias "${G}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof X==="string")this.config.fields={[X]:this.config.fields};if(typeof G==="string"&&!b(w,h)){let J=b(w,Y$)?w._.selectedFields:b(w,U1)?w[s0].selectedFields:w[y.Symbol.Columns];this.config.fields[G]=J}}if(typeof E==="function")E=E(new Proxy(this.config.fields,new A$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:E,table:w,joinType:$,alias:G}),typeof G==="string")switch($){case"left":{this.joinsNotNullableMap[G]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[G]=!0;break}case"inner":{this.joinsNotNullableMap[G]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[G]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");createSetOperator($,w){return(E)=>{let X=typeof E==="function"?E(Y2()):E;if(!RG(this.getSelectedFields(),X.getSelectedFields()))throw 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:$,isAll:w,rightSelect:X}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);except=this.createSetOperator("except",!1);addSetOperators($){return this.config.setOperators.push(...$),this}where($){if(typeof $==="function")$=$(new Proxy(this.config.fields,new A$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=$,this}having($){if(typeof $==="function")$=$(new Proxy(this.config.fields,new A$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=$,this}groupBy(...$){if(typeof $[0]==="function"){let w=$[0](new Proxy(this.config.fields,new A$({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(w)?w:[w]}else this.config.groupBy=$;return this}orderBy(...$){if(typeof $[0]==="function"){let w=$[0](new Proxy(this.config.fields,new A$({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),E=Array.isArray(w)?w:[w];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=E;else this.config.orderBy=E}else{let w=$;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=w;else this.config.orderBy=w}return this}limit($){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=$;else this.config.limit=$;return this}offset($){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=$;else this.config.offset=$;return this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:$,...w}=this.dialect.sqlToQuery(this.getSQL());return w}as($){return new Proxy(new Y$(this.getSQL(),this.config.fields,$),new A$({alias:$,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new A$({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}};F8=class F8 extends a7{static[K]="SQLiteSelect";_prepare($=!0){if(!this.session)throw Error("Cannot execute a query on a query builder. Please use a database instance instead.");let w=Y1(this.config.fields),E=this.session[$?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),w,"all",!0);return E.joinsNotNullableMap=this.joinsNotNullableMap,E}prepare(){return this._prepare(!1)}run=($)=>{return this._prepare().run($)};all=($)=>{return this._prepare().all($)};get=($)=>{return this._prepare().get($)};values=($)=>{return this._prepare().values($)};async execute(){return this.all()}};_U(F8,[v$]);H2=gJ("union",!1),L2=gJ("union",!0),F2=gJ("intersect",!1),j2=gJ("except",!1)});var PG;var M8=R(()=>{E0();aE();yJ();d1();j8();PG=class PG{static[K]="SQLiteQueryBuilder";dialect;dialectConfig;constructor($){this.dialect=b($,KG)?$:void 0,this.dialectConfig=b($,KG)?void 0:$}$with=($,w)=>{let E=this;return{as:(G)=>{if(typeof G==="function")G=G(E);return new Proxy(new jG(G.getSQL(),w??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),$,!0),new A$({alias:$,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...$){let w=this;function E(G){return new Z1({fields:G??void 0,session:void 0,dialect:w.getDialect(),withList:$})}function X(G){return new Z1({fields:G??void 0,session:void 0,dialect:w.getDialect(),withList:$,distinct:!0})}return{select:E,selectDistinct:X}}select($){return new Z1({fields:$??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct($){return new Z1({fields:$??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new VG(this.dialectConfig);return this.dialect}}});var uJ,R8;var e7=R(()=>{E0();Fw();q$();eE();_$();o$();M8();uJ=class uJ{constructor($,w,E,X){this.table=$,this.session=w,this.dialect=E,this.withList=X}static[K]="SQLiteInsertBuilder";values($){if($=Array.isArray($)?$:[$],$.length===0)throw Error("values() must be called with at least one value");let w=$.map((E)=>{let X={},G=this.table[y.Symbol.Columns];for(let J of Object.keys(E)){let A=E[J];X[J]=b(A,h)?A:new J1(A,G[J])}return X});return new R8(this.table,w,this.session,this.dialect,this.withList)}select($){let w=typeof $==="function"?$(new PG):$;if(!b(w,h)&&!RG(this.table[BJ],w._.selectedFields))throw Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new R8(this.table,w,this.session,this.dialect,this.withList,!0)}};R8=class R8 extends v${constructor($,w,E,X,G,J){super();this.session=E,this.dialect=X,this.config={table:$,values:w,withList:G,select:J}}static[K]="SQLiteInsert";config;returning($=this.config.table[S$.Symbol.Columns]){return this.config.returning=Y1($),this}onConflictDoNothing($={}){if(!this.config.onConflict)this.config.onConflict=[];if($.target===void 0)this.config.onConflict.push(T` on conflict do nothing`);else{let w=Array.isArray($.target)?T`${$.target}`:T`${[$.target]}`,E=$.where?T` where ${$.where}`:T``;this.config.onConflict.push(T` on conflict ${w} do nothing${E}`)}return this}onConflictDoUpdate($){if($.where&&($.targetWhere||$.setWhere))throw Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');if(!this.config.onConflict)this.config.onConflict=[];let w=$.where?T` where ${$.where}`:void 0,E=$.targetWhere?T` where ${$.targetWhere}`:void 0,X=$.setWhere?T` where ${$.setWhere}`:void 0,G=Array.isArray($.target)?T`${$.target}`:T`${[$.target]}`,J=this.dialect.buildUpdateSet(this.config.table,KJ(this.config.table,$.set));return this.config.onConflict.push(T` on conflict ${G}${E} do update set ${J}${w}${X}`),this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:$,...w}=this.dialect.sqlToQuery(this.getSQL());return w}_prepare($=!0){return this.session[$?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0)}prepare(){return this._prepare(!1)}run=($)=>{return this._prepare().run($)};all=($)=>{return this._prepare().all($)};get=($)=>{return this._prepare().get($)};values=($)=>{return this._prepare().values($)};async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var hJ,$Y;var wY=R(()=>{E0();Fw();aE();eE();d1();_$();o$();Lw();xJ();hJ=class hJ{constructor($,w,E,X){this.table=$,this.session=w,this.dialect=E,this.withList=X}static[K]="SQLiteUpdateBuilder";set($){return new $Y(this.table,KJ(this.table,$),this.session,this.dialect,this.withList)}};$Y=class $Y extends v${constructor($,w,E,X,G){super();this.session=E,this.dialect=X,this.config={set:w,table:$,withList:G,joins:[]}}static[K]="SQLiteUpdate";config;from($){return this.config.from=$,this}createJoin($){return(w,E)=>{let X=zG(w);if(typeof X==="string"&&this.config.joins.some((G)=>G.alias===X))throw Error(`Alias "${X}" is already used in this query`);if(typeof E==="function"){let G=this.config.from?b(w,S$)?w[y.Symbol.Columns]:b(w,Y$)?w._.selectedFields:b(w,YE)?w[s0].selectedFields:void 0:void 0;E=E(new Proxy(this.config.table[y.Symbol.Columns],new A$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),G&&new Proxy(G,new A$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:E,table:w,joinType:$,alias:X}),this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where($){return this.config.where=$,this}orderBy(...$){if(typeof $[0]==="function"){let w=$[0](new Proxy(this.config.table[y.Symbol.Columns],new A$({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),E=Array.isArray(w)?w:[w];this.config.orderBy=E}else{let w=$;this.config.orderBy=w}return this}limit($){return this.config.limit=$,this}returning($=this.config.table[S$.Symbol.Columns]){return this.config.returning=Y1($),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:$,...w}=this.dialect.sqlToQuery(this.getSQL());return w}_prepare($=!0){return this.session[$?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0)}prepare(){return this._prepare(!1)}run=($)=>{return this._prepare().run($)};all=($)=>{return this._prepare().all($)};get=($)=>{return this._prepare().get($)};values=($)=>{return this._prepare().values($)};async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var z8=R(()=>{o7();e7();M8();j8();wY()});var qG;var EY=R(()=>{E0();q$();qG=class qG extends h{constructor($){super(qG.buildEmbeddedCount($.source,$.filters).queryChunks);this.params=$,this.session=$.session,this.sql=qG.buildCount($.source,$.filters)}sql;static[K]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount($,w){return T`(select count(*) from ${$}${T.raw(" where ").if(w)}${w})`}static buildCount($,w){return T`select count(*) from ${$}${T.raw(" where ").if(w)}${w}`}then($,w){return Promise.resolve(this.session.count(this.sql)).then($,w)}catch($){return this.then(void 0,$)}finally($){return this.then((w)=>{return $?.(),w},(w)=>{throw $?.(),w})}}});var B8,cJ,T8;var XY=R(()=>{E0();Fw();BG();B8=class B8{constructor($,w,E,X,G,J,A,D){this.mode=$,this.fullSchema=w,this.schema=E,this.tableNamesMap=X,this.table=G,this.tableConfig=J,this.dialect=A,this.session=D}static[K]="SQLiteAsyncRelationalQueryBuilder";findMany($){return this.mode==="sync"?new T8(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,$?$:{},"many"):new cJ(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,$?$:{},"many")}findFirst($){return this.mode==="sync"?new T8(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,$?{...$,limit:1}:{limit:1},"first"):new cJ(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,$?{...$,limit:1}:{limit:1},"first")}};cJ=class cJ extends v${constructor($,w,E,X,G,J,A,D,N){super();this.fullSchema=$,this.schema=w,this.tableNamesMap=E,this.table=X,this.tableConfig=G,this.dialect=J,this.session=A,this.config=D,this.mode=N}static[K]="SQLiteAsyncRelationalQuery";mode;getSQL(){return this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}).sql}_prepare($=!1){let{query:w,builtQuery:E}=this._toSQL();return this.session[$?"prepareOneTimeQuery":"prepareQuery"](E,void 0,this.mode==="first"?"get":"all",!0,(X,G)=>{let J=X.map((A)=>kJ(this.schema,this.tableConfig,A,w.selection,G));if(this.mode==="first")return J[0];return J})}prepare(){return this._prepare(!1)}_toSQL(){let $=this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}),w=this.dialect.sqlToQuery($.sql);return{query:$,builtQuery:w}}toSQL(){return this._toSQL().builtQuery}executeRaw(){if(this.mode==="first")return this._prepare(!1).get();return this._prepare(!1).all()}async execute(){return this.executeRaw()}};T8=class T8 extends cJ{static[K]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}});var wX;var GY=R(()=>{E0();Fw();wX=class wX extends v${constructor($,w,E,X,G){super();this.execute=$,this.getSQL=w,this.dialect=X,this.mapBatchResult=G,this.config={action:E}}static[K]="SQLiteRaw";config;getQuery(){return{...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult($,w){return w?this.mapBatchResult($):$}_prepare(){return this}isResponseInArrayMode(){return!1}}});var SG;var nJ=R(()=>{E0();aE();q$();z8();d1();EY();XY();GY();SG=class SG{constructor($,w,E,X){this.resultKind=$,this.dialect=w,this.session=E,this._=X?{schema:X.schema,fullSchema:X.fullSchema,tableNamesMap:X.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let G=this.query;if(this._.schema)for(let[J,A]of Object.entries(this._.schema))G[J]=new B8($,X.fullSchema,this._.schema,this._.tableNamesMap,X.fullSchema[J],A,w,E)}static[K]="BaseSQLiteDatabase";query;$with=($,w)=>{let E=this;return{as:(G)=>{if(typeof G==="function")G=G(new PG(E.dialect));return new Proxy(new jG(G.getSQL(),w??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),$,!0),new A$({alias:$,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count($,w){return new qG({source:$,filters:w,session:this.session})}with(...$){let w=this;function E(D){return new Z1({fields:D??void 0,session:w.session,dialect:w.dialect,withList:$})}function X(D){return new Z1({fields:D??void 0,session:w.session,dialect:w.dialect,withList:$,distinct:!0})}function G(D){return new hJ(D,w.session,w.dialect,$)}function J(D){return new uJ(D,w.session,w.dialect,$)}function A(D){return new vJ(D,w.session,w.dialect,$)}return{select:E,selectDistinct:X,update:G,insert:J,delete:A}}select($){return new Z1({fields:$??void 0,session:this.session,dialect:this.dialect})}selectDistinct($){return new Z1({fields:$??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update($){return new hJ($,this.session,this.dialect)}insert($){return new uJ($,this.session,this.dialect)}delete($){return new vJ($,this.session,this.dialect)}run($){let w=typeof $==="string"?T.raw($):$.getSQL();if(this.resultKind==="async")return new wX(async()=>this.session.run(w),()=>w,"run",this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session));return this.session.run(w)}all($){let w=typeof $==="string"?T.raw($):$.getSQL();if(this.resultKind==="async")return new wX(async()=>this.session.all(w),()=>w,"all",this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session));return this.session.all(w)}get($){let w=typeof $==="string"?T.raw($):$.getSQL();if(this.resultKind==="async")return new wX(async()=>this.session.get(w),()=>w,"get",this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session));return this.session.get(w)}values($){let w=typeof $==="string"?T.raw($):$.getSQL();if(this.resultKind==="async")return new wX(async()=>this.session.values(w),()=>w,"values",this.dialect,this.session.extractRawValuesValueFromBatchResult.bind(this.session));return this.session.values(w)}transaction($,w){return this.session.transaction($,w)}}});var JY=()=>{};var AY=()=>{};function hw($){return new Q8($,!1)}function kG($){return new Q8($,!0)}var Q8,DY,NY;var WY=R(()=>{E0();Q8=class Q8{constructor($,w){this.name=$,this.unique=w}static[K]="SQLiteIndexBuilderOn";on(...$){return new DY(this.name,$,this.unique)}};DY=class DY{static[K]="SQLiteIndexBuilder";config;constructor($,w,E){this.config={name:$,columns:w,unique:E,where:void 0}}where($){return this.config.where=$,this}build($){return new NY(this.config,$)}};NY=class NY{static[K]="SQLiteIndex";config;constructor($,w){this.config={...$,table:w}}}});var OY=()=>{};var UY,I8,K8,V8;var P8=R(()=>{E0();fJ();Fw();nJ();UY=class UY extends v${constructor($){super();this.resultCb=$}static[K]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}};I8=class I8{constructor($,w,E){this.mode=$,this.executeMethod=w,this.query=E}static[K]="PreparedQuery";joinsNotNullableMap;getQuery(){return this.query}mapRunResult($,w){return $}mapAllResult($,w){throw Error("Not implemented")}mapGetResult($,w){throw Error("Not implemented")}execute($){if(this.mode==="async")return this[this.executeMethod]($);return new UY(()=>this[this.executeMethod]($))}mapResult($,w){switch(this.executeMethod){case"run":return this.mapRunResult($,w);case"all":return this.mapAllResult($,w);case"get":return this.mapGetResult($,w)}}};K8=class K8{constructor($){this.dialect=$}static[K]="SQLiteSession";prepareOneTimeQuery($,w,E,X){return this.prepareQuery($,w,E,X)}run($){let w=this.dialect.sqlToQuery($);try{return this.prepareOneTimeQuery(w,void 0,"run",!1).run()}catch(E){throw new $X({cause:E,message:`Failed to run the query '${w.sql}'`})}}extractRawRunValueFromBatchResult($){return $}all($){return this.prepareOneTimeQuery(this.dialect.sqlToQuery($),void 0,"run",!1).all()}extractRawAllValueFromBatchResult($){throw Error("Not implemented")}get($){return this.prepareOneTimeQuery(this.dialect.sqlToQuery($),void 0,"run",!1).get()}extractRawGetValueFromBatchResult($){throw Error("Not implemented")}values($){return this.prepareOneTimeQuery(this.dialect.sqlToQuery($),void 0,"run",!1).values()}async count($){return(await this.values($))[0][0]}extractRawValuesValueFromBatchResult($){throw Error("Not implemented")}};V8=class V8 extends SG{constructor($,w,E,X,G=0){super($,w,E,X);this.schema=X,this.nestedIndex=G}static[K]="SQLiteTransaction";rollback(){throw new U8}}});var YY=()=>{};var HY=()=>{};var q8=R(()=>{JY();AY();H8();nJ();yJ();w8();WY();OY();z8();P8();eE();E8();YY();HY()});var S8,k8,LY;var b8=R(()=>{E0();zJ();q$();q8();P8();o$();S8=class S8 extends K8{constructor($,w,E,X={}){super(w);this.client=$,this.schema=E,this.logger=X.logger??new cD}static[K]="SQLiteBunSession";logger;exec($){this.client.exec($)}prepareQuery($,w,E,X,G){let J=this.client.prepare($.sql);return new LY(J,$,this.logger,w,E,X,G)}transaction($,w={}){let E=new k8("sync",this.dialect,this,this.schema),X;return this.client.transaction(()=>{X=$(E)})[w.behavior??"deferred"](),X}};k8=class k8 extends V8{static[K]="SQLiteBunTransaction";transaction($){let w=`sp${this.nestedIndex}`,E=new k8("sync",this.dialect,this.session,this.schema,this.nestedIndex+1);this.session.run(T.raw(`savepoint ${w}`));try{let X=$(E);return this.session.run(T.raw(`release savepoint ${w}`)),X}catch(X){throw this.session.run(T.raw(`rollback to savepoint ${w}`)),X}}};LY=class LY extends I8{constructor($,w,E,X,G,J,A){super("sync",G,w);this.stmt=$,this.logger=E,this.fields=X,this._isResponseInArrayMode=J,this.customResultMapper=A}static[K]="SQLiteBunPreparedQuery";run($){let w=MG(this.query.params,$??{});return this.logger.logQuery(this.query.sql,w),this.stmt.run(...w)}all($){let{fields:w,query:E,logger:X,joinsNotNullableMap:G,stmt:J,customResultMapper:A}=this;if(!w&&!A){let N=MG(E.params,$??{});return X.logQuery(E.sql,N),J.all(...N)}let D=this.values($);if(A)return A(D);return D.map((N)=>dD(w,N,G))}get($){let w=MG(this.query.params,$??{});this.logger.logQuery(this.query.sql,w);let E=this.stmt.values(...w)[0];if(!E)return;let{fields:X,joinsNotNullableMap:G,customResultMapper:J}=this;if(!X&&!J)return E;if(J)return J([E]);return dD(X,E,G)}values($){let w=MG(this.query.params,$??{});return this.logger.logQuery(this.query.sql,w),this.stmt.values(...w)}isResponseInArrayMode(){return this._isResponseInArrayMode}}});import{Database as mJ}from"bun:sqlite";function EX($,w={}){let E=new VG({casing:w.casing}),X;if(w.logger===!0)X=new hD;else if(w.logger!==!1)X=w.logger;let G;if(w.schema){let D=W7(w.schema,U7);G={fullSchema:w.schema,schema:D.tables,tableNamesMap:D.tableNamesMap}}let J=new S8($,E,G,{logger:X}),A=new FY("sync",E,J,G);return A.$client=$,A}function rJ(...$){if($[0]===void 0||typeof $[0]==="string"){let w=$[0]===void 0?new mJ:new mJ($[0]);return EX(w,$[1])}if(fU($[0])){let{connection:w,client:E,...X}=$[0];if(E)return EX(E,X);if(typeof w==="object"){let{source:J,...A}=w,D=Object.values(A).filter((W)=>W!==void 0).length?A:void 0,N=new mJ(J,D);return EX(N,X)}let G=new mJ(w);return EX(G,X)}return EX($[0],$[1])}var FY;var jY=R(()=>{E0();zJ();BG();nJ();yJ();o$();b8();FY=class FY extends SG{static[K]="BunSQLiteDatabase"};(($)=>{function w(E){return EX({},E)}$.mock=w})(rJ||(rJ={}))});var MY=R(()=>{jY();b8()});var RY=R(()=>{SJ()});var i$=R(()=>{ZJ();pD();b1();E0();fJ();RY();zJ();Fw();BG();Y8();d1();_$();o$();Lw()});var C8={};Ww(C8,{webhooks:()=>M2,tasks:()=>r,task_links:()=>f$,sessions:()=>C1,prompts:()=>D$,prompt_history:()=>ZG,projects:()=>n0,memories:()=>H1,jobs:()=>I0,job_runs:()=>E$,job_run_logs:()=>cw,gateway_sessions:()=>x$,comments:()=>G$,bridge_permissions:()=>XX,bridge_messages:()=>Z8,bridge_chats:()=>X$});var bG,n0,r,G$,f$,H1,D$,ZG,I0,E$,cw,C1,X$,Z8,XX,x$,M2;var d$=R(()=>{i$();q8();bG={created_at:s("created_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`),updated_at:s("updated_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`)},n0=M$("projects",{id:q("id").primaryKey(),name:q("name").notNull(),description:q("description"),status:q("status",{enum:["active","archived","paused"]}).default("active").notNull(),scope:q("scope"),tags:q("tags",{mode:"json"}).$type(),obsidian_path:q("obsidian_path"),...bG},($)=>[kG("projects_name_idx").on($.name)]),r=M$("tasks",{id:q("id").primaryKey(),project_id:q("project_id").references(()=>n0.id),title:q("title").notNull(),body:q("body"),status:q("status",{enum:["todo","doing","review","changes_requested","blocked","done","cancelled"]}).default("todo").notNull(),priority:q("priority",{enum:["low","normal","high","critical"]}).default("normal").notNull(),progress:s("progress").default(0).notNull(),due_at:s("due_at",{mode:"timestamp"}),tags:q("tags",{mode:"json"}).$type(),author:q("author").default("human").notNull(),claimed_by:q("claimed_by"),claim_expires_at:s("claim_expires_at",{mode:"timestamp"}),...bG}),G$=M$("comments",{id:q("id").primaryKey(),resource_type:q("resource_type",{enum:["task","project","job","memory"]}).notNull(),resource_id:q("resource_id").notNull(),content:q("content").notNull(),author:q("author").default("human").notNull(),created_at:s("created_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`)},($)=>[hw("comments_resource_idx").on($.resource_type,$.resource_id)]),f$=M$("task_links",{id:q("id").primaryKey(),from_task_id:q("from_task_id").notNull().references(()=>r.id,{onDelete:"cascade"}),to_task_id:q("to_task_id").notNull().references(()=>r.id,{onDelete:"cascade"}),link_type:q("link_type",{enum:["blocks","blocked_by","relates_to","duplicates","clones","subtask_of","parent_of"]}).notNull(),created_at:s("created_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`)},($)=>[hw("task_links_from_idx").on($.from_task_id),hw("task_links_to_idx").on($.to_task_id)]),H1=M$("memories",{id:q("id").primaryKey(),project_id:q("project_id").references(()=>n0.id),title:q("title"),type:q("type",{enum:["fact","decision","event","rule","discovery"]}).default("fact").notNull(),content:q("content").notNull(),source:q("source"),scope:q("scope"),tags:q("tags",{mode:"json"}).$type(),importance:q("importance",{enum:["low","normal","high","critical"]}).default("normal").notNull(),expires_at:s("expires_at",{mode:"timestamp"}),access_count:s("access_count").notNull().default(0),last_accessed_at:s("last_accessed_at",{mode:"timestamp"}),...bG}),D$=M$("prompts",{id:q("id").primaryKey(),name:q("name").notNull(),description:q("description"),template:q("template").notNull(),is_skill:s("is_skill",{mode:"boolean"}).default(!1).notNull(),skill_dir:q("skill_dir"),skill_version:q("skill_version"),frontmatter:q("frontmatter",{mode:"json"}).$type(),tags:q("tags",{mode:"json"}).$type(),version:s("version").default(1).notNull(),pinned:s("pinned",{mode:"boolean"}).default(!1).notNull(),last_used_at:s("last_used_at",{mode:"timestamp"}),...bG},($)=>[kG("prompts_name_idx").on($.name)]),ZG=M$("prompt_history",{id:q("id").primaryKey(),prompt_id:q("prompt_id").notNull().references(()=>D$.id,{onDelete:"cascade"}),version:s("version").notNull(),name:q("name").notNull(),description:q("description"),template:q("template").notNull(),tags:q("tags",{mode:"json"}).$type(),changed_by:q("changed_by").default("human").notNull(),changed_at:s("changed_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`)},($)=>[hw("prompt_history_prompt_id_idx").on($.prompt_id,$.version)]),I0=M$("jobs",{id:q("id").primaryKey(),project_id:q("project_id").references(()=>n0.id),name:q("name").notNull(),description:q("description"),command:q("command").notNull(),prompt_id:q("prompt_id").references(()=>D$.id),prompt_vars:q("prompt_vars",{mode:"json"}).$type(),inject_context:s("inject_context",{mode:"boolean"}).default(!0).notNull(),trigger_type:q("trigger_type",{enum:["one-shot","cron","watch","webhook","manual","bridge-msg"]}).notNull(),cron_expr:q("cron_expr"),watch_path:q("watch_path"),run_at:s("run_at",{mode:"timestamp"}),timeout_secs:s("timeout_secs").default(300).notNull(),max_retries:s("max_retries").default(0).notNull(),overlap:q("overlap",{enum:["skip","queue","kill"]}).default("skip").notNull(),env_vars:q("env_vars",{mode:"json"}).$type(),working_dir:q("working_dir"),notify_on:q("notify_on",{enum:["never","failure","always"]}).default("failure").notNull(),notify_channel:q("notify_channel").default("telegram").notNull(),os_installed:s("os_installed",{mode:"boolean"}).default(!1).notNull(),enabled:s("enabled",{mode:"boolean"}).default(!0).notNull(),last_run_at:s("last_run_at",{mode:"timestamp"}),next_run_at:s("next_run_at",{mode:"timestamp"}),run_count:s("run_count").default(0).notNull(),...bG},($)=>[kG("jobs_name_idx").on($.name)]),E$=M$("job_runs",{id:q("id").primaryKey(),job_id:q("job_id").notNull().references(()=>I0.id,{onDelete:"cascade"}),status:q("status",{enum:["pending","running","success","failed","cancelled","skipped"]}).notNull(),trigger_by:q("trigger_by"),started_at:s("started_at",{mode:"timestamp"}),ended_at:s("ended_at",{mode:"timestamp"}),exit_code:s("exit_code"),stdout:q("stdout"),stderr:q("stderr"),error_msg:q("error_msg"),retry_num:s("retry_num").default(0).notNull(),created_at:s("created_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`)},($)=>[hw("job_runs_job_id_idx").on($.job_id)]),cw=M$("job_run_logs",{id:s("id",{mode:"number"}).primaryKey({autoIncrement:!0}),run_id:q("run_id").notNull().references(()=>E$.id,{onDelete:"cascade"}),ts:s("ts",{mode:"timestamp"}).notNull(),stream:q("stream",{enum:["stdout","stderr"]}).notNull(),line:q("line").notNull()},($)=>[hw("job_run_logs_run_id_idx").on($.run_id,$.ts)]),C1=M$("sessions",{id:q("id").primaryKey(),agent:q("agent").notNull(),agent_version:q("agent_version"),project_id:q("project_id").references(()=>n0.id),job_run_id:q("job_run_id").references(()=>E$.id),summary:q("summary"),events:q("events",{mode:"json"}).$type(),snapshot:q("snapshot"),tokens_used:s("tokens_used"),created_at:s("created_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`)}),X$=M$("bridge_chats",{id:q("id").primaryKey(),platform:q("platform",{enum:["telegram","slack","discord","feishu"]}).notNull(),chat_id:q("chat_id").notNull(),username:q("username"),display_name:q("display_name"),mode:q("mode").default("direct").notNull(),authorized:s("authorized",{mode:"boolean"}).default(!1).notNull(),session_id:q("session_id"),thread_id:q("thread_id"),working_dir:q("working_dir"),updated_at:s("updated_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`),created_at:s("created_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`)},($)=>[kG("bridge_chats_platform_chat_idx").on($.platform,$.chat_id)]),Z8=M$("bridge_messages",{id:q("id").primaryKey(),chat_id:q("chat_id").references(()=>X$.id),direction:q("direction",{enum:["in","out"]}).notNull(),role:q("role",{enum:["system","user","assistant"]}).default("user").notNull(),text:q("text"),job_run_id:q("job_run_id").references(()=>E$.id),gateway_session_id:q("gateway_session_id").references(()=>x$.id),platform_msg_id:q("platform_msg_id"),thread_id:q("thread_id"),metadata:q("metadata",{mode:"json"}).$type(),created_at:s("created_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`)}),XX=M$("bridge_permissions",{id:q("id").primaryKey(),chat_id:q("chat_id"),gateway_session_id:q("gateway_session_id").references(()=>x$.id),job_run_id:q("job_run_id").references(()=>E$.id),tool:q("tool").notNull(),command:q("command"),scope:q("scope",{enum:["once","session"]}).default("once").notNull(),message:q("message"),status:q("status",{enum:["pending","approved","denied","expired"]}).default("pending").notNull(),expires_at:s("expires_at",{mode:"timestamp"}),created_at:s("created_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`),resolved_at:s("resolved_at",{mode:"timestamp"})}),x$=M$("gateway_sessions",{id:q("id").primaryKey(),chat_id:q("chat_id").notNull().references(()=>X$.id,{onDelete:"cascade"}),backend:q("backend",{enum:["claude","codex","cursor"]}).notNull(),mode:q("mode").notNull(),runtime_session_id:q("runtime_session_id"),cwd:q("cwd"),title:q("title"),model:q("model"),status:q("status",{enum:["idle","running","stopped","error"]}).default("idle").notNull(),auto_approve:s("auto_approve",{mode:"boolean"}).default(!1).notNull(),task_id:q("task_id").references(()=>r.id,{onDelete:"set null"}),last_error:q("last_error"),last_activity_at:s("last_activity_at",{mode:"timestamp"}),created_at:s("created_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`),updated_at:s("updated_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`)},($)=>[hw("gateway_sessions_chat_idx").on($.chat_id,$.updated_at)]),M2=M$("webhooks",{id:q("id").primaryKey(),job_id:q("job_id").notNull().references(()=>I0.id,{onDelete:"cascade"}),token:q("token").notNull().unique(),enabled:s("enabled",{mode:"boolean"}).default(!0).notNull(),created_at:s("created_at",{mode:"timestamp"}).notNull().default(T`(unixepoch())`)})});import{Database as R2}from"bun:sqlite";import{mkdirSync as z2}from"fs";import{dirname as T2}from"path";function B2($){$.exec(`
|
|
36
36
|
CREATE TABLE IF NOT EXISTS projects (
|
|
37
37
|
id TEXT PRIMARY KEY,
|
|
38
38
|
name TEXT NOT NULL,
|
|
@@ -359,62 +359,62 @@ Expecting one of '${E.join("', '")}'`);let X=`${$}Help`;return this.on(X,(G)=>{l
|
|
|
359
359
|
);
|
|
360
360
|
|
|
361
361
|
CREATE INDEX IF NOT EXISTS idx_snapshots_session ON session_snapshots(session_id, created_at DESC);
|
|
362
|
-
`);let w=["ALTER TABLE memories ADD COLUMN title TEXT","ALTER TABLE memories ADD COLUMN type TEXT NOT NULL DEFAULT 'fact'","ALTER TABLE session_events ADD COLUMN data_hash TEXT","ALTER TABLE tasks ADD COLUMN progress INTEGER NOT NULL DEFAULT 0","ALTER TABLE tasks ADD COLUMN claimed_by TEXT","ALTER TABLE tasks ADD COLUMN claim_expires_at INTEGER","ALTER TABLE sessions ADD COLUMN agent_version TEXT","ALTER TABLE bridge_chats ADD COLUMN display_name TEXT","ALTER TABLE bridge_chats ADD COLUMN thread_id TEXT","ALTER TABLE bridge_chats ADD COLUMN working_dir TEXT","ALTER TABLE bridge_chats ADD COLUMN updated_at INTEGER NOT NULL DEFAULT (unixepoch())","ALTER TABLE bridge_messages ADD COLUMN role TEXT NOT NULL DEFAULT 'user'","ALTER TABLE bridge_messages ADD COLUMN gateway_session_id TEXT REFERENCES gateway_sessions(id)","ALTER TABLE bridge_messages ADD COLUMN thread_id TEXT","ALTER TABLE bridge_messages ADD COLUMN metadata TEXT","ALTER TABLE bridge_permissions ADD COLUMN gateway_session_id TEXT REFERENCES gateway_sessions(id)","ALTER TABLE bridge_permissions ADD COLUMN scope TEXT NOT NULL DEFAULT 'once'","ALTER TABLE bridge_permissions ADD COLUMN message TEXT","ALTER TABLE bridge_permissions ADD COLUMN expires_at INTEGER","ALTER TABLE gateway_sessions ADD COLUMN auto_approve INTEGER NOT NULL DEFAULT 0","ALTER TABLE gateway_sessions ADD COLUMN task_id TEXT REFERENCES tasks(id) ON DELETE SET NULL","UPDATE jobs SET enabled=0 WHERE trigger_type='repeat'","ALTER TABLE memories ADD COLUMN project_id TEXT REFERENCES projects(id)","ALTER TABLE jobs ADD COLUMN project_id TEXT REFERENCES projects(id)","CREATE UNIQUE INDEX IF NOT EXISTS projects_name_idx ON projects(name)","ALTER TABLE memories ADD COLUMN access_count INTEGER NOT NULL DEFAULT 0","ALTER TABLE memories ADD COLUMN last_accessed_at INTEGER","INSERT INTO comments (id, resource_type, resource_id, content, author, created_at) SELECT id, 'task', task_id, content, author, created_at FROM task_notes WHERE 1","DROP TABLE IF EXISTS task_notes","DROP TABLE IF EXISTS task_comments","DROP TABLE IF EXISTS project_comments"];for(let E of w)try{$.exec(E)}catch{}}function
|
|
362
|
+
`);let w=["ALTER TABLE memories ADD COLUMN title TEXT","ALTER TABLE memories ADD COLUMN type TEXT NOT NULL DEFAULT 'fact'","ALTER TABLE session_events ADD COLUMN data_hash TEXT","ALTER TABLE tasks ADD COLUMN progress INTEGER NOT NULL DEFAULT 0","ALTER TABLE tasks ADD COLUMN claimed_by TEXT","ALTER TABLE tasks ADD COLUMN claim_expires_at INTEGER","ALTER TABLE sessions ADD COLUMN agent_version TEXT","ALTER TABLE bridge_chats ADD COLUMN display_name TEXT","ALTER TABLE bridge_chats ADD COLUMN thread_id TEXT","ALTER TABLE bridge_chats ADD COLUMN working_dir TEXT","ALTER TABLE bridge_chats ADD COLUMN updated_at INTEGER NOT NULL DEFAULT (unixepoch())","ALTER TABLE bridge_messages ADD COLUMN role TEXT NOT NULL DEFAULT 'user'","ALTER TABLE bridge_messages ADD COLUMN gateway_session_id TEXT REFERENCES gateway_sessions(id)","ALTER TABLE bridge_messages ADD COLUMN thread_id TEXT","ALTER TABLE bridge_messages ADD COLUMN metadata TEXT","ALTER TABLE bridge_permissions ADD COLUMN gateway_session_id TEXT REFERENCES gateway_sessions(id)","ALTER TABLE bridge_permissions ADD COLUMN scope TEXT NOT NULL DEFAULT 'once'","ALTER TABLE bridge_permissions ADD COLUMN message TEXT","ALTER TABLE bridge_permissions ADD COLUMN expires_at INTEGER","ALTER TABLE gateway_sessions ADD COLUMN auto_approve INTEGER NOT NULL DEFAULT 0","ALTER TABLE gateway_sessions ADD COLUMN task_id TEXT REFERENCES tasks(id) ON DELETE SET NULL","UPDATE jobs SET enabled=0 WHERE trigger_type='repeat'","ALTER TABLE memories ADD COLUMN project_id TEXT REFERENCES projects(id)","ALTER TABLE jobs ADD COLUMN project_id TEXT REFERENCES projects(id)","CREATE UNIQUE INDEX IF NOT EXISTS projects_name_idx ON projects(name)","ALTER TABLE memories ADD COLUMN access_count INTEGER NOT NULL DEFAULT 0","ALTER TABLE memories ADD COLUMN last_accessed_at INTEGER","INSERT INTO comments (id, resource_type, resource_id, content, author, created_at) SELECT id, 'task', task_id, content, author, created_at FROM task_notes WHERE 1","DROP TABLE IF EXISTS task_notes","DROP TABLE IF EXISTS task_comments","DROP TABLE IF EXISTS project_comments"];for(let E of w)try{$.exec(E)}catch{}}function Q2($){let w=O0(),E=$??w.db.path;if(E!==":memory:")z2(T2(E),{recursive:!0});let X=new R2(E);return X.exec("PRAGMA journal_mode=WAL;"),X.exec("PRAGMA foreign_keys=ON;"),X.exec("PRAGMA synchronous=NORMAL;"),B2(X),rJ(X,{schema:C8})}function x(){if(!_8)_8=Q2();return _8}var _8=null;var y$=R(()=>{C$();MY();d$()});async function A1($){let w=x(),E=await w.query.jobs.findFirst({where:V(I0.id,$.jobId)});if(!E)throw Error(`Job not found: ${$.jobId}`);let X=$.runId??i(),G=new Date;if($.runId)await w.update(E$).set({status:"running",started_at:G}).where(V(E$.id,X));else await w.insert(E$).values({id:X,job_id:E.id,status:"running",trigger_by:$.triggerBy??"manual",started_at:G,created_at:G});await w.update(I0).set({last_run_at:G,run_count:E.run_count+1,updated_at:G}).where(V(I0.id,E.id)),v8.info(`Starting job: ${E.name} [${X}]`);let J={...process.env,ORC_JOB_RUN_ID:X,...E.env_vars??{},...$.envOverrides??{}},A=(E.timeout_secs??300)*1000;try{let D=Bun.spawn({cmd:["sh","-c",E.command],cwd:E.working_dir??process.cwd(),env:J,stdout:"pipe",stderr:"pipe"}),N=[],W=[],O=[],Y=setTimeout(()=>D.kill(),A),H=async(z,B)=>{let Q=new TextDecoder,k="";for await(let v of z){k+=Q.decode(v,{stream:!0});let C=k.split(`
|
|
363
363
|
`);k=C.pop()??"";for(let n of C){if(B==="stdout")N.push(n);else W.push(n);O.push({run_id:X,ts:new Date,stream:B,line:n})}}};await Promise.all([H(D.stdout,"stdout"),H(D.stderr,"stderr"),D.exited]),clearTimeout(Y);let L=D.exitCode??-1,F=new Date,j=L===0;if(O.length>0)await w.insert(cw).values(O);await w.update(E$).set({status:j?"success":"failed",exit_code:L,ended_at:F,stdout:N.join(`
|
|
364
364
|
`).slice(0,65536),stderr:W.join(`
|
|
365
|
-
`).slice(0,16384)}).where(V(E$.id,X));let M=Math.round((F.getTime()-G.getTime())/1000);return await w.insert(C1).values({id:i(),agent:"runner",summary:`Job "${E.name}" ${j?"succeeded":"failed"} in ${M}s (exit ${L})`,job_run_id:X,created_at:F}),
|
|
366
|
-
`);G=D.pop()??"";for(let N of D)if(N.trim())w(N)}if(G.trim())w(G)}finally{E.releaseLock()}}function
|
|
365
|
+
`).slice(0,16384)}).where(V(E$.id,X));let M=Math.round((F.getTime()-G.getTime())/1000);return await w.insert(C1).values({id:i(),agent:"runner",summary:`Job "${E.name}" ${j?"succeeded":"failed"} in ${M}s (exit ${L})`,job_run_id:X,created_at:F}),v8.info(`Job ${E.name} [${X}] ${j?"succeeded":"failed"} (exit ${L})`),X}catch(D){let N=D instanceof Error?D.message:String(D);throw await w.update(E$).set({status:"failed",ended_at:new Date,error_msg:N}).where(V(E$.id,X)),v8.error(`Job ${E.name} [${X}] crashed: ${N}`),D}}var v8;var nw=R(()=>{X1();p$();y$();d$();i$();v8=Z0("runner:executor")});function pJ($,w){zY.set($,w)}function TY($,w){let E=zY.get($);if(!E)throw Error(`No adapter registered for: ${$}`);return E(w)}var zY;var oJ=R(()=>{zY=new Map});async function GX($,w){if(typeof $==="number")return;let E=$.getReader(),X=new TextDecoder,G="";try{while(!0){let{done:J,value:A}=await E.read();if(J)break;G+=X.decode(A,{stream:!0});let D=G.split(`
|
|
366
|
+
`);G=D.pop()??"";for(let N of D)if(N.trim())w(N)}if(G.trim())w(G)}finally{E.releaseLock()}}function JX($,w){if(!$||typeof $==="number")return;$.write(w)}function tJ($){if(!$||typeof $==="number")return;$.end()}function AX($,w){f8.set($,w)}function iJ($){let w=f8.get($);if(!w)throw Error(`No agent backend registered for: ${$}`);return w()}function BY(){return[...f8.keys()]}var f8;var dJ=R(()=>{f8=new Map});var QY={};Ww(QY,{startCodexSession:()=>x8,CodexSession:()=>lJ});function K2(){let $=new Set(["OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_ORG_ID","HOME","USER","PATH","SHELL","TERM","LANG","SSH_AUTH_SOCK","SSH_AGENT_PID","TMPDIR","TMP","TEMP","SYSTEMROOT","WINDIR","COMSPEC"]),w={};for(let[E,X]of Object.entries(process.env))if(X!==void 0&&($.has(E)||E.startsWith("OPENAI_")))w[E]=X;return w}class lJ{id=i();proc=null;eventQueue=[];resolveNext=null;done=!1;state={hasReceivedResult:!1,lastAssistantText:""};runtimeSessionId;permissionResolvers=new Map;stderrLines=[];cwd;constructor($){this.cwd=$.cwd,this.runtimeSessionId=$.runtimeSessionId}async start($,w){let E=["codex","exec","--output-format","stream-json"];if($.runtimeSessionId)E.push("--session",$.runtimeSessionId);if($.model)E.push("--model",$.model);if(E.push(w),this.proc=Bun.spawn({cmd:E,cwd:this.cwd,stdin:"pipe",stdout:"pipe",stderr:"pipe",env:K2()}),this.proc.stdout)GX(this.proc.stdout,(X)=>{try{this.handleLine(JSON.parse(X))}catch{}}).then(()=>{if(!this.state.hasReceivedResult)this.done=!0,this.resolveNext?.(),this.resolveNext=null});if(this.proc.stderr)GX(this.proc.stderr,(X)=>{if(this.stderrLines.push(X),this.stderrLines.length>100)this.stderrLines.shift()});this.watchExit()}handleLine($){let w=String($.type??"");if(w==="assistant_message"||w==="message"){let E=$.content,X=typeof E==="string"?E:Array.isArray(E)?E.map((G)=>String(G.text??"")).join(""):"";if(X)this.state.lastAssistantText=X,this.push({type:"text",data:X});return}if(w==="tool_call"||w==="function_call"){let E=String($.id??i());this.push({type:"tool_use",data:{id:E,name:String($.name??""),input:JSON.stringify($.arguments??$.input??{})}});return}if(w==="tool_result"||w==="function_result"){this.push({type:"tool_result",data:{toolUseId:String($.tool_call_id??$.id??""),content:String($.output??$.content??""),isError:Boolean($.is_error??!1)}});return}if(w==="approval_request"||w==="permission_request"){let E=String($.id??i()),X=String($.tool??$.name??""),G=JSON.stringify($.input??$.command??{}),J=new Promise((A)=>{this.permissionResolvers.set(E,A)});this.push({type:"permission_request",data:{requestId:E,tool:X,command:G}}),J.then((A)=>{if(A!=="denied"){let D=JSON.stringify({type:"approval_response",id:E,approved:!0});JX(this.proc?.stdin,new TextEncoder().encode(`${D}
|
|
367
367
|
`))}});return}if(w==="done"||w==="completed"||w==="session_end"){if(this.state.hasReceivedResult=!0,$.session_id)this.runtimeSessionId=String($.session_id);this.push({type:"result",data:{runtimeSessionId:this.runtimeSessionId,usage:$.usage}}),this.done=!0,this.resolveNext?.(),this.resolveNext=null}}async watchExit(){if(!this.proc)return;let $=await this.proc.exited;if(this.state.hasReceivedResult||this.done)return;if($!==0){let w=this.stderrLines.join(`
|
|
368
|
-
`).trim();this.push({type:"error",data:w||`codex exited with code ${$}`})}this.done=!0,this.resolveNext?.(),this.resolveNext=null}push($){this.eventQueue.push($),this.resolveNext?.(),this.resolveNext=null}async send($){let w=JSON.stringify({type:"user_message",content:$});
|
|
369
|
-
`))}respondPermission($,w){let E=this.permissionResolvers.get($);if(E)this.permissionResolvers.delete($),E(w)}getRuntimeSessionId(){return this.runtimeSessionId}async*events(){while(!0){while(this.eventQueue.length>0)yield this.eventQueue.shift();if(this.done)break;await new Promise(($)=>{this.resolveNext=$})}while(this.eventQueue.length>0)yield this.eventQueue.shift()}alive(){return this.proc?.exitCode===null}async close(){if(!this.proc)return;
|
|
370
|
-
`);if(
|
|
371
|
-
`))}async send($){let w={type:"user",message:{role:"user",content:$}};
|
|
372
|
-
`))}respondPermission($,w){let E=this.permissionResolvers.get($);if(E)this.permissionResolvers.delete($),E(w)}getRuntimeSessionId(){return this.runtimeSessionId}async*events(){while(!0){while(this.eventQueue.length>0)yield this.eventQueue.shift();if(this.done)break;await new Promise(($)=>{this.resolveNext=$})}while(this.eventQueue.length>0)yield this.eventQueue.shift()}alive(){if(!this.proc)return!1;return this.proc.exitCode===null}async close(){if(!this.proc)return;
|
|
373
|
-
${N}`);continue}if(D.type==="permission_request"){let{requestId:N,tool:W,command:O}=D.data;if($.session.auto_approve){w.respondPermission(N,"approved");continue}if(A.pause(),X)X.freeze($.session.id);await
|
|
368
|
+
`).trim();this.push({type:"error",data:w||`codex exited with code ${$}`})}this.done=!0,this.resolveNext?.(),this.resolveNext=null}push($){this.eventQueue.push($),this.resolveNext?.(),this.resolveNext=null}async send($){let w=JSON.stringify({type:"user_message",content:$});JX(this.proc?.stdin,new TextEncoder().encode(`${w}
|
|
369
|
+
`))}respondPermission($,w){let E=this.permissionResolvers.get($);if(E)this.permissionResolvers.delete($),E(w)}getRuntimeSessionId(){return this.runtimeSessionId}async*events(){while(!0){while(this.eventQueue.length>0)yield this.eventQueue.shift();if(this.done)break;await new Promise(($)=>{this.resolveNext=$})}while(this.eventQueue.length>0)yield this.eventQueue.shift()}alive(){return this.proc?.exitCode===null}async close(){if(!this.proc)return;tJ(this.proc.stdin);let $=setTimeout(()=>this.proc?.kill(),I2);try{await this.proc.exited}finally{clearTimeout($)}this.proc=null,this.done=!0,this.resolveNext?.(),this.resolveNext=null}}function V2(){return{name:"codex",async preflight(){if(!Bun.which("codex"))return{ok:!1,error:"codex CLI not found on PATH"};return{ok:!0}},async startSession($){throw Error("Codex sessions require an initial prompt \u2014 use startCodexSession() directly")},async resumeSession($,w){return new lJ({...w,runtimeSessionId:$})},async stop(){}}}async function x8($,w){let E=new lJ($);return await E.start($,w),E}var Je,I2=8000;var sJ=R(()=>{X1();p$();dJ();Je=Z0("agent-runtime:codex");AX("codex",V2)});function S2(){let $=new Set(["ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","HOME","USER","PATH","SHELL","TERM","LANG","LC_ALL","SSH_AUTH_SOCK","SSH_AGENT_PID","XDG_RUNTIME_DIR","TMPDIR","TMP","TEMP","SYSTEMROOT","WINDIR","COMSPEC"]),w={};for(let[E,X]of Object.entries(process.env))if(X!==void 0&&($.has(E)||E.startsWith("ANTHROPIC_")))w[E]=X;return w}function y8(){return Bun.which("claude")??null}function k2($){return/auth|api.key|invalid.key|401|unauthorized/i.test($)}function IY($){if(!$)return"";if(typeof $==="string")return $;return $.map((w)=>w.text??w.thinking??"").join("")}class g8{id=i();proc=null;eventQueue=[];resolveNext=null;done=!1;state={hasReceivedResult:!1,hasStreamedText:!1,lastAssistantText:""};permissionResolvers=new Map;stderrRing=[];cwd;runtimeSessionId;claudePath;constructor($,w){this.cwd=$.cwd,this.runtimeSessionId=$.runtimeSessionId,this.claudePath=w}spawn($=[]){let w=[this.claudePath,"--output-format","stream-json","--input-format","stream-json","--permission-prompt-tool","stdio","--no-color",...$];if(this.proc=Bun.spawn({cmd:w,cwd:this.cwd,stdin:"pipe",stdout:"pipe",stderr:"pipe",env:S2()}),this.proc.stdout)GX(this.proc.stdout,(E)=>{try{this.handleStdoutLine(JSON.parse(E))}catch{}}).then(()=>this.handleEof());if(this.proc.stderr)GX(this.proc.stderr,(E)=>{if(this.stderrRing.push(E),this.stderrRing.length>q2)this.stderrRing.shift()});this.watchExit()}push($){this.eventQueue.push($),this.resolveNext?.(),this.resolveNext=null}handleEof(){if(!this.state.hasReceivedResult)this.done=!0,this.resolveNext?.(),this.resolveNext=null}async start($){let w=$.runtimeSessionId?["--resume",$.runtimeSessionId]:[];this.spawn(w)}handleStdoutLine($){if($.type==="assistant"&&$.message?.content){for(let w of $.message.content){if(w.type==="text"&&w.text)this.state.hasStreamedText=!0,this.state.lastAssistantText=w.text,this.push({type:"text",data:w.text});if(w.type==="thinking"&&w.thinking)this.push({type:"thinking",data:w.thinking})}return}if($.type==="tool_use"){let w=$.id??i();this.push({type:"tool_use",data:{id:w,name:$.name??"",input:JSON.stringify($.input??{})}});return}if($.type==="tool_result"){this.push({type:"tool_result",data:{toolUseId:$.tool_use_id??$.tool_id??"",content:IY($.content),isError:$.is_error??!1}});return}if($.type==="control_request"||$.type==="permission_request"){let w=$.id??i(),E=$.name??IY($.content),X=typeof $.input==="object"&&$.input!==null?JSON.stringify($.input):String($.input??""),G=new Promise((J)=>{this.permissionResolvers.set(w,J)});this.push({type:"permission_request",data:{requestId:w,tool:E,command:X}}),G.then((J)=>this.sendControlResponse(w,J));return}if($.type==="result"||$.subtype==="end_turn"){if(this.state.hasReceivedResult=!0,$.session_id)this.runtimeSessionId=$.session_id;this.push({type:"result",data:{runtimeSessionId:this.runtimeSessionId,usage:$.usage}}),this.done=!0,this.resolveNext?.(),this.resolveNext=null;return}}async watchExit(){if(!this.proc)return;let $=await this.proc.exited;if(this.state.hasReceivedResult||this.done)return;let w=this.stderrRing.join(`
|
|
370
|
+
`);if(k2(w))this.push({type:"error",data:"Authentication failed \u2014 check ANTHROPIC_API_KEY"});else if($!==0){let E=w.trim()||`claude exited with code ${$}`;this.push({type:"error",data:E})}this.done=!0,this.resolveNext?.(),this.resolveNext=null}sendControlResponse($,w){let X={type:"control_response",id:$,result:w==="approved"||w==="session"?"approve":"deny"};JX(this.proc?.stdin,new TextEncoder().encode(`${JSON.stringify(X)}
|
|
371
|
+
`))}async send($){let w={type:"user",message:{role:"user",content:$}};JX(this.proc?.stdin,new TextEncoder().encode(`${JSON.stringify(w)}
|
|
372
|
+
`))}respondPermission($,w){let E=this.permissionResolvers.get($);if(E)this.permissionResolvers.delete($),E(w)}getRuntimeSessionId(){return this.runtimeSessionId}async*events(){while(!0){while(this.eventQueue.length>0)yield this.eventQueue.shift();if(this.done)break;await new Promise(($)=>{this.resolveNext=$})}while(this.eventQueue.length>0)yield this.eventQueue.shift()}alive(){if(!this.proc)return!1;return this.proc.exitCode===null}async close(){if(!this.proc)return;tJ(this.proc.stdin);let $=setTimeout(()=>this.proc?.kill(),P2);try{await this.proc.exited}finally{clearTimeout($)}this.proc=null,this.done=!0,this.resolveNext?.(),this.resolveNext=null}}function b2(){return{name:"claude",async preflight(){let $=y8();if(!$)return{ok:!1,error:"claude CLI not found on PATH"};try{let w=Bun.spawn({cmd:[$,"--version"],stdout:"pipe",stderr:"pipe"}),E=await new Response(w.stdout).text();if(await w.exited,w.exitCode!==0)return{ok:!1,error:"claude --version failed"};let X=/(\d+)\./.exec(E);if((X?Number(X[1]):0)<2)return{ok:!1,error:`claude CLI too old (${E.trim()}), need >= 2.x`};return{ok:!0}}catch(w){return{ok:!1,error:String(w)}}},async startSession($){let w=y8();if(!w)throw Error("claude CLI not found on PATH");let E=new g8($,w);return await E.start($),E},async resumeSession($,w){let E=y8();if(!E)throw Error("claude CLI not found on PATH");let X=new g8({...w,runtimeSessionId:$},E);return await X.start({...w,runtimeSessionId:$}),X},async stop(){}}}var Oe,P2=8000,q2=200;var KY=R(()=>{X1();p$();dJ();Oe=Z0("agent-runtime:claude");AX("claude",b2)});var VY={};Ww(VY,{startCodexSession:()=>x8,registerBackend:()=>AX,listRegisteredBackends:()=>BY,createBackend:()=>iJ});var aJ=R(()=>{sJ();dJ();KY();sJ()});async function PY($){let w=x(),E=`${$.platform}:${$.chatId}`,X=await w.query.bridge_chats.findFirst({where:V(X$.id,E)});if(X)return await w.update(X$).set({username:$.username??X.username,display_name:$.displayName??X.display_name,authorized:$.authorized,thread_id:$.threadId??X.thread_id,updated_at:new Date}).where(V(X$.id,E)),await w.query.bridge_chats.findFirst({where:V(X$.id,E)})??X;return await w.insert(X$).values({id:E,platform:$.platform,chat_id:$.chatId,username:$.username,display_name:$.displayName,authorized:$.authorized,mode:$.mode,thread_id:$.threadId,updated_at:new Date,created_at:new Date}),await w.query.bridge_chats.findFirst({where:V(X$.id,E)})}async function u8($,w){await x().update(X$).set({mode:w,updated_at:new Date}).where(V(X$.id,$))}async function qY($,w){await x().update(X$).set({working_dir:w,updated_at:new Date}).where(V(X$.id,$))}async function DX($){await x().insert(Z8).values({id:i(),chat_id:$.chatKey,direction:$.direction,role:$.role,text:$.text,platform_msg_id:$.platformMessageId,gateway_session_id:$.gatewaySessionId,thread_id:$.threadId,metadata:$.metadata,created_at:new Date})}async function h8($){let w=x(),E=i(),X=new Date;return await w.insert(x$).values({id:E,chat_id:$.chatKey,backend:$.backend,cwd:$.cwd,mode:$.mode,title:$.title,status:"idle",last_activity_at:X,created_at:X,updated_at:X}),await w.update(X$).set({session_id:E,updated_at:X}).where(V(X$.id,$.chatKey)),await w.query.gateway_sessions.findFirst({where:V(x$.id,E)})}async function jw($){let w=x(),E=await w.query.bridge_chats.findFirst({where:V(X$.id,$)});if(E?.session_id){let X=await w.query.gateway_sessions.findFirst({where:V(x$.id,E.session_id)});if(X)return X}return w.query.gateway_sessions.findFirst({where:V(x$.chat_id,$),orderBy:[x0(x$.updated_at)]})}async function NX($){return x().query.gateway_sessions.findMany({where:V(x$.chat_id,$),orderBy:[x0(x$.updated_at)],limit:20})}async function CG($,w){await x().update(X$).set({session_id:w,updated_at:new Date}).where(V(X$.id,$))}async function a1($,w){await x().update(x$).set({...w,updated_at:new Date}).where(V(x$.id,$))}async function SY($){let w=x(),E=i();return await w.insert(XX).values({id:E,chat_id:$.chatKey,gateway_session_id:$.gatewaySessionId,tool:$.tool,command:$.command,message:$.message,scope:$.scope??"once",expires_at:$.expiresAt,created_at:new Date}),await w.query.bridge_permissions.findFirst({where:V(XX.id,E)})}async function c8($){let w=x();if($.length===26)return w.query.bridge_permissions.findFirst({where:V(XX.id,$)});return(await w.query.bridge_permissions.findMany({limit:20,orderBy:[x0(XX.created_at)]})).find((X)=>X.id.endsWith($))}async function _G($){let w=x();if($.length===26)return w.query.tasks.findFirst({where:V(r.id,$)});return(await w.query.tasks.findMany({limit:100,orderBy:[x0(r.updated_at)]})).find((X)=>X.id.endsWith($)||X.id===$)}async function kY($,w){let E=x();if(!await E.query.tasks.findFirst({where:V(r.id,$)}))return null;let G=new Date;if(await E.update(r).set({status:"done",updated_at:G}).where(V(r.id,$)),w)await E.insert(G$).values({id:i(),resource_type:"task",resource_id:$,content:w,author:"human",created_at:G});return await E.query.tasks.findFirst({where:V(r.id,$)})??null}async function bY($,w){let E=x();if(!await E.query.tasks.findFirst({where:V(r.id,$)}))return null;let G=new Date;if(await E.update(r).set({status:"changes_requested",updated_at:G}).where(V(r.id,$)),w)await E.insert(G$).values({id:i(),resource_type:"task",resource_id:$,content:w,author:"human",created_at:G});return await E.query.tasks.findFirst({where:V(r.id,$)})??null}async function n8($=8){return(await x().query.tasks.findMany({limit:$,orderBy:[x0(r.updated_at)]})).filter((X)=>!["done","cancelled"].includes(X.status))}async function ZY($,w=5){let X=await x().query.memories.findMany({limit:w*3,orderBy:[x0(H1.created_at)]}),G=$.toLowerCase().split(/\s+/).filter(Boolean);return X.filter((J)=>G.every((A)=>J.content.toLowerCase().includes(A)||J.title?.toLowerCase().includes(A))).slice(0,w)}async function eJ($){return x().query.jobs.findFirst({where:V(I0.name,$)})}async function m8($=10){return x().query.jobs.findMany({limit:$,orderBy:[x0(I0.updated_at)]})}async function CY(){return x().query.bridge_chats.findMany({where:S0(V(X$.authorized,!0),PJ(X$.platform,["telegram","slack"])),orderBy:[x0(X$.updated_at)]})}async function _Y($,w){await x().update(x$).set({task_id:w,updated_at:new Date}).where(V(x$.id,$))}var vG=R(()=>{X1();y$();d$();i$()});async function vY($,w,E,X){let G=xG.get($.session.id);if(!G||!G.alive())G=await C2($,w),xG.set($.session.id,G);else if($.session.backend==="codex")await G.send(w);else await G.send(w);return await _2($,G,E,X)}async function C2($,w){let E=$.session.backend,X=$.session.runtime_session_id??void 0;if(E==="codex"){let{startCodexSession:A}=await Promise.resolve().then(() => (sJ(),QY));return await A({cwd:$.session.cwd,model:$.session.model??void 0,runtimeSessionId:X},w)}let G=iJ(E);if(X)try{return await G.resumeSession(X,{cwd:$.session.cwd,model:$.session.model??void 0,runtimeSessionId:X})}catch(A){fG.warn(`Failed to resume ${E} session, starting fresh`,{err:A})}let J=await G.startSession({cwd:$.session.cwd,model:$.session.model??void 0});return await J.send(w),J}async function _2($,w,E,X){let G="",J,A=v2($.session.id,w);try{for await(let D of w.events()){if(A.reset(),D.type==="text"){if(G+=D.data,X&&E)await X.update($.session.id,G);continue}if(D.type==="thinking")continue;if(D.type==="tool_use"){let N=`\uD83D\uDD27 ${D.data.name}`;if(X&&E)await X.update($.session.id,`${G}
|
|
373
|
+
${N}`);continue}if(D.type==="permission_request"){let{requestId:N,tool:W,command:O}=D.data;if($.session.auto_approve){w.respondPermission(N,"approved");continue}if(A.pause(),X)X.freeze($.session.id);await SY({chatKey:$.chatKey,gatewaySessionId:$.session.id,tool:W,command:O,scope:"once",expiresAt:new Date(Date.now()+300000)});let Y=[[{label:"\u2705 Allow",value:`perm:approve:${N}`},{label:"\u274C Deny",value:`perm:deny:${N}`},{label:"\uD83D\uDD13 Allow session",value:`perm:session:${N}`}]],H=`\uD83D\uDD11 <b>Permission request</b>
|
|
374
374
|
<b>Tool:</b> ${W}
|
|
375
|
-
<b>Command:</b> <code>${O.slice(0,200)}</code>`;if("sendWithButtons"in $.adapter)await $.adapter.sendWithButtons($.chatId,H,Y,{threadId:$.threadId,parseMode:"html"});else await $.adapter.send($.chatId,H,{threadId:$.threadId,parseMode:"html"});let L=await $.permissionManager.waitFor(N);if(w.respondPermission(N,L?"approved":"denied"),X)X.unfreeze($.session.id);A.resume();continue}if(D.type==="result"){J=D.data.runtimeSessionId;break}if(D.type==="error")throw Error(D.data)}}finally{A.clear()}return{output:G.trim()||"(no output)",runtimeSessionId:J}}function
|
|
376
|
-
`)}async function
|
|
377
|
-
`)}}if(X==="/mode"){if(!G)return{text:"Usage: /mode <direct|agent:claude|agent:codex|agent:cursor|multi|job:name>"};let J=G;return await
|
|
378
|
-
`)}}if(X==="/task"){if(!G)return{text:"Usage: /task <id>"};let J=await
|
|
379
|
-
`),buttons:D}}if(X==="/approve"){if(!G)return{text:"Usage: /approve <task-or-permission-id> [note]"};let[J,...A]=G.split(/\s+/);if(!J)return{text:"Usage: /approve <task-or-permission-id> [note]"};let D=A.join(" ").trim(),N=await
|
|
380
|
-
`)}}if(X==="/run"){if(!G)return{text:"Usage: /run <job-name>"};let J=await
|
|
381
|
-
`)}}if(X==="/sessions"){let J=await
|
|
382
|
-
`)}}if(X==="/session"){let[J,...A]=E.slice(1);if(!J)return{text:"Usage: /session <new|list|switch <id>|stop>"};if(J==="new"){let D=
|
|
383
|
-
`)}}if(J==="switch"){let D=A.join(" ").trim();if(!D)return{text:"Usage: /session switch <id-or-index>"};let N=await
|
|
384
|
-
|
|
385
|
-
Type /help for available commands.`}}async function
|
|
375
|
+
<b>Command:</b> <code>${O.slice(0,200)}</code>`;if("sendWithButtons"in $.adapter)await $.adapter.sendWithButtons($.chatId,H,Y,{threadId:$.threadId,parseMode:"html"});else await $.adapter.send($.chatId,H,{threadId:$.threadId,parseMode:"html"});let L=await $.permissionManager.waitFor(N);if(w.respondPermission(N,L?"approved":"denied"),X)X.unfreeze($.session.id);A.resume();continue}if(D.type==="result"){J=D.data.runtimeSessionId;break}if(D.type==="error")throw Error(D.data)}}finally{A.clear()}return{output:G.trim()||"(no output)",runtimeSessionId:J}}function v2($,w){let E=!1,X=null;function G(){if(X)clearTimeout(X);if(E)return;X=setTimeout(async()=>{fG.warn("Idle timeout \u2014 closing agent session",{sessionId:$}),await w.close().catch(()=>{}),xG.delete($),await a1($,{status:"error",last_error:"Idle timeout",last_activity_at:new Date})},Z2)}return G(),{reset(){G()},pause(){if(E=!0,X)clearTimeout(X),X=null},resume(){E=!1,G()},clear(){if(X)clearTimeout(X),X=null}}}async function fY($){let w=xG.get($);if(w)xG.delete($),await w.close().catch(()=>{})}async function xY(){let{listRegisteredBackends:$,createBackend:w}=await Promise.resolve().then(() => (aJ(),VY));for(let E of $())try{let G=await w(E).preflight();if(!G.ok)fG.warn(`Agent backend preflight failed: ${E}`,{error:G.error});else fG.info(`Agent backend ready: ${E}`)}catch(X){fG.warn(`Agent backend preflight error: ${E}`,{err:X})}}var fG,Z2=600000,xG;var yY=R(()=>{p$();aJ();vG();fG=Z0("gateway:runner"),xG=new Map});class r8{windows=new Map;allow($){let w=Date.now(),E=w-60000,X=this.windows.get($)??[];if(X=X.filter((G)=>G>E),X.length>=20)return this.windows.set($,X),!1;return X.push(w),this.windows.set($,X),!0}clear($){this.windows.delete($)}}function p8($){return $.replace(f2,(w)=>`${"*".repeat(w.length-4)}${w.slice(-4)}`)}var f2;var gY=R(()=>{f2=/\b(sk-[A-Za-z0-9\-_]{20,}|xox[bpoa]-[A-Za-z0-9-]+|ghp_[A-Za-z0-9]{36}|AIza[A-Za-z0-9\-_]{35}|[0-9]{8,10}:[A-Za-z0-9\-_]{35})\b/g});function nY($){if($.endsWith("codex"))return"codex";if($.endsWith("cursor"))return"cursor";return"claude"}function uY($){if($==="running")return"\u26A1";if($==="error")return"\u274C";if($==="stopped")return"\u26D4";return"\uD83D\uDCA4"}function hY($){if($==="critical")return"\uD83D\uDD34";if($==="high")return"\uD83D\uDFE0";if($==="normal")return"\uD83D\uDFE1";return"\u26AA"}function cY($){if($==="done")return"\u2705";if($==="review")return"\uD83D\uDC40";if($==="doing")return"\uD83D\uDD28";if($==="blocked")return"\uD83D\uDEA7";if($==="changes_requested")return"\uD83D\uDD01";if($==="cancelled")return"\u274C";return"\uD83D\uDCCB"}function x2($){let w=["<b>ORC Gateway Commands</b>","","<b>Navigation</b>","/help \u2014 this message","/status \u2014 system overview","/mode [direct|agent:claude|agent:codex|agent:cursor|multi|job:<name>] \u2014 switch mode","/cwd <path> \u2014 set working directory","","<b>Tasks</b>","/tasks \u2014 list active tasks","/task <id> \u2014 task details","/approve <id> [note] \u2014 approve task or permission","/reject <id> [note] \u2014 reject task or deny permission","/assign <task-id> <agent> \u2014 assign task to agent session","","<b>Jobs</b>","/jobs \u2014 list jobs","/run <name> \u2014 trigger a job","","<b>Memory</b>","/mem <query> \u2014 search memories","","<b>Agents</b>","/agent claude|codex|cursor \u2014 switch active agent","/sessions \u2014 list all agent sessions","/session new|list|switch <id>|stop \u2014 session lifecycle"];if($.startsWith("agent:")||$==="multi")w.push("","<i>Current mode: agent \u2014 send any text to the active agent</i>");return w.join(`
|
|
376
|
+
`)}async function mY($){let w=$.rawText.trim();if(!w.startsWith("/"))return null;let E=w.split(/\s+/),X=E[0]??"",G=E.slice(1).join(" ").trim();if(X==="/start"||X==="/help")return{html:x2($.currentMode??"direct")};if(X==="/status"){let J=await n8(5),A=await NX($.chatKey),D=await m8(5),N=await jw($.chatKey),W=["<b>ORC Status</b>","",`Mode: <code>${$.currentMode??"direct"}</code>`,`Working dir: <code>${$.currentWorkingDir??"(unset)"}</code>`,"",`<b>Tasks</b>: ${J.length} active`,`<b>Jobs</b>: ${D.length} defined`,`<b>Sessions</b>: ${A.length} total`];if(N)W.push(`<b>Active session</b>: ${N.backend} ${uY(N.status)} <code>${N.id.slice(-6)}</code>`);return{html:W.join(`
|
|
377
|
+
`)}}if(X==="/mode"){if(!G)return{text:"Usage: /mode <direct|agent:claude|agent:codex|agent:cursor|multi|job:name>"};let J=G;return await u8($.chatKey,J),{text:`Mode updated to ${J}`,mode:J}}if(X==="/cwd"){if(!G)return{text:"Usage: /cwd <absolute-path>"};await qY($.chatKey,G);let J=await jw($.chatKey);if(J)await a1(J.id,{cwd:G});return{text:`Working directory set to ${G}`}}if(X==="/agent"){if(G!=="claude"&&G!=="codex"&&G!=="cursor")return{text:"Usage: /agent <claude|codex|cursor>"};let J=`agent:${G}`;return await u8($.chatKey,J),{text:`Agent mode set to ${J}`,mode:J}}if(X==="/tasks"){let J=await n8();if(J.length===0)return{text:"No active tasks."};let A=["<b>Active Tasks</b>",""];for(let D of J){let N=D.claimed_by?` [${D.claimed_by}]`:"";A.push(`${cY(D.status)} ${hY(D.priority)} <code>${D.id.slice(-6)}</code> ${D.title}${N}`)}return{html:A.join(`
|
|
378
|
+
`)}}if(X==="/task"){if(!G)return{text:"Usage: /task <id>"};let J=await _G(G);if(!J)return{text:`Task not found: ${G}`};let A=[`<b>${J.title}</b>`,`ID: <code>${J.id}</code>`,`Status: ${cY(J.status)} ${J.status}`,`Priority: ${hY(J.priority)} ${J.priority}`];if(J.claimed_by)A.push(`Agent: ${J.claimed_by}`);if(J.body)A.push("",J.body.slice(0,500));let D=J.status==="review"?[[{label:"\u2705 Approve",value:`task:approve:${J.id}`},{label:"\uD83D\uDD01 Changes",value:`task:reject:${J.id}`}]]:void 0;return{html:A.join(`
|
|
379
|
+
`),buttons:D}}if(X==="/approve"){if(!G)return{text:"Usage: /approve <task-or-permission-id> [note]"};let[J,...A]=G.split(/\s+/);if(!J)return{text:"Usage: /approve <task-or-permission-id> [note]"};let D=A.join(" ").trim(),N=await c8(J);if(N)return{text:`Permission ${N.id.slice(-6)} queued for approval \u2014 use the button or wait for agent context.`};let W=await _G(J);if(!W)return{text:`No task or permission found for ${J}`};return await kY(W.id,D||"Approved from gateway"),{text:`\u2705 Approved task [${W.id.slice(-6)}] ${W.title}`}}if(X==="/reject"){if(!G)return{text:"Usage: /reject <task-or-permission-id> [note]"};let[J,...A]=G.split(/\s+/);if(!J)return{text:"Usage: /reject <task-or-permission-id> [note]"};let D=A.join(" ").trim(),N=await c8(J);if(N)return{text:`Permission ${N.id.slice(-6)} denial queued \u2014 use the button or wait for agent context.`};let W=await _G(J);if(!W)return{text:`No task or permission found for ${J}`};return await bY(W.id,D||"Changes requested from gateway"),{text:`\uD83D\uDD01 Changes requested for [${W.id.slice(-6)}] ${W.title}`}}if(X==="/assign"){let[J,A]=G.split(/\s+/);if(!J||!A)return{text:"Usage: /assign <task-id> <agent>"};if(A!=="claude"&&A!=="codex"&&A!=="cursor")return{text:"Agent must be: claude, codex, or cursor"};let D=await _G(J);if(!D)return{text:`Task not found: ${J}`};let W=(await NX($.chatKey)).find((O)=>O.backend===A&&O.status!=="stopped");if(!W)return{text:`No active ${A} session found. Start one with /agent ${A} then send a message.`};return await _Y(W.id,D.id),{text:`Assigned [${D.id.slice(-6)}] ${D.title} \u2192 ${A} session [${W.id.slice(-6)}]`}}if(X==="/jobs"){let J=await m8();if(J.length===0)return{text:"No jobs defined."};let A=["<b>Jobs</b>",""];for(let D of J){let N=D.last_run_at?"ran":"never";A.push(`\u2022 <code>${D.name}</code> (${D.trigger_type}) \u2014 ${N} \xD7 ${D.run_count}`)}return{html:A.join(`
|
|
380
|
+
`)}}if(X==="/run"){if(!G)return{text:"Usage: /run <job-name>"};let J=await eJ(G);if(!J)return{text:`Job not found: ${G}`};let A=await A1({jobId:J.id,triggerBy:"bridge-msg"});return{text:`Triggered ${J.name} \u2192 run ${A.slice(-6)}`}}if(X==="/mem"){if(!G)return{text:"Usage: /mem <query>"};let J=await ZY(G);if(J.length===0)return{text:"No matching memories."};let A=["<b>Memories</b>",""];for(let D of J){let N=D.title??D.content.slice(0,40);A.push(`\u2022 [${D.id.slice(-6)}] <b>${N}</b>`),A.push(` ${D.content.slice(0,120)}${D.content.length>120?"\u2026":""}`)}return{html:A.join(`
|
|
381
|
+
`)}}if(X==="/sessions"){let J=await NX($.chatKey);if(J.length===0)return{text:"No agent sessions yet."};let A=await jw($.chatKey),D=["<b>Agent Sessions</b>",""];for(let N of J){let W=N.id===A?.id?"\u25B6 ":" ",O=N.task_id?` task:${N.task_id.slice(-6)}`:"";if(D.push(`${W}${uY(N.status)} <code>${N.id.slice(-6)}</code> ${N.backend}${O}`),N.cwd)D.push(` cwd: <code>${N.cwd}</code>`)}return{html:D.join(`
|
|
382
|
+
`)}}if(X==="/session"){let[J,...A]=E.slice(1);if(!J)return{text:"Usage: /session <new|list|switch <id>|stop>"};if(J==="new"){let D=nY($.currentMode??"agent:claude"),N=await h8({chatKey:$.chatKey,backend:D,cwd:$.currentWorkingDir??void 0,mode:$.currentMode??`agent:${D}`,title:`Session ${i().slice(-6)}`});return await CG($.chatKey,N.id),{text:`Created and activated ${D} session [${N.id.slice(-6)}]`}}if(J==="list"){let D=await NX($.chatKey);if(D.length===0)return{text:"No gateway sessions yet."};let N=await jw($.chatKey);return{text:D.map((O,Y)=>{return`${O.id===N?.id?"*":" "}${Y+1}. [${O.id.slice(-6)}] ${O.backend} ${O.status} cwd=${O.cwd??"(unset)"}`}).join(`
|
|
383
|
+
`)}}if(J==="switch"){let D=A.join(" ").trim();if(!D)return{text:"Usage: /session switch <id-or-index>"};let N=await NX($.chatKey),W=/^\d+$/.test(D)?N[Number(D)-1]:N.find((O)=>O.id===D||O.id.endsWith(D));if(!W)return{text:`Session not found: ${D}`};return await CG($.chatKey,W.id),{text:`Active session: [${W.id.slice(-6)}] ${W.backend}`}}if(J==="stop"){let D=await jw($.chatKey);if(D)await a1(D.id,{status:"stopped"});return await CG($.chatKey,null),{text:"Cleared active gateway session."}}return{text:"Usage: /session <new|list|switch <id>|stop>"}}return{text:`Unknown command: ${X}
|
|
384
|
+
|
|
385
|
+
Type /help for available commands.`}}async function rY($){let w=await jw($.chatKey),E=nY($.mode);if(w&&w.backend===E&&w.status!=="stopped")return w;let X=await h8({chatKey:$.chatKey,backend:E,cwd:$.cwd??void 0,mode:$.mode,title:`Session ${i().slice(-6)}`});return await CG($.chatKey,X.id),X}var pY=R(()=>{X1();nw();vG()});class o8{pending=new Map;waitFor($){return new Promise((w)=>{let E=setTimeout(()=>{if(this.pending.delete($))w(!1)},300000);this.pending.set($,{resolve:w,timer:E})})}resolve($,w){let E=this.pending.get($);if(!E)return!1;return clearTimeout(E.timer),this.pending.delete($),E.resolve(w),!0}denyAll(){for(let[$,w]of this.pending)clearTimeout(w.timer),w.resolve(!1),this.pending.delete($)}hasPending($){return this.pending.has($)}}class $A{states=new Map;adapter;constructor($){this.adapter=$}static supports($){return"updateMessage"in $&&typeof $.updateMessage==="function"}async init($,w,E,X){this.states.set($,{chatId:w,msgId:E,lastText:X,lastEditAt:0,frozen:!1,degraded:!1,pendingText:null,pendingTimer:null})}async update($,w){let E=this.states.get($);if(!E||E.degraded)return;let X=w.length>3000?`${w.slice(0,3000)}
|
|
386
386
|
\u2026`:w;if(E.frozen){E.pendingText=X;return}let G=Date.now(),J=Math.abs(X.length-E.lastText.length),A=G-E.lastEditAt;if(A<1500||J<30){if(E.pendingText=X,!E.pendingTimer){let D=Math.max(1500-A,100);E.pendingTimer=setTimeout(()=>this.flushPending($),D)}return}await this.doEdit(E,X)}freeze($){let w=this.states.get($);if(w)w.frozen=!0}unfreeze($){let w=this.states.get($);if(!w)return;if(w.frozen=!1,w.pendingText)this.flushPending($)}async finalize($,w){let E=this.states.get($);if(!E)return;if(E.pendingTimer)clearTimeout(E.pendingTimer),E.pendingTimer=null;let X=w.length>3000?`${w.slice(0,3000)}
|
|
387
|
-
\u2026`:w;if(!E.degraded&&X!==E.lastText)await this.doEdit(E,X);this.states.delete($)}cleanup($){let w=this.states.get($);if(w?.pendingTimer)clearTimeout(w.pendingTimer);this.states.delete($)}async flushPending($){let w=this.states.get($);if(!w||!w.pendingText||w.frozen)return;w.pendingTimer=null;let E=w.pendingText;w.pendingText=null,await this.doEdit(w,E)}async doEdit($,w){try{await this.adapter.updateMessage($.chatId,$.msgId,w),$.lastText=w,$.lastEditAt=Date.now()}catch{$.degraded=!0}}}class r8{locked=new Set;tryAcquire($){if(this.locked.has($))return!1;return this.locked.add($),!0}release($){this.locked.delete($)}isLocked($){return this.locked.has($)}}function Z2($){let w=O0(),E=w.gateway.slack.bot_token,X=w.gateway.slack.app_token;if(!E||!X)throw Error("Slack bot_token and app_token are required.");let G=null,J=null,A=!1,D=new Map;function N(M){let z=w.gateway.slack.authorized_users.map(String);return z.length>0&&z.includes(M)}function W(M){let z=Date.now();if(D.has(M))return!0;D.set(M,z);for(let[B,Q]of D)if(z-Q>b2)D.delete(B);return!1}function O(M){if(!M)return!1;return parseFloat(M)*1000<$}async function Y(){let M=await fetch("https://slack.com/api/apps.connections.open",{method:"POST",headers:{Authorization:`Bearer ${X}`}}),z=await M.json();if(!M.ok||!z.ok||!z.url)throw Error(z.error??`Slack socket connect failed (${M.status})`);return new WebSocket(z.url)}async function H(M){if(!G||!M||G.readyState!==WebSocket.OPEN)return;G.send(JSON.stringify({envelope_id:M}))}async function L(M){let z=JSON.parse(M.data);if(await H(z.envelope_id),!J)return;if(z.type==="interactive"){let C=z.payload??{},n=C.actions?.[0]?.value,T0=C.user?.id,f0=C.channel?.id;if(!n||!T0||!f0||!N(T0))return;await J({platform:"slack",chatId:f0,userId:T0,username:C.user?.username,displayName:C.user?.name,text:n,threadId:C.message?.ts});return}let Q=(z.payload??{}).event;if(!Q?.type||!Q.user||!Q.channel)return;if(!N(Q.user))return;if(Q.type!=="app_mention"&&!(Q.type==="message"&&Q.channel_type==="im"))return;if(Q.ts&&W(Q.ts))return;if(O(Q.ts))return;let k=[];for(let C of Q.files??[]){if(!C.url_private_download||!C.mimetype?.startsWith("audio/"))continue;try{let n=await fetch(C.url_private_download,{headers:{Authorization:`Bearer ${E}`}});k.push({kind:"audio",data:new Uint8Array(await n.arrayBuffer()),mimeType:C.mimetype,format:C.mimetype.split("/").at(1)??"mp3"})}catch{}}let v=(Q.text??"").replace(/^<@[^>]+>\s*/,"").trim();await J({platform:"slack",chatId:Q.channel,userId:Q.user,text:v,threadId:Q.thread_ts??Q.ts,platformMessageId:Q.ts,attachments:k.length>0?k:void 0})}async function F(M,z){let B=await fetch(`https://slack.com/api/${M}`,{method:"POST",headers:{Authorization:`Bearer ${E}`,"Content-Type":"application/json; charset=utf-8"},body:JSON.stringify(z)}),Q=await B.json();if(!B.ok||Q.ok!==!0)throw Error(String(Q.error??`Slack request failed (${B.status})`));return Q}function j(M,z){if(!z?.length)return;return[{type:"section",text:{type:"mrkdwn",text:M}},{type:"actions",elements:z.flat().map((B)=>({type:"button",text:{type:"plain_text",text:B.label},value:B.value,action_id:B.value}))}]}return{platform:"slack",async start(M){J=M,A=!0;async function z(){G=await Y(),G.addEventListener("message",(B)=>{L(B)}),G.addEventListener("close",async()=>{if(!A)return;eJ.warn("Slack socket closed; reconnecting in 5s"),await new Promise((B)=>setTimeout(B,5000));try{await z()}catch(B){eJ.error("Slack reconnect failed",{err:B})}}),G.addEventListener("error",(B)=>{eJ.warn("Slack socket error",{err:B})}),eJ.info("Slack gateway adapter connected")}await z()},async stop(){A=!1,G?.close()},async send(M,z,B){let Q=j(z,B?.buttons),k=await F("chat.postMessage",{channel:M,text:z,thread_ts:B?.threadId,...Q?{blocks:Q}:{}});return`${String(k.channel??M)}:${String(k.ts??"")}`},async updateMessage(M,z,B,Q){let[k,v]=z.split(":");if(!k||!v)return;let C=j(B,Q?.buttons);await F("chat.update",{channel:k,ts:v,text:B,...C?{blocks:C}:{}})},async sendWithButtons(M,z,B,Q){let k=j(z,B),v=await F("chat.postMessage",{channel:M,text:z,thread_ts:Q?.threadId,...k?{blocks:k}:{}});return`${String(v.channel??M)}:${String(v.ts??"")}`}}}var eJ,b2=60000;var mY=R(()=>{C$();p$();rJ();eJ=Z0("gateway:slack");mJ("slack",($)=>Z2($))});import{mkdtempSync as C2,readFileSync as _2,rmSync as rY,writeFileSync as v2}from"fs";import{tmpdir as f2}from"os";import{join as p8}from"path";function x2(){return Bun.which("ffmpeg")??null}function oY($){let w=$.toLowerCase();if(w==="oga"||w==="opus")return"ogg";if(w==="mpeg"||w==="mpga")return"mp3";return w}function pY($){let w=$.toLowerCase();if(w==="wav")return"audio/wav";if(w==="ogg"||w==="opus")return"audio/ogg";if(w==="mp4"||w==="m4a")return"audio/mp4";return"audio/mpeg"}function tY($,w,E){let X=x2();if(!X)throw Error("ffmpeg is required for voice support.");let G=C2(p8(f2(),"orc-gateway-")),J=p8(G,`input.${oY(w)}`),A=p8(G,`output.${E}`);v2(J,$);let D=["-y","-i",J];if(E==="mp3")D.push("-ac","1","-ar","16000");if(E==="ogg")D.push("-c:a","libopus");D.push(A);let N=Bun.spawnSync({cmd:[X,...D],stdout:"ignore",stderr:"pipe"});if(N.exitCode!==0){let O=new TextDecoder().decode(N.stderr);throw rY(G,{recursive:!0,force:!0}),Error(O||"ffmpeg conversion failed")}let W=_2(A);return rY(G,{recursive:!0,force:!0}),new Uint8Array(W)}function y2($){return!["mp3","wav","webm","m4a","mp4"].includes($.toLowerCase())}async function iY($){let w=O0();if(!w.speech.enabled)throw Error("Speech support is not enabled.");let{audio:E,format:X}=$;if(y2(X))E=tY(E,X,"mp3"),X="mp3";if(w.speech.provider==="qwen"){let W=w.speech.qwen.api_key;if(!W)throw Error("Qwen speech API key is not configured.");let O=w.speech.qwen.base_url??"https://dashscope.aliyuncs.com/compatible-mode/v1",Y={model:w.speech.qwen.model??"qwen3-asr-flash",messages:[{role:"user",content:[{type:"input_audio",input_audio:{data:`data:${pY(X)};base64,${Buffer.from(E).toString("base64")}`}}]}]},H=await fetch(`${O.replace(/\/$/,"")}/chat/completions`,{method:"POST",headers:{Authorization:`Bearer ${W}`,"Content-Type":"application/json"},body:JSON.stringify(Y)}),L=await H.json();if(!H.ok)throw Error(L.error?.message??`Speech request failed (${H.status})`);return L.choices?.[0]?.message?.content?.trim()??""}let G=w.speech.provider==="groq"?w.speech.groq:w.speech.openai;if(!G.api_key)throw Error("Speech API key is not configured.");let J=G.base_url??(w.speech.provider==="groq"?"https://api.groq.com/openai/v1":"https://api.openai.com/v1"),A=new FormData;if(A.append("model",G.model??(w.speech.provider==="groq"?"whisper-large-v3-turbo":"whisper-1")),A.append("response_format","text"),w.speech.language)A.append("language",w.speech.language);A.append("file",new File([E],`audio.${oY(X)}`,{type:pY(X)}));let D=await fetch(`${J.replace(/\/$/,"")}/audio/transcriptions`,{method:"POST",headers:{Authorization:`Bearer ${G.api_key}`},body:A}),N=await D.text();if(!D.ok)throw Error(N||`Speech request failed (${D.status})`);return N.trim()}async function dY($){let w=O0();if(!w.tts.enabled)throw Error("TTS is not enabled.");if(w.tts.max_text_len>0&&$.length>w.tts.max_text_len)throw Error("Reply is too long for TTS.");if(w.tts.provider==="qwen"){let A=w.tts.qwen.api_key;if(!A)throw Error("Qwen TTS API key is not configured.");let D=await fetch(w.tts.qwen.base_url??"https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation",{method:"POST",headers:{Authorization:`Bearer ${A}`,"Content-Type":"application/json"},body:JSON.stringify({model:w.tts.qwen.model??"qwen3-tts-flash",input:{text:$,voice:w.tts.voice||"Cherry"}})}),N=await D.json();if(!D.ok||N.code)throw Error(N.message??`TTS request failed (${D.status})`);if(!N.output?.audio?.url)throw Error("Qwen TTS did not return audio.");let W=await fetch(N.output.audio.url),O=new Uint8Array(await W.arrayBuffer());return{audio:tY(O,"wav","ogg"),format:"ogg"}}let E=w.tts.openai.api_key??w.speech.openai.api_key;if(!E)throw Error("OpenAI TTS API key is not configured.");let X=w.tts.openai.base_url??"https://api.openai.com/v1",G=await fetch(`${X.replace(/\/$/,"")}/audio/speech`,{method:"POST",headers:{Authorization:`Bearer ${E}`,"Content-Type":"application/json"},body:JSON.stringify({model:w.tts.openai.model??"tts-1",input:$,voice:w.tts.voice||"alloy"})});if(!G.ok)throw Error(await G.text());return{audio:new Uint8Array(await G.arrayBuffer()),format:"mp3"}}var lY=R(()=>{C$()});var EA=Z((WH)=>{Object.defineProperty(WH,"__esModule",{value:!0});WH.matchFilter=g2;WH.parse=AH;WH.preprocess=DH;var sY=new Map;function g2($){var w;let E=Array.isArray($)?$:[$],X=E.join(","),G=(w=sY.get(X))!==null&&w!==void 0?w:(()=>{let J=AH(E),A=u2(J);return sY.set(X,A),A})();return(J)=>G(J)}function AH($){return Array.isArray($)?$.map((w)=>w.split(":")):[$.split(":")]}function u2($){let w=$.flatMap((G)=>h2(G,DH(G))),E=n2(w),X=m2(E);return(G)=>!!X(G.update,G)}function DH($){let w=wA,E=[$].flatMap((X)=>{let[G,J,A]=X;if(!(G in JH))return[X];if(!G&&!J&&!A)return[X];let N=JH[G].map((W)=>[W,J,A]);if(J===void 0)return N;if(J in t8&&(J||A))return N;return N.filter(([W])=>{var O;return!!((O=w[W])===null||O===void 0?void 0:O[J])})}).flatMap((X)=>{let[G,J,A]=X;if(!(J in t8))return[X];if(!J&&!A)return[X];let N=t8[J].map((W)=>[G,W,A]);if(A===void 0)return N;return N.filter(([,W])=>{var O,Y;return!!((Y=(O=w[G])===null||O===void 0?void 0:O[W])===null||Y===void 0?void 0:Y[A])})});if(E.length===0)throw Error(`Shortcuts in '${$.join(":")}' do not expand to any valid filter query`);return E}function h2($,w){if(w.length===0)throw Error("Empty filter query given");let E=w.map(c2).filter((X)=>X!==!0);if(E.length===0)return w;else if(E.length===1)throw Error(E[0]);else throw Error(`Invalid filter query '${$.join(":")}'. There are ${E.length} errors after expanding the contained shortcuts: ${E.join("; ")}`)}function c2($){let[w,E,X,...G]=$;if(w===void 0)return"Empty filter query given";if(!(w in wA)){let D=Object.keys(wA);return`Invalid L1 filter '${w}' given in '${$.join(":")}'. Permitted values are: ${D.map((N)=>`'${N}'`).join(", ")}.`}if(E===void 0)return!0;let J=wA[w];if(!(E in J)){let D=Object.keys(J);return`Invalid L2 filter '${E}' given in '${$.join(":")}'. Permitted values are: ${D.map((N)=>`'${N}'`).join(", ")}.`}if(X===void 0)return!0;let A=J[E];if(!(X in A)){let D=Object.keys(A);return`Invalid L3 filter '${X}' given in '${$.join(":")}'. ${D.length===0?`No further filtering is possible after '${w}:${E}'.`:`Permitted values are: ${D.map((N)=>`'${N}'`).join(", ")}.`}`}if(G.length===0)return!0;return`Cannot filter further than three levels, ':${G.join(":")}' is invalid!`}function n2($){var w,E;let X={};for(let[G,J,A]of $){let D=(w=X[G])!==null&&w!==void 0?w:X[G]={};if(J!==void 0){let N=(E=D[J])!==null&&E!==void 0?E:D[J]=new Set;if(A!==void 0)N.add(A)}}return X}function o8($,w){return(E,X)=>$(E,X)||w(E,X)}function aY($,w){return(E,X)=>{let G=$(E,X);return G&&w(G,X)}}function eY($){return(w,E)=>$(w,E)!=null}function m2($){let w=Object.entries($).map(([E,X])=>{let G=(A)=>A[E],J=Object.entries(X).map(([A,D])=>{let N=(O)=>O[A],W=Array.from(D).map((O)=>{return O==="me"?(H,L)=>{let F=L.me.id;return $H(H,(j)=>j.id===F)}:(H)=>$H(H,(L)=>L[O]||L.type===O)});return W.length===0?eY(N):aY(N,W.reduce(o8))});return J.length===0?eY(G):aY(G,J.reduce(o8))});if(w.length===0)throw Error("Cannot create filter function for empty query");return w.reduce(o8)}function $H($,w){let E=(X)=>X!=null&&w(X);return Array.isArray($)?$.some(E):E($)}var wH={mention:{},hashtag:{},cashtag:{},bot_command:{},url:{},email:{},phone_number:{},bold:{},italic:{},underline:{},strikethrough:{},spoiler:{},blockquote:{},expandable_blockquote:{},code:{},pre:{},text_link:{},text_mention:{},custom_emoji:{}},i8={me:{},is_bot:{},is_premium:{},added_to_attachment_menu:{}},r2={user:{},hidden_user:{},chat:{},channel:{}},p2={is_video:{},is_animated:{},premium_animation:{}},d8={emoji:{},custom_emoji:{},paid:{}},EH={can_be_upgraded:{},is_upgrade_separate:{},is_private:{}},NH={forward_origin:r2,is_topic_message:{},is_automatic_forward:{},business_connection_id:{},text:{},animation:{},audio:{},document:{},paid_media:{},photo:{},sticker:p2,story:{},video:{},video_note:{},voice:{},contact:{},dice:{},game:{},poll:{},venue:{},location:{},entities:wH,caption_entities:wH,caption:{},link_preview_options:{url:{},prefer_small_media:{},prefer_large_media:{},show_above_text:{}},effect_id:{},paid_star_count:{},has_media_spoiler:{},new_chat_title:{},new_chat_photo:{},delete_chat_photo:{},message_auto_delete_timer_changed:{},pinned_message:{},invoice:{},proximity_alert_triggered:{},chat_background_set:{},giveaway_created:{},giveaway:{only_new_members:{},has_public_winners:{}},giveaway_winners:{only_new_members:{},was_refunded:{}},giveaway_completed:{},gift:EH,gift_upgrade_sent:EH,unique_gift:{transfer_star_count:{}},paid_message_price_changed:{},video_chat_scheduled:{},video_chat_started:{},video_chat_ended:{},video_chat_participants_invited:{},web_app_data:{}},$A={...NH,direct_messages_topic:{},chat_owner_left:{new_owner:{}},chat_owner_changd:{},new_chat_members:i8,left_chat_member:i8,group_chat_created:{},supergroup_chat_created:{},migrate_to_chat_id:{},migrate_from_chat_id:{},successful_payment:{},refunded_payment:{},users_shared:{},chat_shared:{},connected_website:{},write_access_allowed:{},passport_data:{},boost_added:{},forum_topic_created:{is_name_implicit:{}},forum_topic_edited:{name:{},icon_custom_emoji_id:{}},forum_topic_closed:{},forum_topic_reopened:{},general_forum_topic_hidden:{},general_forum_topic_unhidden:{},checklist:{others_can_add_tasks:{},others_can_mark_tasks_as_done:{}},checklist_tasks_done:{},checklist_tasks_added:{},suggested_post_info:{},suggested_post_approved:{},suggested_post_approval_failed:{},suggested_post_declined:{},suggested_post_paid:{},suggested_post_refunded:{},sender_boost_count:{}},XH={...NH,channel_chat_created:{},direct_message_price_changed:{},is_paid_post:{}},o2={can_reply:{},is_enabled:{}},t2={old_reaction:d8,new_reaction:d8},i2={reactions:d8},d2={data:{},game_short_name:{}},GH={from:i8},wA={message:$A,edited_message:$A,channel_post:XH,edited_channel_post:XH,business_connection:o2,business_message:$A,edited_business_message:$A,deleted_business_messages:{},inline_query:{},chosen_inline_result:{},callback_query:d2,shipping_query:{},pre_checkout_query:{},poll:{},poll_answer:{},my_chat_member:GH,chat_member:GH,chat_join_request:{},message_reaction:t2,message_reaction_count:i2,chat_boost:{},removed_chat_boost:{},purchased_paid_media:{}},JH={"":["message","channel_post"],msg:["message","channel_post"],edit:["edited_message","edited_channel_post"]},t8={"":["entities","caption_entities"],media:["photo","video"],file:["photo","animation","audio","document","video","video_note","voice","sticker"]}});var GA=Z((OH)=>{Object.defineProperty(OH,"__esModule",{value:!0});OH.Context=void 0;var e2=EA(),e1={filterQuery($){let w=(0,e2.matchFilter)($);return(E)=>w(E)},text($){let w=e1.filterQuery([":text",":caption"]),E=HE($);return(X)=>{var G,J;if(!w(X))return!1;let A=(G=X.message)!==null&&G!==void 0?G:X.channelPost,D=(J=A.text)!==null&&J!==void 0?J:A.caption;return LE(X,D,E)}},command($){let w=e1.filterQuery(":entities:bot_command"),E=new Set,X=new Set;return XA($).forEach((G)=>{if(G.startsWith("/"))throw Error(`Do not include '/' when registering command handlers (use '${G.substring(1)}' not '${G}')`);(G.includes("@")?E:X).add(G)}),(G)=>{var J,A;if(!w(G))return!1;let D=(J=G.message)!==null&&J!==void 0?J:G.channelPost,N=(A=D.text)!==null&&A!==void 0?A:D.caption;return D.entities.some((W)=>{if(W.type!=="bot_command")return!1;if(W.offset!==0)return!1;let O=N.substring(1,W.length);if(X.has(O)||E.has(O))return G.match=N.substring(O.length+1).trimStart(),!0;let Y=O.indexOf("@");if(Y===-1)return!1;let H=O.substring(Y+1).toLowerCase(),L=G.me.username.toLowerCase();if(H!==L)return!1;let F=O.substring(0,Y);if(X.has(F))return G.match=N.substring(O.length+1).trimStart(),!0;return!1})}},reaction($){let w=e1.filterQuery("message_reaction"),E=typeof $==="string"?[{type:"emoji",emoji:$}]:(Array.isArray($)?$:[$]).map((A)=>typeof A==="string"?{type:"emoji",emoji:A}:A),X=new Set(E.filter((A)=>A.type==="emoji").map((A)=>A.emoji)),G=new Set(E.filter((A)=>A.type==="custom_emoji").map((A)=>A.custom_emoji_id)),J=E.some((A)=>A.type==="paid");return(A)=>{if(!w(A))return!1;let{old_reaction:D,new_reaction:N}=A.messageReaction;for(let W of N){let O=!1;if(W.type==="emoji")for(let Y of D){if(Y.type!=="emoji")continue;if(Y.emoji===W.emoji){O=!0;break}}else if(W.type==="custom_emoji")for(let Y of D){if(Y.type!=="custom_emoji")continue;if(Y.custom_emoji_id===W.custom_emoji_id){O=!0;break}}else if(W.type==="paid")for(let Y of D){if(Y.type!=="paid")continue;O=!0;break}if(O)continue;if(W.type==="emoji"){if(X.has(W.emoji))return!0}else if(W.type==="custom_emoji"){if(G.has(W.custom_emoji_id))return!0}else if(W.type==="paid"){if(J)return!0}else return!0}return!1}},chatType($){let w=new Set(XA($));return(E)=>{var X;return((X=E.chat)===null||X===void 0?void 0:X.type)!==void 0&&w.has(E.chat.type)}},callbackQuery($){let w=e1.filterQuery("callback_query:data"),E=HE($);return(X)=>w(X)&&LE(X,X.callbackQuery.data,E)},gameQuery($){let w=e1.filterQuery("callback_query:game_short_name"),E=HE($);return(X)=>w(X)&&LE(X,X.callbackQuery.game_short_name,E)},inlineQuery($){let w=e1.filterQuery("inline_query"),E=HE($);return(X)=>w(X)&&LE(X,X.inlineQuery.query,E)},chosenInlineResult($){let w=e1.filterQuery("chosen_inline_result"),E=HE($);return(X)=>w(X)&&LE(X,X.chosenInlineResult.result_id,E)},preCheckoutQuery($){let w=e1.filterQuery("pre_checkout_query"),E=HE($);return(X)=>w(X)&&LE(X,X.preCheckoutQuery.invoice_payload,E)},shippingQuery($){let w=e1.filterQuery("shipping_query"),E=HE($);return(X)=>w(X)&&LE(X,X.shippingQuery.invoice_payload,E)}};class l${constructor($,w,E){this.update=$,this.api=w,this.me=E}get message(){return this.update.message}get editedMessage(){return this.update.edited_message}get channelPost(){return this.update.channel_post}get editedChannelPost(){return this.update.edited_channel_post}get businessConnection(){return this.update.business_connection}get businessMessage(){return this.update.business_message}get editedBusinessMessage(){return this.update.edited_business_message}get deletedBusinessMessages(){return this.update.deleted_business_messages}get messageReaction(){return this.update.message_reaction}get messageReactionCount(){return this.update.message_reaction_count}get inlineQuery(){return this.update.inline_query}get chosenInlineResult(){return this.update.chosen_inline_result}get callbackQuery(){return this.update.callback_query}get shippingQuery(){return this.update.shipping_query}get preCheckoutQuery(){return this.update.pre_checkout_query}get poll(){return this.update.poll}get pollAnswer(){return this.update.poll_answer}get myChatMember(){return this.update.my_chat_member}get chatMember(){return this.update.chat_member}get chatJoinRequest(){return this.update.chat_join_request}get chatBoost(){return this.update.chat_boost}get removedChatBoost(){return this.update.removed_chat_boost}get purchasedPaidMedia(){return this.update.purchased_paid_media}get msg(){var $,w,E,X,G,J,A;return(J=(G=(X=(E=(w=($=this.message)!==null&&$!==void 0?$:this.editedMessage)!==null&&w!==void 0?w:this.channelPost)!==null&&E!==void 0?E:this.editedChannelPost)!==null&&X!==void 0?X:this.businessMessage)!==null&&G!==void 0?G:this.editedBusinessMessage)!==null&&J!==void 0?J:(A=this.callbackQuery)===null||A===void 0?void 0:A.message}get chat(){var $,w,E,X,G,J,A,D,N;return(N=(D=(A=(J=(G=(X=(E=(w=($=this.msg)!==null&&$!==void 0?$:this.deletedBusinessMessages)!==null&&w!==void 0?w:this.messageReaction)!==null&&E!==void 0?E:this.messageReactionCount)!==null&&X!==void 0?X:this.myChatMember)!==null&&G!==void 0?G:this.chatMember)!==null&&J!==void 0?J:this.chatJoinRequest)!==null&&A!==void 0?A:this.chatBoost)!==null&&D!==void 0?D:this.removedChatBoost)===null||N===void 0?void 0:N.chat}get senderChat(){var $;return($=this.msg)===null||$===void 0?void 0:$.sender_chat}get from(){var $,w,E,X,G,J,A,D,N,W,O,Y,H,L,F,j,M;return(A=(J=(w=($=this.businessConnection)!==null&&$!==void 0?$:this.messageReaction)!==null&&w!==void 0?w:(G=(X=(E=this.chatBoost)===null||E===void 0?void 0:E.boost)!==null&&X!==void 0?X:this.removedChatBoost)===null||G===void 0?void 0:G.source)===null||J===void 0?void 0:J.user)!==null&&A!==void 0?A:(M=(j=(F=(L=(H=(Y=(O=(W=(N=(D=this.callbackQuery)!==null&&D!==void 0?D:this.msg)!==null&&N!==void 0?N:this.inlineQuery)!==null&&W!==void 0?W:this.chosenInlineResult)!==null&&O!==void 0?O:this.shippingQuery)!==null&&Y!==void 0?Y:this.preCheckoutQuery)!==null&&H!==void 0?H:this.myChatMember)!==null&&L!==void 0?L:this.chatMember)!==null&&F!==void 0?F:this.chatJoinRequest)!==null&&j!==void 0?j:this.purchasedPaidMedia)===null||M===void 0?void 0:M.from}get msgId(){var $,w,E,X,G;return(X=(w=($=this.msg)===null||$===void 0?void 0:$.message_id)!==null&&w!==void 0?w:(E=this.messageReaction)===null||E===void 0?void 0:E.message_id)!==null&&X!==void 0?X:(G=this.messageReactionCount)===null||G===void 0?void 0:G.message_id}get chatId(){var $,w,E;return(w=($=this.chat)===null||$===void 0?void 0:$.id)!==null&&w!==void 0?w:(E=this.businessConnection)===null||E===void 0?void 0:E.user_chat_id}get inlineMessageId(){var $,w,E;return(w=($=this.callbackQuery)===null||$===void 0?void 0:$.inline_message_id)!==null&&w!==void 0?w:(E=this.chosenInlineResult)===null||E===void 0?void 0:E.inline_message_id}get businessConnectionId(){var $,w,E,X,G;return(X=(w=($=this.msg)===null||$===void 0?void 0:$.business_connection_id)!==null&&w!==void 0?w:(E=this.businessConnection)===null||E===void 0?void 0:E.id)!==null&&X!==void 0?X:(G=this.deletedBusinessMessages)===null||G===void 0?void 0:G.business_connection_id}entities($){var w,E;let X=this.msg;if(X===void 0)return[];let G=(w=X.text)!==null&&w!==void 0?w:X.caption;if(G===void 0)return[];let J=(E=X.entities)!==null&&E!==void 0?E:X.caption_entities;if(J===void 0)return[];if($!==void 0){let A=new Set(XA($));J=J.filter((D)=>A.has(D.type))}return J.map((A)=>({...A,text:G.substring(A.offset,A.offset+A.length)}))}reactions(){let $=[],w=[],E=[],X=[],G=[],J=[],A=[],D=[],N=!1,W=!1,O=this.messageReaction;if(O!==void 0){let{old_reaction:Y,new_reaction:H}=O;for(let L of H)if(L.type==="emoji")$.push(L.emoji);else if(L.type==="custom_emoji")G.push(L.custom_emoji_id);else if(L.type==="paid")N=W=!0;for(let L of Y)if(L.type==="emoji")X.push(L.emoji);else if(L.type==="custom_emoji")D.push(L.custom_emoji_id);else if(L.type==="paid")W=!1;w.push(...$),J.push(...G);for(let L=0;L<X.length;L++){let F=w.length;if(F===0)break;let j=X[L];for(let M=0;M<F;M++)if(j===w[M]){E.push(j),X.splice(L,1),w.splice(M,1),L--;break}}for(let L=0;L<D.length;L++){let F=J.length;if(F===0)break;let j=D[L];for(let M=0;M<F;M++)if(j===J[M]){A.push(j),D.splice(L,1),J.splice(M,1),L--;break}}}return{emoji:$,emojiAdded:w,emojiKept:E,emojiRemoved:X,customEmoji:G,customEmojiAdded:J,customEmojiKept:A,customEmojiRemoved:D,paid:N,paidAdded:W}}has($){return l$.has.filterQuery($)(this)}hasText($){return l$.has.text($)(this)}hasCommand($){return l$.has.command($)(this)}hasReaction($){return l$.has.reaction($)(this)}hasChatType($){return l$.has.chatType($)(this)}hasCallbackQuery($){return l$.has.callbackQuery($)(this)}hasGameQuery($){return l$.has.gameQuery($)(this)}hasInlineQuery($){return l$.has.inlineQuery($)(this)}hasChosenInlineResult($){return l$.has.chosenInlineResult($)(this)}hasPreCheckoutQuery($){return l$.has.preCheckoutQuery($)(this)}hasShippingQuery($){return l$.has.shippingQuery($)(this)}reply($,w,E){var X;let G=this.msg;return this.api.sendMessage(I(this.chatId,"sendMessage"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithDraft($,w,E){let X=this.msg;return this.api.sendMessageDraft(I(this.chatId,"sendMessageDraft"),this.update.update_id,$,{...(X===null||X===void 0?void 0:X.is_topic_message)?{message_thread_id:X===null||X===void 0?void 0:X.message_thread_id}:{},...w},E)}forwardMessage($,w,E){var X;let G=this.msg;return this.api.forwardMessage($,I(this.chatId,"forwardMessage"),I(this.msgId,"forwardMessage"),{direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}forwardMessages($,w,E,X){var G;let J=this.msg;return this.api.forwardMessages($,I(this.chatId,"forwardMessages"),w,{direct_messages_topic_id:(G=J===null||J===void 0?void 0:J.direct_messages_topic)===null||G===void 0?void 0:G.topic_id,...E},X)}copyMessage($,w,E){var X;let G=this.msg;return this.api.copyMessage($,I(this.chatId,"copyMessage"),I(this.msgId,"copyMessage"),{direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}copyMessages($,w,E,X){var G;let J=this.msg;return this.api.copyMessages($,I(this.chatId,"copyMessages"),w,{direct_messages_topic_id:(G=J===null||J===void 0?void 0:J.direct_messages_topic)===null||G===void 0?void 0:G.topic_id,...E},X)}replyWithPhoto($,w,E){var X;let G=this.msg;return this.api.sendPhoto(I(this.chatId,"sendPhoto"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithAudio($,w,E){var X;let G=this.msg;return this.api.sendAudio(I(this.chatId,"sendAudio"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithDocument($,w,E){var X;let G=this.msg;return this.api.sendDocument(I(this.chatId,"sendDocument"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithVideo($,w,E){var X;let G=this.msg;return this.api.sendVideo(I(this.chatId,"sendVideo"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithAnimation($,w,E){var X;let G=this.msg;return this.api.sendAnimation(I(this.chatId,"sendAnimation"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithVoice($,w,E){var X;let G=this.msg;return this.api.sendVoice(I(this.chatId,"sendVoice"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithVideoNote($,w,E){var X;let G=this.msg;return this.api.sendVideoNote(I(this.chatId,"sendVideoNote"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithMediaGroup($,w,E){var X;let G=this.msg;return this.api.sendMediaGroup(I(this.chatId,"sendMediaGroup"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithLocation($,w,E,X){var G;let J=this.msg;return this.api.sendLocation(I(this.chatId,"sendLocation"),$,w,{business_connection_id:this.businessConnectionId,...(J===null||J===void 0?void 0:J.is_topic_message)?{message_thread_id:J.message_thread_id}:{},direct_messages_topic_id:(G=J===null||J===void 0?void 0:J.direct_messages_topic)===null||G===void 0?void 0:G.topic_id,...E},X)}editMessageLiveLocation($,w,E,X){let G=this.inlineMessageId;return G!==void 0?this.api.editMessageLiveLocationInline(G,$,w,{business_connection_id:this.businessConnectionId,...E},X):this.api.editMessageLiveLocation(I(this.chatId,"editMessageLiveLocation"),I(this.msgId,"editMessageLiveLocation"),$,w,{business_connection_id:this.businessConnectionId,...E},X)}stopMessageLiveLocation($,w){let E=this.inlineMessageId;return E!==void 0?this.api.stopMessageLiveLocationInline(E,{business_connection_id:this.businessConnectionId,...$},w):this.api.stopMessageLiveLocation(I(this.chatId,"stopMessageLiveLocation"),I(this.msgId,"stopMessageLiveLocation"),{business_connection_id:this.businessConnectionId,...$},w)}sendPaidMedia($,w,E,X){var G,J;let A=this.msg;return this.api.sendPaidMedia(I(this.chatId,"sendPaidMedia"),$,w,{business_connection_id:this.businessConnectionId,...(A===null||A===void 0?void 0:A.is_topic_message)?{message_thread_id:A.message_thread_id}:{},direct_messages_topic_id:(J=(G=this.msg)===null||G===void 0?void 0:G.direct_messages_topic)===null||J===void 0?void 0:J.topic_id,...E},X)}replyWithVenue($,w,E,X,G,J){var A;let D=this.msg;return this.api.sendVenue(I(this.chatId,"sendVenue"),$,w,E,X,{business_connection_id:this.businessConnectionId,...(D===null||D===void 0?void 0:D.is_topic_message)?{message_thread_id:D.message_thread_id}:{},direct_messages_topic_id:(A=D===null||D===void 0?void 0:D.direct_messages_topic)===null||A===void 0?void 0:A.topic_id,...G},J)}replyWithContact($,w,E,X){var G;let J=this.msg;return this.api.sendContact(I(this.chatId,"sendContact"),$,w,{business_connection_id:this.businessConnectionId,...(J===null||J===void 0?void 0:J.is_topic_message)?{message_thread_id:J.message_thread_id}:{},direct_messages_topic_id:(G=J===null||J===void 0?void 0:J.direct_messages_topic)===null||G===void 0?void 0:G.topic_id,...E},X)}replyWithPoll($,w,E,X){let G=this.msg;return this.api.sendPoll(I(this.chatId,"sendPoll"),$,w,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},...E},X)}replyWithChecklist($,w,E){return this.api.sendChecklist(I(this.businessConnectionId,"sendChecklist"),I(this.chatId,"sendChecklist"),$,w,E)}editMessageChecklist($,w,E){var X,G,J,A;let D=I(this.msg,"editMessageChecklist"),N=(A=(G=(X=D.checklist_tasks_done)===null||X===void 0?void 0:X.checklist_message)!==null&&G!==void 0?G:(J=D.checklist_tasks_added)===null||J===void 0?void 0:J.checklist_message)!==null&&A!==void 0?A:D;return this.api.editMessageChecklist(I(this.businessConnectionId,"editMessageChecklist"),I(N.chat.id,"editMessageChecklist"),I(N.message_id,"editMessageChecklist"),$,w,E)}replyWithDice($,w,E){var X;let G=this.msg;return this.api.sendDice(I(this.chatId,"sendDice"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithChatAction($,w,E){let X=this.msg;return this.api.sendChatAction(I(this.chatId,"sendChatAction"),$,{business_connection_id:this.businessConnectionId,message_thread_id:X===null||X===void 0?void 0:X.message_thread_id,...w},E)}react($,w,E){return this.api.setMessageReaction(I(this.chatId,"setMessageReaction"),I(this.msgId,"setMessageReaction"),typeof $==="string"?[{type:"emoji",emoji:$}]:(Array.isArray($)?$:[$]).map((X)=>typeof X==="string"?{type:"emoji",emoji:X}:X),w,E)}getUserProfilePhotos($,w){return this.api.getUserProfilePhotos(I(this.from,"getUserProfilePhotos").id,$,w)}getUserProfileAudios($,w){return this.api.getUserProfileAudios(I(this.from,"getUserProfileAudios").id,$,w)}setUserEmojiStatus($,w){return this.api.setUserEmojiStatus(I(this.from,"setUserEmojiStatus").id,$,w)}getUserChatBoosts($,w){return this.api.getUserChatBoosts($!==null&&$!==void 0?$:I(this.chatId,"getUserChatBoosts"),I(this.from,"getUserChatBoosts").id,w)}getUserGifts($,w){return this.api.getUserGifts(I(this.from,"getUserGifts").id,$,w)}getChatGifts($,w){return this.api.getChatGifts(I(this.chatId,"getChatGifts"),$,w)}getBusinessConnection($){return this.api.getBusinessConnection(I(this.businessConnectionId,"getBusinessConnection"),$)}getFile($){var w,E,X,G,J,A;let D=I(this.msg,"getFile"),N=D.photo!==void 0?D.photo[D.photo.length-1]:(A=(J=(G=(X=(E=(w=D.animation)!==null&&w!==void 0?w:D.audio)!==null&&E!==void 0?E:D.document)!==null&&X!==void 0?X:D.video)!==null&&G!==void 0?G:D.video_note)!==null&&J!==void 0?J:D.voice)!==null&&A!==void 0?A:D.sticker;return this.api.getFile(I(N,"getFile").file_id,$)}kickAuthor(...$){return this.banAuthor(...$)}banAuthor($,w){return this.api.banChatMember(I(this.chatId,"banAuthor"),I(this.from,"banAuthor").id,$,w)}kickChatMember(...$){return this.banChatMember(...$)}banChatMember($,w,E){return this.api.banChatMember(I(this.chatId,"banChatMember"),$,w,E)}unbanChatMember($,w,E){return this.api.unbanChatMember(I(this.chatId,"unbanChatMember"),$,w,E)}restrictAuthor($,w,E){return this.api.restrictChatMember(I(this.chatId,"restrictAuthor"),I(this.from,"restrictAuthor").id,$,w,E)}restrictChatMember($,w,E,X){return this.api.restrictChatMember(I(this.chatId,"restrictChatMember"),$,w,E,X)}promoteAuthor($,w){return this.api.promoteChatMember(I(this.chatId,"promoteAuthor"),I(this.from,"promoteAuthor").id,$,w)}promoteChatMember($,w,E){return this.api.promoteChatMember(I(this.chatId,"promoteChatMember"),$,w,E)}setChatAdministratorAuthorCustomTitle($,w){return this.api.setChatAdministratorCustomTitle(I(this.chatId,"setChatAdministratorAuthorCustomTitle"),I(this.from,"setChatAdministratorAuthorCustomTitle").id,$,w)}setChatAdministratorCustomTitle($,w,E){return this.api.setChatAdministratorCustomTitle(I(this.chatId,"setChatAdministratorCustomTitle"),$,w,E)}setAuthorTag($,w){return this.api.setChatMemberTag(I(this.chatId,"setChatMemberTag"),I(this.from,"setChatMemberTag").id,$,w)}setChatMemberTag($,w,E){return this.api.setChatMemberTag(I(this.chatId,"setChatMemberTag"),$,w,E)}banChatSenderChat($,w){return this.api.banChatSenderChat(I(this.chatId,"banChatSenderChat"),$,w)}unbanChatSenderChat($,w){return this.api.unbanChatSenderChat(I(this.chatId,"unbanChatSenderChat"),$,w)}setChatPermissions($,w,E){return this.api.setChatPermissions(I(this.chatId,"setChatPermissions"),$,w,E)}exportChatInviteLink($){return this.api.exportChatInviteLink(I(this.chatId,"exportChatInviteLink"),$)}createChatInviteLink($,w){return this.api.createChatInviteLink(I(this.chatId,"createChatInviteLink"),$,w)}editChatInviteLink($,w,E){return this.api.editChatInviteLink(I(this.chatId,"editChatInviteLink"),$,w,E)}createChatSubscriptionInviteLink($,w,E,X){return this.api.createChatSubscriptionInviteLink(I(this.chatId,"createChatSubscriptionInviteLink"),$,w,E,X)}editChatSubscriptionInviteLink($,w,E){return this.api.editChatSubscriptionInviteLink(I(this.chatId,"editChatSubscriptionInviteLink"),$,w,E)}revokeChatInviteLink($,w){return this.api.revokeChatInviteLink(I(this.chatId,"editChatInviteLink"),$,w)}approveChatJoinRequest($,w){return this.api.approveChatJoinRequest(I(this.chatId,"approveChatJoinRequest"),$,w)}declineChatJoinRequest($,w){return this.api.declineChatJoinRequest(I(this.chatId,"declineChatJoinRequest"),$,w)}approveSuggestedPost($,w){return this.api.approveSuggestedPost(I(this.chatId,"approveSuggestedPost"),I(this.msgId,"approveSuggestedPost"),$,w)}declineSuggestedPost($,w){return this.api.declineSuggestedPost(I(this.chatId,"declineSuggestedPost"),I(this.msgId,"declineSuggestedPost"),$,w)}setChatPhoto($,w){return this.api.setChatPhoto(I(this.chatId,"setChatPhoto"),$,w)}deleteChatPhoto($){return this.api.deleteChatPhoto(I(this.chatId,"deleteChatPhoto"),$)}setChatTitle($,w){return this.api.setChatTitle(I(this.chatId,"setChatTitle"),$,w)}setChatDescription($,w){return this.api.setChatDescription(I(this.chatId,"setChatDescription"),$,w)}pinChatMessage($,w,E){return this.api.pinChatMessage(I(this.chatId,"pinChatMessage"),$,{business_connection_id:this.businessConnectionId,...w},E)}unpinChatMessage($,w,E){return this.api.unpinChatMessage(I(this.chatId,"unpinChatMessage"),$,{business_connection_id:this.businessConnectionId,...w},E)}unpinAllChatMessages($){return this.api.unpinAllChatMessages(I(this.chatId,"unpinAllChatMessages"),$)}leaveChat($){return this.api.leaveChat(I(this.chatId,"leaveChat"),$)}getChat($){return this.api.getChat(I(this.chatId,"getChat"),$)}getChatAdministrators($){return this.api.getChatAdministrators(I(this.chatId,"getChatAdministrators"),$)}getChatMembersCount(...$){return this.getChatMemberCount(...$)}getChatMemberCount($){return this.api.getChatMemberCount(I(this.chatId,"getChatMemberCount"),$)}getAuthor($){return this.api.getChatMember(I(this.chatId,"getAuthor"),I(this.from,"getAuthor").id,$)}getChatMember($,w){return this.api.getChatMember(I(this.chatId,"getChatMember"),$,w)}setChatStickerSet($,w){return this.api.setChatStickerSet(I(this.chatId,"setChatStickerSet"),$,w)}deleteChatStickerSet($){return this.api.deleteChatStickerSet(I(this.chatId,"deleteChatStickerSet"),$)}createForumTopic($,w,E){return this.api.createForumTopic(I(this.chatId,"createForumTopic"),$,w,E)}editForumTopic($,w){let E=I(this.msg,"editForumTopic"),X=I(E.message_thread_id,"editForumTopic");return this.api.editForumTopic(E.chat.id,X,$,w)}closeForumTopic($){let w=I(this.msg,"closeForumTopic"),E=I(w.message_thread_id,"closeForumTopic");return this.api.closeForumTopic(w.chat.id,E,$)}reopenForumTopic($){let w=I(this.msg,"reopenForumTopic"),E=I(w.message_thread_id,"reopenForumTopic");return this.api.reopenForumTopic(w.chat.id,E,$)}deleteForumTopic($){let w=I(this.msg,"deleteForumTopic"),E=I(w.message_thread_id,"deleteForumTopic");return this.api.deleteForumTopic(w.chat.id,E,$)}unpinAllForumTopicMessages($){let w=I(this.msg,"unpinAllForumTopicMessages"),E=I(w.message_thread_id,"unpinAllForumTopicMessages");return this.api.unpinAllForumTopicMessages(w.chat.id,E,$)}editGeneralForumTopic($,w){return this.api.editGeneralForumTopic(I(this.chatId,"editGeneralForumTopic"),$,w)}closeGeneralForumTopic($){return this.api.closeGeneralForumTopic(I(this.chatId,"closeGeneralForumTopic"),$)}reopenGeneralForumTopic($){return this.api.reopenGeneralForumTopic(I(this.chatId,"reopenGeneralForumTopic"),$)}hideGeneralForumTopic($){return this.api.hideGeneralForumTopic(I(this.chatId,"hideGeneralForumTopic"),$)}unhideGeneralForumTopic($){return this.api.unhideGeneralForumTopic(I(this.chatId,"unhideGeneralForumTopic"),$)}unpinAllGeneralForumTopicMessages($){return this.api.unpinAllGeneralForumTopicMessages(I(this.chatId,"unpinAllGeneralForumTopicMessages"),$)}answerCallbackQuery($,w){return this.api.answerCallbackQuery(I(this.callbackQuery,"answerCallbackQuery").id,typeof $==="string"?{text:$}:$,w)}setChatMenuButton($,w){return this.api.setChatMenuButton($,w)}getChatMenuButton($,w){return this.api.getChatMenuButton($,w)}setMyDefaultAdministratorRights($,w){return this.api.setMyDefaultAdministratorRights($,w)}getMyDefaultAdministratorRights($,w){return this.api.getMyDefaultAdministratorRights($,w)}editMessageText($,w,E){var X,G,J,A,D;let N=this.inlineMessageId;return N!==void 0?this.api.editMessageTextInline(N,$,{business_connection_id:this.businessConnectionId,...w},E):this.api.editMessageText(I(this.chatId,"editMessageText"),I((A=(G=(X=this.msg)===null||X===void 0?void 0:X.message_id)!==null&&G!==void 0?G:(J=this.messageReaction)===null||J===void 0?void 0:J.message_id)!==null&&A!==void 0?A:(D=this.messageReactionCount)===null||D===void 0?void 0:D.message_id,"editMessageText"),$,{business_connection_id:this.businessConnectionId,...w},E)}editMessageCaption($,w){var E,X,G,J,A;let D=this.inlineMessageId;return D!==void 0?this.api.editMessageCaptionInline(D,{business_connection_id:this.businessConnectionId,...$},w):this.api.editMessageCaption(I(this.chatId,"editMessageCaption"),I((J=(X=(E=this.msg)===null||E===void 0?void 0:E.message_id)!==null&&X!==void 0?X:(G=this.messageReaction)===null||G===void 0?void 0:G.message_id)!==null&&J!==void 0?J:(A=this.messageReactionCount)===null||A===void 0?void 0:A.message_id,"editMessageCaption"),{business_connection_id:this.businessConnectionId,...$},w)}editMessageMedia($,w,E){var X,G,J,A,D;let N=this.inlineMessageId;return N!==void 0?this.api.editMessageMediaInline(N,$,{business_connection_id:this.businessConnectionId,...w},E):this.api.editMessageMedia(I(this.chatId,"editMessageMedia"),I((A=(G=(X=this.msg)===null||X===void 0?void 0:X.message_id)!==null&&G!==void 0?G:(J=this.messageReaction)===null||J===void 0?void 0:J.message_id)!==null&&A!==void 0?A:(D=this.messageReactionCount)===null||D===void 0?void 0:D.message_id,"editMessageMedia"),$,{business_connection_id:this.businessConnectionId,...w},E)}editMessageReplyMarkup($,w){var E,X,G,J,A;let D=this.inlineMessageId;return D!==void 0?this.api.editMessageReplyMarkupInline(D,{business_connection_id:this.businessConnectionId,...$},w):this.api.editMessageReplyMarkup(I(this.chatId,"editMessageReplyMarkup"),I((J=(X=(E=this.msg)===null||E===void 0?void 0:E.message_id)!==null&&X!==void 0?X:(G=this.messageReaction)===null||G===void 0?void 0:G.message_id)!==null&&J!==void 0?J:(A=this.messageReactionCount)===null||A===void 0?void 0:A.message_id,"editMessageReplyMarkup"),{business_connection_id:this.businessConnectionId,...$},w)}stopPoll($,w){var E,X,G,J,A;return this.api.stopPoll(I(this.chatId,"stopPoll"),I((J=(X=(E=this.msg)===null||E===void 0?void 0:E.message_id)!==null&&X!==void 0?X:(G=this.messageReaction)===null||G===void 0?void 0:G.message_id)!==null&&J!==void 0?J:(A=this.messageReactionCount)===null||A===void 0?void 0:A.message_id,"stopPoll"),{business_connection_id:this.businessConnectionId,...$},w)}deleteMessage($){var w,E,X,G,J;return this.api.deleteMessage(I(this.chatId,"deleteMessage"),I((G=(E=(w=this.msg)===null||w===void 0?void 0:w.message_id)!==null&&E!==void 0?E:(X=this.messageReaction)===null||X===void 0?void 0:X.message_id)!==null&&G!==void 0?G:(J=this.messageReactionCount)===null||J===void 0?void 0:J.message_id,"deleteMessage"),$)}deleteMessages($,w){return this.api.deleteMessages(I(this.chatId,"deleteMessages"),$,w)}deleteBusinessMessages($,w){return this.api.deleteBusinessMessages(I(this.businessConnectionId,"deleteBusinessMessages"),$,w)}setBusinessAccountName($,w,E){return this.api.setBusinessAccountName(I(this.businessConnectionId,"setBusinessAccountName"),$,w,E)}setBusinessAccountUsername($,w){return this.api.setBusinessAccountUsername(I(this.businessConnectionId,"setBusinessAccountUsername"),$,w)}setBusinessAccountBio($,w){return this.api.setBusinessAccountBio(I(this.businessConnectionId,"setBusinessAccountBio"),$,w)}setBusinessAccountProfilePhoto($,w,E){return this.api.setBusinessAccountProfilePhoto(I(this.businessConnectionId,"setBusinessAccountProfilePhoto"),$,w,E)}removeBusinessAccountProfilePhoto($,w){return this.api.removeBusinessAccountProfilePhoto(I(this.businessConnectionId,"removeBusinessAccountProfilePhoto"),$,w)}setBusinessAccountGiftSettings($,w,E){return this.api.setBusinessAccountGiftSettings(I(this.businessConnectionId,"setBusinessAccountGiftSettings"),$,w,E)}getBusinessAccountStarBalance($){return this.api.getBusinessAccountStarBalance(I(this.businessConnectionId,"getBusinessAccountStarBalance"),$)}transferBusinessAccountStars($,w){return this.api.transferBusinessAccountStars(I(this.businessConnectionId,"transferBusinessAccountStars"),$,w)}getBusinessAccountGifts($,w){return this.api.getBusinessAccountGifts(I(this.businessConnectionId,"getBusinessAccountGifts"),$,w)}convertGiftToStars($,w){return this.api.convertGiftToStars(I(this.businessConnectionId,"convertGiftToStars"),$,w)}upgradeGift($,w,E){return this.api.upgradeGift(I(this.businessConnectionId,"upgradeGift"),$,w,E)}transferGift($,w,E,X){return this.api.transferGift(I(this.businessConnectionId,"transferGift"),$,w,E,X)}postStory($,w,E,X){return this.api.postStory(I(this.businessConnectionId,"postStory"),$,w,E,X)}repostStory($,w,E){var X;let G=I((X=this.msg)===null||X===void 0?void 0:X.story,"repostStory");return this.api.repostStory(I(this.businessConnectionId,"repostStory"),G.chat.id,G.id,$,w,E)}editStory($,w,E,X){return this.api.editStory(I(this.businessConnectionId,"editStory"),$,w,E,X)}deleteStory($,w){return this.api.deleteStory(I(this.businessConnectionId,"deleteStory"),$,w)}replyWithSticker($,w,E){var X;let G=this.msg;return this.api.sendSticker(I(this.chatId,"sendSticker"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}getCustomEmojiStickers($){var w,E;return this.api.getCustomEmojiStickers(((E=(w=this.msg)===null||w===void 0?void 0:w.entities)!==null&&E!==void 0?E:[]).filter((X)=>X.type==="custom_emoji").map((X)=>X.custom_emoji_id),$)}replyWithGift($,w,E){return this.api.sendGift(I(this.from,"sendGift").id,$,w,E)}giftPremiumSubscription($,w,E,X){return this.api.giftPremiumSubscription(I(this.from,"giftPremiumSubscription").id,$,w,E,X)}replyWithGiftToChannel($,w,E){return this.api.sendGiftToChannel(I(this.chat,"sendGift").id,$,w,E)}answerInlineQuery($,w,E){return this.api.answerInlineQuery(I(this.inlineQuery,"answerInlineQuery").id,$,w,E)}savePreparedInlineMessage($,w,E){return this.api.savePreparedInlineMessage(I(this.from,"savePreparedInlineMessage").id,$,w,E)}replyWithInvoice($,w,E,X,G,J,A){var D;let N=this.msg;return this.api.sendInvoice(I(this.chatId,"sendInvoice"),$,w,E,X,G,{...(N===null||N===void 0?void 0:N.is_topic_message)?{message_thread_id:N.message_thread_id}:{},direct_messages_topic_id:(D=N===null||N===void 0?void 0:N.direct_messages_topic)===null||D===void 0?void 0:D.topic_id,...J},A)}answerShippingQuery($,w,E){return this.api.answerShippingQuery(I(this.shippingQuery,"answerShippingQuery").id,$,w,E)}answerPreCheckoutQuery($,w,E){return this.api.answerPreCheckoutQuery(I(this.preCheckoutQuery,"answerPreCheckoutQuery").id,$,typeof w==="string"?{error_message:w}:w,E)}refundStarPayment($){var w;return this.api.refundStarPayment(I(this.from,"refundStarPayment").id,I((w=this.msg)===null||w===void 0?void 0:w.successful_payment,"refundStarPayment").telegram_payment_charge_id,$)}editUserStarSubscription($,w,E){return this.api.editUserStarSubscription(I(this.from,"editUserStarSubscription").id,$,w,E)}verifyUser($,w){return this.api.verifyUser(I(this.from,"verifyUser").id,$,w)}verifyChat($,w){return this.api.verifyChat(I(this.chatId,"verifyChat"),$,w)}removeUserVerification($){return this.api.removeUserVerification(I(this.from,"removeUserVerification").id,$)}removeChatVerification($){return this.api.removeChatVerification(I(this.chatId,"removeChatVerification"),$)}readBusinessMessage($){return this.api.readBusinessMessage(I(this.businessConnectionId,"readBusinessMessage"),I(this.chatId,"readBusinessMessage"),I(this.msgId,"readBusinessMessage"),$)}setPassportDataErrors($,w){return this.api.setPassportDataErrors(I(this.from,"setPassportDataErrors").id,$,w)}replyWithGame($,w,E){let X=this.msg;return this.api.sendGame(I(this.chatId,"sendGame"),$,{business_connection_id:this.businessConnectionId,...(X===null||X===void 0?void 0:X.is_topic_message)?{message_thread_id:X.message_thread_id}:{},...w},E)}}OH.Context=l$;l$.has=e1;function I($,w){if($===void 0)throw Error(`Missing information for API call to ${w}`);return $}function HE($){return XA($).map((w)=>typeof w==="string"?(E)=>E===w?w:null:(E)=>E.match(w))}function LE($,w,E){for(let X of E){let G=X(w);if(G)return $.match=G,!0}return!1}function XA($){return Array.isArray($)?$:[$]}});var a8=Z((LH)=>{Object.defineProperty(LH,"__esModule",{value:!0});LH.Composer=LH.BotError=void 0;LH.run=HH;var _1=GA();class s8 extends Error{constructor($,w){super($S($));if(this.error=$,this.ctx=w,this.name="BotError",$ instanceof Error)this.stack=$.stack}}LH.BotError=s8;function $S($){let w;if($ instanceof Error)w=`${$.name} in middleware: ${$.message}`;else{let E=typeof $;switch(w=`Non-error value of type ${E} thrown in middleware`,E){case"bigint":case"boolean":case"number":case"symbol":w+=`: ${$}`;break;case"string":w+=`: ${String($).substring(0,50)}`;break;default:w+="!";break}}return w}function xG($){return typeof $==="function"?$:(w,E)=>$.middleware()(w,E)}function YH($,w){return async(E,X)=>{let G=!1;await $(E,async()=>{if(G)throw Error("`next` already called before!");else G=!0;await w(E,X)})}}function l8($,w){return w()}var wS=()=>Promise.resolve();async function HH($,w){await $(w,wS)}class FE{constructor(...$){this.handler=$.length===0?l8:$.map(xG).reduce(YH)}middleware(){return this.handler}use(...$){let w=new FE(...$);return this.handler=YH(this.handler,xG(w)),w}on($,...w){return this.filter(_1.Context.has.filterQuery($),...w)}hears($,...w){return this.filter(_1.Context.has.text($),...w)}command($,...w){return this.filter(_1.Context.has.command($),...w)}reaction($,...w){return this.filter(_1.Context.has.reaction($),...w)}chatType($,...w){return this.filter(_1.Context.has.chatType($),...w)}callbackQuery($,...w){return this.filter(_1.Context.has.callbackQuery($),...w)}gameQuery($,...w){return this.filter(_1.Context.has.gameQuery($),...w)}inlineQuery($,...w){return this.filter(_1.Context.has.inlineQuery($),...w)}chosenInlineResult($,...w){return this.filter(_1.Context.has.chosenInlineResult($),...w)}preCheckoutQuery($,...w){return this.filter(_1.Context.has.preCheckoutQuery($),...w)}shippingQuery($,...w){return this.filter(_1.Context.has.shippingQuery($),...w)}filter($,...w){let E=new FE(...w);return this.branch($,E,l8),E}drop($,...w){return this.filter(async(E)=>!await $(E),...w)}fork(...$){let w=new FE(...$),E=xG(w);return this.use((X,G)=>Promise.all([G(),HH(E,X)])),w}lazy($){return this.use(async(w,E)=>{let X=await $(w),G=Array.isArray(X)?X:[X];await xG(new FE(...G))(w,E)})}route($,w,E=l8){return this.lazy(async(X)=>{var G;let J=await $(X);return(G=J===void 0||!w[J]?E:w[J])!==null&&G!==void 0?G:[]})}branch($,w,E){return this.lazy(async(X)=>await $(X)?w:E)}errorBoundary($,...w){let E=new FE(...w),X=xG(E);return this.use(async(G,J)=>{let A=!1,D=()=>(A=!0,Promise.resolve());try{await X(G,D)}catch(N){A=!1,await $(new s8(N,G),D)}if(A)await J()}),E}}LH.Composer=FE});var MH=Z((he,jH)=>{var NX=1000,WX=NX*60,OX=WX*60,jE=OX*24,GS=jE*7,JS=jE*365.25;jH.exports=function($,w){w=w||{};var E=typeof $;if(E==="string"&&$.length>0)return AS($);else if(E==="number"&&isFinite($))return w.long?NS($):DS($);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify($))};function AS($){if($=String($),$.length>100)return;var w=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec($);if(!w)return;var E=parseFloat(w[1]),X=(w[2]||"ms").toLowerCase();switch(X){case"years":case"year":case"yrs":case"yr":case"y":return E*JS;case"weeks":case"week":case"w":return E*GS;case"days":case"day":case"d":return E*jE;case"hours":case"hour":case"hrs":case"hr":case"h":return E*OX;case"minutes":case"minute":case"mins":case"min":case"m":return E*WX;case"seconds":case"second":case"secs":case"sec":case"s":return E*NX;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return E;default:return}}function DS($){var w=Math.abs($);if(w>=jE)return Math.round($/jE)+"d";if(w>=OX)return Math.round($/OX)+"h";if(w>=WX)return Math.round($/WX)+"m";if(w>=NX)return Math.round($/NX)+"s";return $+"ms"}function NS($){var w=Math.abs($);if(w>=jE)return JA($,w,jE,"day");if(w>=OX)return JA($,w,OX,"hour");if(w>=WX)return JA($,w,WX,"minute");if(w>=NX)return JA($,w,NX,"second");return $+" ms"}function JA($,w,E,X){var G=w>=E*1.5;return Math.round($/E)+" "+X+(G?"s":"")}});var e8=Z((ce,RH)=>{function WS($){E.debug=E,E.default=E,E.coerce=N,E.disable=A,E.enable=G,E.enabled=D,E.humanize=MH(),E.destroy=W,Object.keys($).forEach((O)=>{E[O]=$[O]}),E.names=[],E.skips=[],E.formatters={};function w(O){let Y=0;for(let H=0;H<O.length;H++)Y=(Y<<5)-Y+O.charCodeAt(H),Y|=0;return E.colors[Math.abs(Y)%E.colors.length]}E.selectColor=w;function E(O){let Y,H=null,L,F;function j(...M){if(!j.enabled)return;let z=j,B=Number(new Date),Q=B-(Y||B);if(z.diff=Q,z.prev=Y,z.curr=B,Y=B,M[0]=E.coerce(M[0]),typeof M[0]!=="string")M.unshift("%O");let k=0;M[0]=M[0].replace(/%([a-zA-Z%])/g,(C,n)=>{if(C==="%%")return"%";k++;let T0=E.formatters[n];if(typeof T0==="function"){let f0=M[k];C=T0.call(z,f0),M.splice(k,1),k--}return C}),E.formatArgs.call(z,M),(z.log||E.log).apply(z,M)}if(j.namespace=O,j.useColors=E.useColors(),j.color=E.selectColor(O),j.extend=X,j.destroy=E.destroy,Object.defineProperty(j,"enabled",{enumerable:!0,configurable:!1,get:()=>{if(H!==null)return H;if(L!==E.namespaces)L=E.namespaces,F=E.enabled(O);return F},set:(M)=>{H=M}}),typeof E.init==="function")E.init(j);return j}function X(O,Y){let H=E(this.namespace+(typeof Y>"u"?":":Y)+O);return H.log=this.log,H}function G(O){E.save(O),E.namespaces=O,E.names=[],E.skips=[];let Y=(typeof O==="string"?O:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let H of Y)if(H[0]==="-")E.skips.push(H.slice(1));else E.names.push(H)}function J(O,Y){let H=0,L=0,F=-1,j=0;while(H<O.length)if(L<Y.length&&(Y[L]===O[H]||Y[L]==="*"))if(Y[L]==="*")F=L,j=H,L++;else H++,L++;else if(F!==-1)L=F+1,j++,H=j;else return!1;while(L<Y.length&&Y[L]==="*")L++;return L===Y.length}function A(){let O=[...E.names,...E.skips.map((Y)=>"-"+Y)].join(",");return E.enable(""),O}function D(O){for(let Y of E.skips)if(J(O,Y))return!1;for(let Y of E.names)if(J(O,Y))return!0;return!1}function N(O){if(O instanceof Error)return O.stack||O.message;return O}function W(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return E.enable(E.load()),E}RH.exports=WS});var TH=Z((zH,AA)=>{zH.formatArgs=US;zH.save=YS;zH.load=HS;zH.useColors=OS;zH.storage=LS();zH.destroy=(()=>{let $=!1;return()=>{if(!$)$=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}})();zH.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function OS(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let $;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&($=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt($[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function US($){if($[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+$[0]+(this.useColors?"%c ":" ")+"+"+AA.exports.humanize(this.diff),!this.useColors)return;let w="color: "+this.color;$.splice(1,0,w,"color: inherit");let E=0,X=0;$[0].replace(/%[a-zA-Z%]/g,(G)=>{if(G==="%%")return;if(E++,G==="%c")X=E}),$.splice(X,0,w)}zH.log=console.debug||console.log||(()=>{});function YS($){try{if($)zH.storage.setItem("debug",$);else zH.storage.removeItem("debug")}catch(w){}}function HS(){let $;try{$=zH.storage.getItem("debug")||zH.storage.getItem("DEBUG")}catch(w){}if(!$&&typeof process<"u"&&"env"in process)$=process.env.DEBUG;return $}function LS(){try{return localStorage}catch($){}}AA.exports=e8()(zH);var{formatters:FS}=AA.exports;FS.j=function($){try{return JSON.stringify($)}catch(w){return"[UnexpectedJSONParseError]: "+w.message}}});var QH={};Ww(QH,{default:()=>SS,createSupportsColor:()=>$N});import wN from"process";import IS from"os";import BH from"tty";function L1($,w=globalThis.Deno?globalThis.Deno.args:wN.argv){let E=$.startsWith("-")?"":$.length===1?"-":"--",X=w.indexOf(E+$),G=w.indexOf("--");return X!==-1&&(G===-1||X<G)}function KS(){if(!("FORCE_COLOR"in m0))return;if(m0.FORCE_COLOR==="true")return 1;if(m0.FORCE_COLOR==="false")return 0;if(m0.FORCE_COLOR.length===0)return 1;let $=Math.min(Number.parseInt(m0.FORCE_COLOR,10),3);if(![0,1,2,3].includes($))return;return $}function VS($){if($===0)return!1;return{level:$,hasBasic:!0,has256:$>=2,has16m:$>=3}}function PS($,{streamIsTTY:w,sniffFlags:E=!0}={}){let X=KS();if(X!==void 0)DA=X;let G=E?DA:X;if(G===0)return 0;if(E){if(L1("color=16m")||L1("color=full")||L1("color=truecolor"))return 3;if(L1("color=256"))return 2}if("TF_BUILD"in m0&&"AGENT_NAME"in m0)return 1;if($&&!w&&G===void 0)return 0;let J=G||0;if(m0.TERM==="dumb")return J;if(wN.platform==="win32"){let A=IS.release().split(".");if(Number(A[0])>=10&&Number(A[2])>=10586)return Number(A[2])>=14931?3:2;return 1}if("CI"in m0){if(["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some((A)=>(A in m0)))return 3;if(["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some((A)=>(A in m0))||m0.CI_NAME==="codeship")return 1;return J}if("TEAMCITY_VERSION"in m0)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(m0.TEAMCITY_VERSION)?1:0;if(m0.COLORTERM==="truecolor")return 3;if(m0.TERM==="xterm-kitty")return 3;if(m0.TERM==="xterm-ghostty")return 3;if(m0.TERM==="wezterm")return 3;if("TERM_PROGRAM"in m0){let A=Number.parseInt((m0.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(m0.TERM_PROGRAM){case"iTerm.app":return A>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(m0.TERM))return 2;if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(m0.TERM))return 1;if("COLORTERM"in m0)return 1;return J}function $N($,w={}){let E=PS($,{streamIsTTY:$&&$.isTTY,...w});return VS(E)}var m0,DA,qS,SS;var IH=R(()=>{({env:m0}=wN);if(L1("no-color")||L1("no-colors")||L1("color=false")||L1("color=never"))DA=0;else if(L1("color")||L1("colors")||L1("color=true")||L1("color=always"))DA=1;qS={stdout:$N({isTTY:BH.isatty(1)}),stderr:$N({isTTY:BH.isatty(2)})},SS=qS});var qH=Z((VH,WA)=>{var kS=V$("tty"),NA=V$("util");VH.init=xS;VH.log=_S;VH.formatArgs=ZS;VH.save=vS;VH.load=fS;VH.useColors=bS;VH.destroy=NA.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");VH.colors=[6,2,3,4,5,1];try{let $=(IH(),kO(QH));if($&&($.stderr||$).level>=2)VH.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221]}catch($){}VH.inspectOpts=Object.keys(process.env).filter(($)=>{return/^debug_/i.test($)}).reduce(($,w)=>{let E=w.substring(6).toLowerCase().replace(/_([a-z])/g,(G,J)=>{return J.toUpperCase()}),X=process.env[w];if(/^(yes|on|true|enabled)$/i.test(X))X=!0;else if(/^(no|off|false|disabled)$/i.test(X))X=!1;else if(X==="null")X=null;else X=Number(X);return $[E]=X,$},{});function bS(){return"colors"in VH.inspectOpts?Boolean(VH.inspectOpts.colors):kS.isatty(process.stderr.fd)}function ZS($){let{namespace:w,useColors:E}=this;if(E){let X=this.color,G="\x1B[3"+(X<8?X:"8;5;"+X),J=` ${G};1m${w} \x1B[0m`;$[0]=J+$[0].split(`
|
|
387
|
+
\u2026`:w;if(!E.degraded&&X!==E.lastText)await this.doEdit(E,X);this.states.delete($)}cleanup($){let w=this.states.get($);if(w?.pendingTimer)clearTimeout(w.pendingTimer);this.states.delete($)}async flushPending($){let w=this.states.get($);if(!w||!w.pendingText||w.frozen)return;w.pendingTimer=null;let E=w.pendingText;w.pendingText=null,await this.doEdit(w,E)}async doEdit($,w){try{await this.adapter.updateMessage($.chatId,$.msgId,w),$.lastText=w,$.lastEditAt=Date.now()}catch{$.degraded=!0}}}class t8{locked=new Set;tryAcquire($){if(this.locked.has($))return!1;return this.locked.add($),!0}release($){this.locked.delete($)}isLocked($){return this.locked.has($)}}function g2($){let w=O0(),E=w.gateway.slack.bot_token,X=w.gateway.slack.app_token;if(!E||!X)throw Error("Slack bot_token and app_token are required.");let G=null,J=null,A=!1,D=new Map;function N(M){let z=w.gateway.slack.authorized_users.map(String);return z.length>0&&z.includes(M)}function W(M){let z=Date.now();if(D.has(M))return!0;D.set(M,z);for(let[B,Q]of D)if(z-Q>y2)D.delete(B);return!1}function O(M){if(!M)return!1;return parseFloat(M)*1000<$}async function Y(){let M=await fetch("https://slack.com/api/apps.connections.open",{method:"POST",headers:{Authorization:`Bearer ${X}`}}),z=await M.json();if(!M.ok||!z.ok||!z.url)throw Error(z.error??`Slack socket connect failed (${M.status})`);return new WebSocket(z.url)}async function H(M){if(!G||!M||G.readyState!==WebSocket.OPEN)return;G.send(JSON.stringify({envelope_id:M}))}async function L(M){let z=JSON.parse(M.data);if(await H(z.envelope_id),!J)return;if(z.type==="interactive"){let C=z.payload??{},n=C.actions?.[0]?.value,T0=C.user?.id,f0=C.channel?.id;if(!n||!T0||!f0||!N(T0))return;await J({platform:"slack",chatId:f0,userId:T0,username:C.user?.username,displayName:C.user?.name,text:n,threadId:C.message?.ts});return}let Q=(z.payload??{}).event;if(!Q?.type||!Q.user||!Q.channel)return;if(!N(Q.user))return;if(Q.type!=="app_mention"&&!(Q.type==="message"&&Q.channel_type==="im"))return;if(Q.ts&&W(Q.ts))return;if(O(Q.ts))return;let k=[];for(let C of Q.files??[]){if(!C.url_private_download||!C.mimetype?.startsWith("audio/"))continue;try{let n=await fetch(C.url_private_download,{headers:{Authorization:`Bearer ${E}`}});k.push({kind:"audio",data:new Uint8Array(await n.arrayBuffer()),mimeType:C.mimetype,format:C.mimetype.split("/").at(1)??"mp3"})}catch{}}let v=(Q.text??"").replace(/^<@[^>]+>\s*/,"").trim();await J({platform:"slack",chatId:Q.channel,userId:Q.user,text:v,threadId:Q.thread_ts??Q.ts,platformMessageId:Q.ts,attachments:k.length>0?k:void 0})}async function F(M,z){let B=await fetch(`https://slack.com/api/${M}`,{method:"POST",headers:{Authorization:`Bearer ${E}`,"Content-Type":"application/json; charset=utf-8"},body:JSON.stringify(z)}),Q=await B.json();if(!B.ok||Q.ok!==!0)throw Error(String(Q.error??`Slack request failed (${B.status})`));return Q}function j(M,z){if(!z?.length)return;return[{type:"section",text:{type:"mrkdwn",text:M}},{type:"actions",elements:z.flat().map((B)=>({type:"button",text:{type:"plain_text",text:B.label},value:B.value,action_id:B.value}))}]}return{platform:"slack",async start(M){J=M,A=!0;async function z(){G=await Y(),G.addEventListener("message",(B)=>{L(B)}),G.addEventListener("close",async()=>{if(!A)return;wA.warn("Slack socket closed; reconnecting in 5s"),await new Promise((B)=>setTimeout(B,5000));try{await z()}catch(B){wA.error("Slack reconnect failed",{err:B})}}),G.addEventListener("error",(B)=>{wA.warn("Slack socket error",{err:B})}),wA.info("Slack gateway adapter connected")}await z()},async stop(){A=!1,G?.close()},async send(M,z,B){let Q=j(z,B?.buttons),k=await F("chat.postMessage",{channel:M,text:z,thread_ts:B?.threadId,...Q?{blocks:Q}:{}});return`${String(k.channel??M)}:${String(k.ts??"")}`},async updateMessage(M,z,B,Q){let[k,v]=z.split(":");if(!k||!v)return;let C=j(B,Q?.buttons);await F("chat.update",{channel:k,ts:v,text:B,...C?{blocks:C}:{}})},async sendWithButtons(M,z,B,Q){let k=j(z,B),v=await F("chat.postMessage",{channel:M,text:z,thread_ts:Q?.threadId,...k?{blocks:k}:{}});return`${String(v.channel??M)}:${String(v.ts??"")}`}}}var wA,y2=60000;var oY=R(()=>{C$();p$();oJ();wA=Z0("gateway:slack");pJ("slack",($)=>g2($))});import{mkdtempSync as u2,readFileSync as h2,rmSync as tY,writeFileSync as c2}from"fs";import{tmpdir as n2}from"os";import{join as i8}from"path";function m2(){return Bun.which("ffmpeg")??null}function dY($){let w=$.toLowerCase();if(w==="oga"||w==="opus")return"ogg";if(w==="mpeg"||w==="mpga")return"mp3";return w}function iY($){let w=$.toLowerCase();if(w==="wav")return"audio/wav";if(w==="ogg"||w==="opus")return"audio/ogg";if(w==="mp4"||w==="m4a")return"audio/mp4";return"audio/mpeg"}function lY($,w,E){let X=m2();if(!X)throw Error("ffmpeg is required for voice support.");let G=u2(i8(n2(),"orc-gateway-")),J=i8(G,`input.${dY(w)}`),A=i8(G,`output.${E}`);c2(J,$);let D=["-y","-i",J];if(E==="mp3")D.push("-ac","1","-ar","16000");if(E==="ogg")D.push("-c:a","libopus");D.push(A);let N=Bun.spawnSync({cmd:[X,...D],stdout:"ignore",stderr:"pipe"});if(N.exitCode!==0){let O=new TextDecoder().decode(N.stderr);throw tY(G,{recursive:!0,force:!0}),Error(O||"ffmpeg conversion failed")}let W=h2(A);return tY(G,{recursive:!0,force:!0}),new Uint8Array(W)}function r2($){return!["mp3","wav","webm","m4a","mp4"].includes($.toLowerCase())}async function sY($){let w=O0();if(!w.speech.enabled)throw Error("Speech support is not enabled.");let{audio:E,format:X}=$;if(r2(X))E=lY(E,X,"mp3"),X="mp3";if(w.speech.provider==="qwen"){let W=w.speech.qwen.api_key;if(!W)throw Error("Qwen speech API key is not configured.");let O=w.speech.qwen.base_url??"https://dashscope.aliyuncs.com/compatible-mode/v1",Y={model:w.speech.qwen.model??"qwen3-asr-flash",messages:[{role:"user",content:[{type:"input_audio",input_audio:{data:`data:${iY(X)};base64,${Buffer.from(E).toString("base64")}`}}]}]},H=await fetch(`${O.replace(/\/$/,"")}/chat/completions`,{method:"POST",headers:{Authorization:`Bearer ${W}`,"Content-Type":"application/json"},body:JSON.stringify(Y)}),L=await H.json();if(!H.ok)throw Error(L.error?.message??`Speech request failed (${H.status})`);return L.choices?.[0]?.message?.content?.trim()??""}let G=w.speech.provider==="groq"?w.speech.groq:w.speech.openai;if(!G.api_key)throw Error("Speech API key is not configured.");let J=G.base_url??(w.speech.provider==="groq"?"https://api.groq.com/openai/v1":"https://api.openai.com/v1"),A=new FormData;if(A.append("model",G.model??(w.speech.provider==="groq"?"whisper-large-v3-turbo":"whisper-1")),A.append("response_format","text"),w.speech.language)A.append("language",w.speech.language);A.append("file",new File([E],`audio.${dY(X)}`,{type:iY(X)}));let D=await fetch(`${J.replace(/\/$/,"")}/audio/transcriptions`,{method:"POST",headers:{Authorization:`Bearer ${G.api_key}`},body:A}),N=await D.text();if(!D.ok)throw Error(N||`Speech request failed (${D.status})`);return N.trim()}async function aY($){let w=O0();if(!w.tts.enabled)throw Error("TTS is not enabled.");if(w.tts.max_text_len>0&&$.length>w.tts.max_text_len)throw Error("Reply is too long for TTS.");if(w.tts.provider==="qwen"){let A=w.tts.qwen.api_key;if(!A)throw Error("Qwen TTS API key is not configured.");let D=await fetch(w.tts.qwen.base_url??"https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation",{method:"POST",headers:{Authorization:`Bearer ${A}`,"Content-Type":"application/json"},body:JSON.stringify({model:w.tts.qwen.model??"qwen3-tts-flash",input:{text:$,voice:w.tts.voice||"Cherry"}})}),N=await D.json();if(!D.ok||N.code)throw Error(N.message??`TTS request failed (${D.status})`);if(!N.output?.audio?.url)throw Error("Qwen TTS did not return audio.");let W=await fetch(N.output.audio.url),O=new Uint8Array(await W.arrayBuffer());return{audio:lY(O,"wav","ogg"),format:"ogg"}}let E=w.tts.openai.api_key??w.speech.openai.api_key;if(!E)throw Error("OpenAI TTS API key is not configured.");let X=w.tts.openai.base_url??"https://api.openai.com/v1",G=await fetch(`${X.replace(/\/$/,"")}/audio/speech`,{method:"POST",headers:{Authorization:`Bearer ${E}`,"Content-Type":"application/json"},body:JSON.stringify({model:w.tts.openai.model??"tts-1",input:$,voice:w.tts.voice||"alloy"})});if(!G.ok)throw Error(await G.text());return{audio:new Uint8Array(await G.arrayBuffer()),format:"mp3"}}var eY=R(()=>{C$()});var GA=Z((YH)=>{Object.defineProperty(YH,"__esModule",{value:!0});YH.matchFilter=p2;YH.parse=WH;YH.preprocess=OH;var $H=new Map;function p2($){var w;let E=Array.isArray($)?$:[$],X=E.join(","),G=(w=$H.get(X))!==null&&w!==void 0?w:(()=>{let J=WH(E),A=o2(J);return $H.set(X,A),A})();return(J)=>G(J)}function WH($){return Array.isArray($)?$.map((w)=>w.split(":")):[$.split(":")]}function o2($){let w=$.flatMap((G)=>t2(G,OH(G))),E=d2(w),X=l2(E);return(G)=>!!X(G.update,G)}function OH($){let w=XA,E=[$].flatMap((X)=>{let[G,J,A]=X;if(!(G in NH))return[X];if(!G&&!J&&!A)return[X];let N=NH[G].map((W)=>[W,J,A]);if(J===void 0)return N;if(J in l8&&(J||A))return N;return N.filter(([W])=>{var O;return!!((O=w[W])===null||O===void 0?void 0:O[J])})}).flatMap((X)=>{let[G,J,A]=X;if(!(J in l8))return[X];if(!J&&!A)return[X];let N=l8[J].map((W)=>[G,W,A]);if(A===void 0)return N;return N.filter(([,W])=>{var O,Y;return!!((Y=(O=w[G])===null||O===void 0?void 0:O[W])===null||Y===void 0?void 0:Y[A])})});if(E.length===0)throw Error(`Shortcuts in '${$.join(":")}' do not expand to any valid filter query`);return E}function t2($,w){if(w.length===0)throw Error("Empty filter query given");let E=w.map(i2).filter((X)=>X!==!0);if(E.length===0)return w;else if(E.length===1)throw Error(E[0]);else throw Error(`Invalid filter query '${$.join(":")}'. There are ${E.length} errors after expanding the contained shortcuts: ${E.join("; ")}`)}function i2($){let[w,E,X,...G]=$;if(w===void 0)return"Empty filter query given";if(!(w in XA)){let D=Object.keys(XA);return`Invalid L1 filter '${w}' given in '${$.join(":")}'. Permitted values are: ${D.map((N)=>`'${N}'`).join(", ")}.`}if(E===void 0)return!0;let J=XA[w];if(!(E in J)){let D=Object.keys(J);return`Invalid L2 filter '${E}' given in '${$.join(":")}'. Permitted values are: ${D.map((N)=>`'${N}'`).join(", ")}.`}if(X===void 0)return!0;let A=J[E];if(!(X in A)){let D=Object.keys(A);return`Invalid L3 filter '${X}' given in '${$.join(":")}'. ${D.length===0?`No further filtering is possible after '${w}:${E}'.`:`Permitted values are: ${D.map((N)=>`'${N}'`).join(", ")}.`}`}if(G.length===0)return!0;return`Cannot filter further than three levels, ':${G.join(":")}' is invalid!`}function d2($){var w,E;let X={};for(let[G,J,A]of $){let D=(w=X[G])!==null&&w!==void 0?w:X[G]={};if(J!==void 0){let N=(E=D[J])!==null&&E!==void 0?E:D[J]=new Set;if(A!==void 0)N.add(A)}}return X}function d8($,w){return(E,X)=>$(E,X)||w(E,X)}function wH($,w){return(E,X)=>{let G=$(E,X);return G&&w(G,X)}}function EH($){return(w,E)=>$(w,E)!=null}function l2($){let w=Object.entries($).map(([E,X])=>{let G=(A)=>A[E],J=Object.entries(X).map(([A,D])=>{let N=(O)=>O[A],W=Array.from(D).map((O)=>{return O==="me"?(H,L)=>{let F=L.me.id;return XH(H,(j)=>j.id===F)}:(H)=>XH(H,(L)=>L[O]||L.type===O)});return W.length===0?EH(N):wH(N,W.reduce(d8))});return J.length===0?EH(G):wH(G,J.reduce(d8))});if(w.length===0)throw Error("Cannot create filter function for empty query");return w.reduce(d8)}function XH($,w){let E=(X)=>X!=null&&w(X);return Array.isArray($)?$.some(E):E($)}var GH={mention:{},hashtag:{},cashtag:{},bot_command:{},url:{},email:{},phone_number:{},bold:{},italic:{},underline:{},strikethrough:{},spoiler:{},blockquote:{},expandable_blockquote:{},code:{},pre:{},text_link:{},text_mention:{},custom_emoji:{}},s8={me:{},is_bot:{},is_premium:{},added_to_attachment_menu:{}},s2={user:{},hidden_user:{},chat:{},channel:{}},a2={is_video:{},is_animated:{},premium_animation:{}},a8={emoji:{},custom_emoji:{},paid:{}},JH={can_be_upgraded:{},is_upgrade_separate:{},is_private:{}},UH={forward_origin:s2,is_topic_message:{},is_automatic_forward:{},business_connection_id:{},text:{},animation:{},audio:{},document:{},paid_media:{},photo:{},sticker:a2,story:{},video:{},video_note:{},voice:{},contact:{},dice:{},game:{},poll:{},venue:{},location:{},entities:GH,caption_entities:GH,caption:{},link_preview_options:{url:{},prefer_small_media:{},prefer_large_media:{},show_above_text:{}},effect_id:{},paid_star_count:{},has_media_spoiler:{},new_chat_title:{},new_chat_photo:{},delete_chat_photo:{},message_auto_delete_timer_changed:{},pinned_message:{},invoice:{},proximity_alert_triggered:{},chat_background_set:{},giveaway_created:{},giveaway:{only_new_members:{},has_public_winners:{}},giveaway_winners:{only_new_members:{},was_refunded:{}},giveaway_completed:{},gift:JH,gift_upgrade_sent:JH,unique_gift:{transfer_star_count:{}},paid_message_price_changed:{},video_chat_scheduled:{},video_chat_started:{},video_chat_ended:{},video_chat_participants_invited:{},web_app_data:{}},EA={...UH,direct_messages_topic:{},chat_owner_left:{new_owner:{}},chat_owner_changd:{},new_chat_members:s8,left_chat_member:s8,group_chat_created:{},supergroup_chat_created:{},migrate_to_chat_id:{},migrate_from_chat_id:{},successful_payment:{},refunded_payment:{},users_shared:{},chat_shared:{},connected_website:{},write_access_allowed:{},passport_data:{},boost_added:{},forum_topic_created:{is_name_implicit:{}},forum_topic_edited:{name:{},icon_custom_emoji_id:{}},forum_topic_closed:{},forum_topic_reopened:{},general_forum_topic_hidden:{},general_forum_topic_unhidden:{},checklist:{others_can_add_tasks:{},others_can_mark_tasks_as_done:{}},checklist_tasks_done:{},checklist_tasks_added:{},suggested_post_info:{},suggested_post_approved:{},suggested_post_approval_failed:{},suggested_post_declined:{},suggested_post_paid:{},suggested_post_refunded:{},sender_boost_count:{}},AH={...UH,channel_chat_created:{},direct_message_price_changed:{},is_paid_post:{}},e2={can_reply:{},is_enabled:{}},$S={old_reaction:a8,new_reaction:a8},wS={reactions:a8},ES={data:{},game_short_name:{}},DH={from:s8},XA={message:EA,edited_message:EA,channel_post:AH,edited_channel_post:AH,business_connection:e2,business_message:EA,edited_business_message:EA,deleted_business_messages:{},inline_query:{},chosen_inline_result:{},callback_query:ES,shipping_query:{},pre_checkout_query:{},poll:{},poll_answer:{},my_chat_member:DH,chat_member:DH,chat_join_request:{},message_reaction:$S,message_reaction_count:wS,chat_boost:{},removed_chat_boost:{},purchased_paid_media:{}},NH={"":["message","channel_post"],msg:["message","channel_post"],edit:["edited_message","edited_channel_post"]},l8={"":["entities","caption_entities"],media:["photo","video"],file:["photo","animation","audio","document","video","video_note","voice","sticker"]}});var AA=Z((HH)=>{Object.defineProperty(HH,"__esModule",{value:!0});HH.Context=void 0;var AS=GA(),e1={filterQuery($){let w=(0,AS.matchFilter)($);return(E)=>w(E)},text($){let w=e1.filterQuery([":text",":caption"]),E=HE($);return(X)=>{var G,J;if(!w(X))return!1;let A=(G=X.message)!==null&&G!==void 0?G:X.channelPost,D=(J=A.text)!==null&&J!==void 0?J:A.caption;return LE(X,D,E)}},command($){let w=e1.filterQuery(":entities:bot_command"),E=new Set,X=new Set;return JA($).forEach((G)=>{if(G.startsWith("/"))throw Error(`Do not include '/' when registering command handlers (use '${G.substring(1)}' not '${G}')`);(G.includes("@")?E:X).add(G)}),(G)=>{var J,A;if(!w(G))return!1;let D=(J=G.message)!==null&&J!==void 0?J:G.channelPost,N=(A=D.text)!==null&&A!==void 0?A:D.caption;return D.entities.some((W)=>{if(W.type!=="bot_command")return!1;if(W.offset!==0)return!1;let O=N.substring(1,W.length);if(X.has(O)||E.has(O))return G.match=N.substring(O.length+1).trimStart(),!0;let Y=O.indexOf("@");if(Y===-1)return!1;let H=O.substring(Y+1).toLowerCase(),L=G.me.username.toLowerCase();if(H!==L)return!1;let F=O.substring(0,Y);if(X.has(F))return G.match=N.substring(O.length+1).trimStart(),!0;return!1})}},reaction($){let w=e1.filterQuery("message_reaction"),E=typeof $==="string"?[{type:"emoji",emoji:$}]:(Array.isArray($)?$:[$]).map((A)=>typeof A==="string"?{type:"emoji",emoji:A}:A),X=new Set(E.filter((A)=>A.type==="emoji").map((A)=>A.emoji)),G=new Set(E.filter((A)=>A.type==="custom_emoji").map((A)=>A.custom_emoji_id)),J=E.some((A)=>A.type==="paid");return(A)=>{if(!w(A))return!1;let{old_reaction:D,new_reaction:N}=A.messageReaction;for(let W of N){let O=!1;if(W.type==="emoji")for(let Y of D){if(Y.type!=="emoji")continue;if(Y.emoji===W.emoji){O=!0;break}}else if(W.type==="custom_emoji")for(let Y of D){if(Y.type!=="custom_emoji")continue;if(Y.custom_emoji_id===W.custom_emoji_id){O=!0;break}}else if(W.type==="paid")for(let Y of D){if(Y.type!=="paid")continue;O=!0;break}if(O)continue;if(W.type==="emoji"){if(X.has(W.emoji))return!0}else if(W.type==="custom_emoji"){if(G.has(W.custom_emoji_id))return!0}else if(W.type==="paid"){if(J)return!0}else return!0}return!1}},chatType($){let w=new Set(JA($));return(E)=>{var X;return((X=E.chat)===null||X===void 0?void 0:X.type)!==void 0&&w.has(E.chat.type)}},callbackQuery($){let w=e1.filterQuery("callback_query:data"),E=HE($);return(X)=>w(X)&&LE(X,X.callbackQuery.data,E)},gameQuery($){let w=e1.filterQuery("callback_query:game_short_name"),E=HE($);return(X)=>w(X)&&LE(X,X.callbackQuery.game_short_name,E)},inlineQuery($){let w=e1.filterQuery("inline_query"),E=HE($);return(X)=>w(X)&&LE(X,X.inlineQuery.query,E)},chosenInlineResult($){let w=e1.filterQuery("chosen_inline_result"),E=HE($);return(X)=>w(X)&&LE(X,X.chosenInlineResult.result_id,E)},preCheckoutQuery($){let w=e1.filterQuery("pre_checkout_query"),E=HE($);return(X)=>w(X)&&LE(X,X.preCheckoutQuery.invoice_payload,E)},shippingQuery($){let w=e1.filterQuery("shipping_query"),E=HE($);return(X)=>w(X)&&LE(X,X.shippingQuery.invoice_payload,E)}};class l${constructor($,w,E){this.update=$,this.api=w,this.me=E}get message(){return this.update.message}get editedMessage(){return this.update.edited_message}get channelPost(){return this.update.channel_post}get editedChannelPost(){return this.update.edited_channel_post}get businessConnection(){return this.update.business_connection}get businessMessage(){return this.update.business_message}get editedBusinessMessage(){return this.update.edited_business_message}get deletedBusinessMessages(){return this.update.deleted_business_messages}get messageReaction(){return this.update.message_reaction}get messageReactionCount(){return this.update.message_reaction_count}get inlineQuery(){return this.update.inline_query}get chosenInlineResult(){return this.update.chosen_inline_result}get callbackQuery(){return this.update.callback_query}get shippingQuery(){return this.update.shipping_query}get preCheckoutQuery(){return this.update.pre_checkout_query}get poll(){return this.update.poll}get pollAnswer(){return this.update.poll_answer}get myChatMember(){return this.update.my_chat_member}get chatMember(){return this.update.chat_member}get chatJoinRequest(){return this.update.chat_join_request}get chatBoost(){return this.update.chat_boost}get removedChatBoost(){return this.update.removed_chat_boost}get purchasedPaidMedia(){return this.update.purchased_paid_media}get msg(){var $,w,E,X,G,J,A;return(J=(G=(X=(E=(w=($=this.message)!==null&&$!==void 0?$:this.editedMessage)!==null&&w!==void 0?w:this.channelPost)!==null&&E!==void 0?E:this.editedChannelPost)!==null&&X!==void 0?X:this.businessMessage)!==null&&G!==void 0?G:this.editedBusinessMessage)!==null&&J!==void 0?J:(A=this.callbackQuery)===null||A===void 0?void 0:A.message}get chat(){var $,w,E,X,G,J,A,D,N;return(N=(D=(A=(J=(G=(X=(E=(w=($=this.msg)!==null&&$!==void 0?$:this.deletedBusinessMessages)!==null&&w!==void 0?w:this.messageReaction)!==null&&E!==void 0?E:this.messageReactionCount)!==null&&X!==void 0?X:this.myChatMember)!==null&&G!==void 0?G:this.chatMember)!==null&&J!==void 0?J:this.chatJoinRequest)!==null&&A!==void 0?A:this.chatBoost)!==null&&D!==void 0?D:this.removedChatBoost)===null||N===void 0?void 0:N.chat}get senderChat(){var $;return($=this.msg)===null||$===void 0?void 0:$.sender_chat}get from(){var $,w,E,X,G,J,A,D,N,W,O,Y,H,L,F,j,M;return(A=(J=(w=($=this.businessConnection)!==null&&$!==void 0?$:this.messageReaction)!==null&&w!==void 0?w:(G=(X=(E=this.chatBoost)===null||E===void 0?void 0:E.boost)!==null&&X!==void 0?X:this.removedChatBoost)===null||G===void 0?void 0:G.source)===null||J===void 0?void 0:J.user)!==null&&A!==void 0?A:(M=(j=(F=(L=(H=(Y=(O=(W=(N=(D=this.callbackQuery)!==null&&D!==void 0?D:this.msg)!==null&&N!==void 0?N:this.inlineQuery)!==null&&W!==void 0?W:this.chosenInlineResult)!==null&&O!==void 0?O:this.shippingQuery)!==null&&Y!==void 0?Y:this.preCheckoutQuery)!==null&&H!==void 0?H:this.myChatMember)!==null&&L!==void 0?L:this.chatMember)!==null&&F!==void 0?F:this.chatJoinRequest)!==null&&j!==void 0?j:this.purchasedPaidMedia)===null||M===void 0?void 0:M.from}get msgId(){var $,w,E,X,G;return(X=(w=($=this.msg)===null||$===void 0?void 0:$.message_id)!==null&&w!==void 0?w:(E=this.messageReaction)===null||E===void 0?void 0:E.message_id)!==null&&X!==void 0?X:(G=this.messageReactionCount)===null||G===void 0?void 0:G.message_id}get chatId(){var $,w,E;return(w=($=this.chat)===null||$===void 0?void 0:$.id)!==null&&w!==void 0?w:(E=this.businessConnection)===null||E===void 0?void 0:E.user_chat_id}get inlineMessageId(){var $,w,E;return(w=($=this.callbackQuery)===null||$===void 0?void 0:$.inline_message_id)!==null&&w!==void 0?w:(E=this.chosenInlineResult)===null||E===void 0?void 0:E.inline_message_id}get businessConnectionId(){var $,w,E,X,G;return(X=(w=($=this.msg)===null||$===void 0?void 0:$.business_connection_id)!==null&&w!==void 0?w:(E=this.businessConnection)===null||E===void 0?void 0:E.id)!==null&&X!==void 0?X:(G=this.deletedBusinessMessages)===null||G===void 0?void 0:G.business_connection_id}entities($){var w,E;let X=this.msg;if(X===void 0)return[];let G=(w=X.text)!==null&&w!==void 0?w:X.caption;if(G===void 0)return[];let J=(E=X.entities)!==null&&E!==void 0?E:X.caption_entities;if(J===void 0)return[];if($!==void 0){let A=new Set(JA($));J=J.filter((D)=>A.has(D.type))}return J.map((A)=>({...A,text:G.substring(A.offset,A.offset+A.length)}))}reactions(){let $=[],w=[],E=[],X=[],G=[],J=[],A=[],D=[],N=!1,W=!1,O=this.messageReaction;if(O!==void 0){let{old_reaction:Y,new_reaction:H}=O;for(let L of H)if(L.type==="emoji")$.push(L.emoji);else if(L.type==="custom_emoji")G.push(L.custom_emoji_id);else if(L.type==="paid")N=W=!0;for(let L of Y)if(L.type==="emoji")X.push(L.emoji);else if(L.type==="custom_emoji")D.push(L.custom_emoji_id);else if(L.type==="paid")W=!1;w.push(...$),J.push(...G);for(let L=0;L<X.length;L++){let F=w.length;if(F===0)break;let j=X[L];for(let M=0;M<F;M++)if(j===w[M]){E.push(j),X.splice(L,1),w.splice(M,1),L--;break}}for(let L=0;L<D.length;L++){let F=J.length;if(F===0)break;let j=D[L];for(let M=0;M<F;M++)if(j===J[M]){A.push(j),D.splice(L,1),J.splice(M,1),L--;break}}}return{emoji:$,emojiAdded:w,emojiKept:E,emojiRemoved:X,customEmoji:G,customEmojiAdded:J,customEmojiKept:A,customEmojiRemoved:D,paid:N,paidAdded:W}}has($){return l$.has.filterQuery($)(this)}hasText($){return l$.has.text($)(this)}hasCommand($){return l$.has.command($)(this)}hasReaction($){return l$.has.reaction($)(this)}hasChatType($){return l$.has.chatType($)(this)}hasCallbackQuery($){return l$.has.callbackQuery($)(this)}hasGameQuery($){return l$.has.gameQuery($)(this)}hasInlineQuery($){return l$.has.inlineQuery($)(this)}hasChosenInlineResult($){return l$.has.chosenInlineResult($)(this)}hasPreCheckoutQuery($){return l$.has.preCheckoutQuery($)(this)}hasShippingQuery($){return l$.has.shippingQuery($)(this)}reply($,w,E){var X;let G=this.msg;return this.api.sendMessage(I(this.chatId,"sendMessage"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithDraft($,w,E){let X=this.msg;return this.api.sendMessageDraft(I(this.chatId,"sendMessageDraft"),this.update.update_id,$,{...(X===null||X===void 0?void 0:X.is_topic_message)?{message_thread_id:X===null||X===void 0?void 0:X.message_thread_id}:{},...w},E)}forwardMessage($,w,E){var X;let G=this.msg;return this.api.forwardMessage($,I(this.chatId,"forwardMessage"),I(this.msgId,"forwardMessage"),{direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}forwardMessages($,w,E,X){var G;let J=this.msg;return this.api.forwardMessages($,I(this.chatId,"forwardMessages"),w,{direct_messages_topic_id:(G=J===null||J===void 0?void 0:J.direct_messages_topic)===null||G===void 0?void 0:G.topic_id,...E},X)}copyMessage($,w,E){var X;let G=this.msg;return this.api.copyMessage($,I(this.chatId,"copyMessage"),I(this.msgId,"copyMessage"),{direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}copyMessages($,w,E,X){var G;let J=this.msg;return this.api.copyMessages($,I(this.chatId,"copyMessages"),w,{direct_messages_topic_id:(G=J===null||J===void 0?void 0:J.direct_messages_topic)===null||G===void 0?void 0:G.topic_id,...E},X)}replyWithPhoto($,w,E){var X;let G=this.msg;return this.api.sendPhoto(I(this.chatId,"sendPhoto"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithAudio($,w,E){var X;let G=this.msg;return this.api.sendAudio(I(this.chatId,"sendAudio"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithDocument($,w,E){var X;let G=this.msg;return this.api.sendDocument(I(this.chatId,"sendDocument"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithVideo($,w,E){var X;let G=this.msg;return this.api.sendVideo(I(this.chatId,"sendVideo"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithAnimation($,w,E){var X;let G=this.msg;return this.api.sendAnimation(I(this.chatId,"sendAnimation"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithVoice($,w,E){var X;let G=this.msg;return this.api.sendVoice(I(this.chatId,"sendVoice"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithVideoNote($,w,E){var X;let G=this.msg;return this.api.sendVideoNote(I(this.chatId,"sendVideoNote"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithMediaGroup($,w,E){var X;let G=this.msg;return this.api.sendMediaGroup(I(this.chatId,"sendMediaGroup"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithLocation($,w,E,X){var G;let J=this.msg;return this.api.sendLocation(I(this.chatId,"sendLocation"),$,w,{business_connection_id:this.businessConnectionId,...(J===null||J===void 0?void 0:J.is_topic_message)?{message_thread_id:J.message_thread_id}:{},direct_messages_topic_id:(G=J===null||J===void 0?void 0:J.direct_messages_topic)===null||G===void 0?void 0:G.topic_id,...E},X)}editMessageLiveLocation($,w,E,X){let G=this.inlineMessageId;return G!==void 0?this.api.editMessageLiveLocationInline(G,$,w,{business_connection_id:this.businessConnectionId,...E},X):this.api.editMessageLiveLocation(I(this.chatId,"editMessageLiveLocation"),I(this.msgId,"editMessageLiveLocation"),$,w,{business_connection_id:this.businessConnectionId,...E},X)}stopMessageLiveLocation($,w){let E=this.inlineMessageId;return E!==void 0?this.api.stopMessageLiveLocationInline(E,{business_connection_id:this.businessConnectionId,...$},w):this.api.stopMessageLiveLocation(I(this.chatId,"stopMessageLiveLocation"),I(this.msgId,"stopMessageLiveLocation"),{business_connection_id:this.businessConnectionId,...$},w)}sendPaidMedia($,w,E,X){var G,J;let A=this.msg;return this.api.sendPaidMedia(I(this.chatId,"sendPaidMedia"),$,w,{business_connection_id:this.businessConnectionId,...(A===null||A===void 0?void 0:A.is_topic_message)?{message_thread_id:A.message_thread_id}:{},direct_messages_topic_id:(J=(G=this.msg)===null||G===void 0?void 0:G.direct_messages_topic)===null||J===void 0?void 0:J.topic_id,...E},X)}replyWithVenue($,w,E,X,G,J){var A;let D=this.msg;return this.api.sendVenue(I(this.chatId,"sendVenue"),$,w,E,X,{business_connection_id:this.businessConnectionId,...(D===null||D===void 0?void 0:D.is_topic_message)?{message_thread_id:D.message_thread_id}:{},direct_messages_topic_id:(A=D===null||D===void 0?void 0:D.direct_messages_topic)===null||A===void 0?void 0:A.topic_id,...G},J)}replyWithContact($,w,E,X){var G;let J=this.msg;return this.api.sendContact(I(this.chatId,"sendContact"),$,w,{business_connection_id:this.businessConnectionId,...(J===null||J===void 0?void 0:J.is_topic_message)?{message_thread_id:J.message_thread_id}:{},direct_messages_topic_id:(G=J===null||J===void 0?void 0:J.direct_messages_topic)===null||G===void 0?void 0:G.topic_id,...E},X)}replyWithPoll($,w,E,X){let G=this.msg;return this.api.sendPoll(I(this.chatId,"sendPoll"),$,w,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},...E},X)}replyWithChecklist($,w,E){return this.api.sendChecklist(I(this.businessConnectionId,"sendChecklist"),I(this.chatId,"sendChecklist"),$,w,E)}editMessageChecklist($,w,E){var X,G,J,A;let D=I(this.msg,"editMessageChecklist"),N=(A=(G=(X=D.checklist_tasks_done)===null||X===void 0?void 0:X.checklist_message)!==null&&G!==void 0?G:(J=D.checklist_tasks_added)===null||J===void 0?void 0:J.checklist_message)!==null&&A!==void 0?A:D;return this.api.editMessageChecklist(I(this.businessConnectionId,"editMessageChecklist"),I(N.chat.id,"editMessageChecklist"),I(N.message_id,"editMessageChecklist"),$,w,E)}replyWithDice($,w,E){var X;let G=this.msg;return this.api.sendDice(I(this.chatId,"sendDice"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}replyWithChatAction($,w,E){let X=this.msg;return this.api.sendChatAction(I(this.chatId,"sendChatAction"),$,{business_connection_id:this.businessConnectionId,message_thread_id:X===null||X===void 0?void 0:X.message_thread_id,...w},E)}react($,w,E){return this.api.setMessageReaction(I(this.chatId,"setMessageReaction"),I(this.msgId,"setMessageReaction"),typeof $==="string"?[{type:"emoji",emoji:$}]:(Array.isArray($)?$:[$]).map((X)=>typeof X==="string"?{type:"emoji",emoji:X}:X),w,E)}getUserProfilePhotos($,w){return this.api.getUserProfilePhotos(I(this.from,"getUserProfilePhotos").id,$,w)}getUserProfileAudios($,w){return this.api.getUserProfileAudios(I(this.from,"getUserProfileAudios").id,$,w)}setUserEmojiStatus($,w){return this.api.setUserEmojiStatus(I(this.from,"setUserEmojiStatus").id,$,w)}getUserChatBoosts($,w){return this.api.getUserChatBoosts($!==null&&$!==void 0?$:I(this.chatId,"getUserChatBoosts"),I(this.from,"getUserChatBoosts").id,w)}getUserGifts($,w){return this.api.getUserGifts(I(this.from,"getUserGifts").id,$,w)}getChatGifts($,w){return this.api.getChatGifts(I(this.chatId,"getChatGifts"),$,w)}getBusinessConnection($){return this.api.getBusinessConnection(I(this.businessConnectionId,"getBusinessConnection"),$)}getFile($){var w,E,X,G,J,A;let D=I(this.msg,"getFile"),N=D.photo!==void 0?D.photo[D.photo.length-1]:(A=(J=(G=(X=(E=(w=D.animation)!==null&&w!==void 0?w:D.audio)!==null&&E!==void 0?E:D.document)!==null&&X!==void 0?X:D.video)!==null&&G!==void 0?G:D.video_note)!==null&&J!==void 0?J:D.voice)!==null&&A!==void 0?A:D.sticker;return this.api.getFile(I(N,"getFile").file_id,$)}kickAuthor(...$){return this.banAuthor(...$)}banAuthor($,w){return this.api.banChatMember(I(this.chatId,"banAuthor"),I(this.from,"banAuthor").id,$,w)}kickChatMember(...$){return this.banChatMember(...$)}banChatMember($,w,E){return this.api.banChatMember(I(this.chatId,"banChatMember"),$,w,E)}unbanChatMember($,w,E){return this.api.unbanChatMember(I(this.chatId,"unbanChatMember"),$,w,E)}restrictAuthor($,w,E){return this.api.restrictChatMember(I(this.chatId,"restrictAuthor"),I(this.from,"restrictAuthor").id,$,w,E)}restrictChatMember($,w,E,X){return this.api.restrictChatMember(I(this.chatId,"restrictChatMember"),$,w,E,X)}promoteAuthor($,w){return this.api.promoteChatMember(I(this.chatId,"promoteAuthor"),I(this.from,"promoteAuthor").id,$,w)}promoteChatMember($,w,E){return this.api.promoteChatMember(I(this.chatId,"promoteChatMember"),$,w,E)}setChatAdministratorAuthorCustomTitle($,w){return this.api.setChatAdministratorCustomTitle(I(this.chatId,"setChatAdministratorAuthorCustomTitle"),I(this.from,"setChatAdministratorAuthorCustomTitle").id,$,w)}setChatAdministratorCustomTitle($,w,E){return this.api.setChatAdministratorCustomTitle(I(this.chatId,"setChatAdministratorCustomTitle"),$,w,E)}setAuthorTag($,w){return this.api.setChatMemberTag(I(this.chatId,"setChatMemberTag"),I(this.from,"setChatMemberTag").id,$,w)}setChatMemberTag($,w,E){return this.api.setChatMemberTag(I(this.chatId,"setChatMemberTag"),$,w,E)}banChatSenderChat($,w){return this.api.banChatSenderChat(I(this.chatId,"banChatSenderChat"),$,w)}unbanChatSenderChat($,w){return this.api.unbanChatSenderChat(I(this.chatId,"unbanChatSenderChat"),$,w)}setChatPermissions($,w,E){return this.api.setChatPermissions(I(this.chatId,"setChatPermissions"),$,w,E)}exportChatInviteLink($){return this.api.exportChatInviteLink(I(this.chatId,"exportChatInviteLink"),$)}createChatInviteLink($,w){return this.api.createChatInviteLink(I(this.chatId,"createChatInviteLink"),$,w)}editChatInviteLink($,w,E){return this.api.editChatInviteLink(I(this.chatId,"editChatInviteLink"),$,w,E)}createChatSubscriptionInviteLink($,w,E,X){return this.api.createChatSubscriptionInviteLink(I(this.chatId,"createChatSubscriptionInviteLink"),$,w,E,X)}editChatSubscriptionInviteLink($,w,E){return this.api.editChatSubscriptionInviteLink(I(this.chatId,"editChatSubscriptionInviteLink"),$,w,E)}revokeChatInviteLink($,w){return this.api.revokeChatInviteLink(I(this.chatId,"editChatInviteLink"),$,w)}approveChatJoinRequest($,w){return this.api.approveChatJoinRequest(I(this.chatId,"approveChatJoinRequest"),$,w)}declineChatJoinRequest($,w){return this.api.declineChatJoinRequest(I(this.chatId,"declineChatJoinRequest"),$,w)}approveSuggestedPost($,w){return this.api.approveSuggestedPost(I(this.chatId,"approveSuggestedPost"),I(this.msgId,"approveSuggestedPost"),$,w)}declineSuggestedPost($,w){return this.api.declineSuggestedPost(I(this.chatId,"declineSuggestedPost"),I(this.msgId,"declineSuggestedPost"),$,w)}setChatPhoto($,w){return this.api.setChatPhoto(I(this.chatId,"setChatPhoto"),$,w)}deleteChatPhoto($){return this.api.deleteChatPhoto(I(this.chatId,"deleteChatPhoto"),$)}setChatTitle($,w){return this.api.setChatTitle(I(this.chatId,"setChatTitle"),$,w)}setChatDescription($,w){return this.api.setChatDescription(I(this.chatId,"setChatDescription"),$,w)}pinChatMessage($,w,E){return this.api.pinChatMessage(I(this.chatId,"pinChatMessage"),$,{business_connection_id:this.businessConnectionId,...w},E)}unpinChatMessage($,w,E){return this.api.unpinChatMessage(I(this.chatId,"unpinChatMessage"),$,{business_connection_id:this.businessConnectionId,...w},E)}unpinAllChatMessages($){return this.api.unpinAllChatMessages(I(this.chatId,"unpinAllChatMessages"),$)}leaveChat($){return this.api.leaveChat(I(this.chatId,"leaveChat"),$)}getChat($){return this.api.getChat(I(this.chatId,"getChat"),$)}getChatAdministrators($){return this.api.getChatAdministrators(I(this.chatId,"getChatAdministrators"),$)}getChatMembersCount(...$){return this.getChatMemberCount(...$)}getChatMemberCount($){return this.api.getChatMemberCount(I(this.chatId,"getChatMemberCount"),$)}getAuthor($){return this.api.getChatMember(I(this.chatId,"getAuthor"),I(this.from,"getAuthor").id,$)}getChatMember($,w){return this.api.getChatMember(I(this.chatId,"getChatMember"),$,w)}setChatStickerSet($,w){return this.api.setChatStickerSet(I(this.chatId,"setChatStickerSet"),$,w)}deleteChatStickerSet($){return this.api.deleteChatStickerSet(I(this.chatId,"deleteChatStickerSet"),$)}createForumTopic($,w,E){return this.api.createForumTopic(I(this.chatId,"createForumTopic"),$,w,E)}editForumTopic($,w){let E=I(this.msg,"editForumTopic"),X=I(E.message_thread_id,"editForumTopic");return this.api.editForumTopic(E.chat.id,X,$,w)}closeForumTopic($){let w=I(this.msg,"closeForumTopic"),E=I(w.message_thread_id,"closeForumTopic");return this.api.closeForumTopic(w.chat.id,E,$)}reopenForumTopic($){let w=I(this.msg,"reopenForumTopic"),E=I(w.message_thread_id,"reopenForumTopic");return this.api.reopenForumTopic(w.chat.id,E,$)}deleteForumTopic($){let w=I(this.msg,"deleteForumTopic"),E=I(w.message_thread_id,"deleteForumTopic");return this.api.deleteForumTopic(w.chat.id,E,$)}unpinAllForumTopicMessages($){let w=I(this.msg,"unpinAllForumTopicMessages"),E=I(w.message_thread_id,"unpinAllForumTopicMessages");return this.api.unpinAllForumTopicMessages(w.chat.id,E,$)}editGeneralForumTopic($,w){return this.api.editGeneralForumTopic(I(this.chatId,"editGeneralForumTopic"),$,w)}closeGeneralForumTopic($){return this.api.closeGeneralForumTopic(I(this.chatId,"closeGeneralForumTopic"),$)}reopenGeneralForumTopic($){return this.api.reopenGeneralForumTopic(I(this.chatId,"reopenGeneralForumTopic"),$)}hideGeneralForumTopic($){return this.api.hideGeneralForumTopic(I(this.chatId,"hideGeneralForumTopic"),$)}unhideGeneralForumTopic($){return this.api.unhideGeneralForumTopic(I(this.chatId,"unhideGeneralForumTopic"),$)}unpinAllGeneralForumTopicMessages($){return this.api.unpinAllGeneralForumTopicMessages(I(this.chatId,"unpinAllGeneralForumTopicMessages"),$)}answerCallbackQuery($,w){return this.api.answerCallbackQuery(I(this.callbackQuery,"answerCallbackQuery").id,typeof $==="string"?{text:$}:$,w)}setChatMenuButton($,w){return this.api.setChatMenuButton($,w)}getChatMenuButton($,w){return this.api.getChatMenuButton($,w)}setMyDefaultAdministratorRights($,w){return this.api.setMyDefaultAdministratorRights($,w)}getMyDefaultAdministratorRights($,w){return this.api.getMyDefaultAdministratorRights($,w)}editMessageText($,w,E){var X,G,J,A,D;let N=this.inlineMessageId;return N!==void 0?this.api.editMessageTextInline(N,$,{business_connection_id:this.businessConnectionId,...w},E):this.api.editMessageText(I(this.chatId,"editMessageText"),I((A=(G=(X=this.msg)===null||X===void 0?void 0:X.message_id)!==null&&G!==void 0?G:(J=this.messageReaction)===null||J===void 0?void 0:J.message_id)!==null&&A!==void 0?A:(D=this.messageReactionCount)===null||D===void 0?void 0:D.message_id,"editMessageText"),$,{business_connection_id:this.businessConnectionId,...w},E)}editMessageCaption($,w){var E,X,G,J,A;let D=this.inlineMessageId;return D!==void 0?this.api.editMessageCaptionInline(D,{business_connection_id:this.businessConnectionId,...$},w):this.api.editMessageCaption(I(this.chatId,"editMessageCaption"),I((J=(X=(E=this.msg)===null||E===void 0?void 0:E.message_id)!==null&&X!==void 0?X:(G=this.messageReaction)===null||G===void 0?void 0:G.message_id)!==null&&J!==void 0?J:(A=this.messageReactionCount)===null||A===void 0?void 0:A.message_id,"editMessageCaption"),{business_connection_id:this.businessConnectionId,...$},w)}editMessageMedia($,w,E){var X,G,J,A,D;let N=this.inlineMessageId;return N!==void 0?this.api.editMessageMediaInline(N,$,{business_connection_id:this.businessConnectionId,...w},E):this.api.editMessageMedia(I(this.chatId,"editMessageMedia"),I((A=(G=(X=this.msg)===null||X===void 0?void 0:X.message_id)!==null&&G!==void 0?G:(J=this.messageReaction)===null||J===void 0?void 0:J.message_id)!==null&&A!==void 0?A:(D=this.messageReactionCount)===null||D===void 0?void 0:D.message_id,"editMessageMedia"),$,{business_connection_id:this.businessConnectionId,...w},E)}editMessageReplyMarkup($,w){var E,X,G,J,A;let D=this.inlineMessageId;return D!==void 0?this.api.editMessageReplyMarkupInline(D,{business_connection_id:this.businessConnectionId,...$},w):this.api.editMessageReplyMarkup(I(this.chatId,"editMessageReplyMarkup"),I((J=(X=(E=this.msg)===null||E===void 0?void 0:E.message_id)!==null&&X!==void 0?X:(G=this.messageReaction)===null||G===void 0?void 0:G.message_id)!==null&&J!==void 0?J:(A=this.messageReactionCount)===null||A===void 0?void 0:A.message_id,"editMessageReplyMarkup"),{business_connection_id:this.businessConnectionId,...$},w)}stopPoll($,w){var E,X,G,J,A;return this.api.stopPoll(I(this.chatId,"stopPoll"),I((J=(X=(E=this.msg)===null||E===void 0?void 0:E.message_id)!==null&&X!==void 0?X:(G=this.messageReaction)===null||G===void 0?void 0:G.message_id)!==null&&J!==void 0?J:(A=this.messageReactionCount)===null||A===void 0?void 0:A.message_id,"stopPoll"),{business_connection_id:this.businessConnectionId,...$},w)}deleteMessage($){var w,E,X,G,J;return this.api.deleteMessage(I(this.chatId,"deleteMessage"),I((G=(E=(w=this.msg)===null||w===void 0?void 0:w.message_id)!==null&&E!==void 0?E:(X=this.messageReaction)===null||X===void 0?void 0:X.message_id)!==null&&G!==void 0?G:(J=this.messageReactionCount)===null||J===void 0?void 0:J.message_id,"deleteMessage"),$)}deleteMessages($,w){return this.api.deleteMessages(I(this.chatId,"deleteMessages"),$,w)}deleteBusinessMessages($,w){return this.api.deleteBusinessMessages(I(this.businessConnectionId,"deleteBusinessMessages"),$,w)}setBusinessAccountName($,w,E){return this.api.setBusinessAccountName(I(this.businessConnectionId,"setBusinessAccountName"),$,w,E)}setBusinessAccountUsername($,w){return this.api.setBusinessAccountUsername(I(this.businessConnectionId,"setBusinessAccountUsername"),$,w)}setBusinessAccountBio($,w){return this.api.setBusinessAccountBio(I(this.businessConnectionId,"setBusinessAccountBio"),$,w)}setBusinessAccountProfilePhoto($,w,E){return this.api.setBusinessAccountProfilePhoto(I(this.businessConnectionId,"setBusinessAccountProfilePhoto"),$,w,E)}removeBusinessAccountProfilePhoto($,w){return this.api.removeBusinessAccountProfilePhoto(I(this.businessConnectionId,"removeBusinessAccountProfilePhoto"),$,w)}setBusinessAccountGiftSettings($,w,E){return this.api.setBusinessAccountGiftSettings(I(this.businessConnectionId,"setBusinessAccountGiftSettings"),$,w,E)}getBusinessAccountStarBalance($){return this.api.getBusinessAccountStarBalance(I(this.businessConnectionId,"getBusinessAccountStarBalance"),$)}transferBusinessAccountStars($,w){return this.api.transferBusinessAccountStars(I(this.businessConnectionId,"transferBusinessAccountStars"),$,w)}getBusinessAccountGifts($,w){return this.api.getBusinessAccountGifts(I(this.businessConnectionId,"getBusinessAccountGifts"),$,w)}convertGiftToStars($,w){return this.api.convertGiftToStars(I(this.businessConnectionId,"convertGiftToStars"),$,w)}upgradeGift($,w,E){return this.api.upgradeGift(I(this.businessConnectionId,"upgradeGift"),$,w,E)}transferGift($,w,E,X){return this.api.transferGift(I(this.businessConnectionId,"transferGift"),$,w,E,X)}postStory($,w,E,X){return this.api.postStory(I(this.businessConnectionId,"postStory"),$,w,E,X)}repostStory($,w,E){var X;let G=I((X=this.msg)===null||X===void 0?void 0:X.story,"repostStory");return this.api.repostStory(I(this.businessConnectionId,"repostStory"),G.chat.id,G.id,$,w,E)}editStory($,w,E,X){return this.api.editStory(I(this.businessConnectionId,"editStory"),$,w,E,X)}deleteStory($,w){return this.api.deleteStory(I(this.businessConnectionId,"deleteStory"),$,w)}replyWithSticker($,w,E){var X;let G=this.msg;return this.api.sendSticker(I(this.chatId,"sendSticker"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},direct_messages_topic_id:(X=G===null||G===void 0?void 0:G.direct_messages_topic)===null||X===void 0?void 0:X.topic_id,...w},E)}getCustomEmojiStickers($){var w,E;return this.api.getCustomEmojiStickers(((E=(w=this.msg)===null||w===void 0?void 0:w.entities)!==null&&E!==void 0?E:[]).filter((X)=>X.type==="custom_emoji").map((X)=>X.custom_emoji_id),$)}replyWithGift($,w,E){return this.api.sendGift(I(this.from,"sendGift").id,$,w,E)}giftPremiumSubscription($,w,E,X){return this.api.giftPremiumSubscription(I(this.from,"giftPremiumSubscription").id,$,w,E,X)}replyWithGiftToChannel($,w,E){return this.api.sendGiftToChannel(I(this.chat,"sendGift").id,$,w,E)}answerInlineQuery($,w,E){return this.api.answerInlineQuery(I(this.inlineQuery,"answerInlineQuery").id,$,w,E)}savePreparedInlineMessage($,w,E){return this.api.savePreparedInlineMessage(I(this.from,"savePreparedInlineMessage").id,$,w,E)}replyWithInvoice($,w,E,X,G,J,A){var D;let N=this.msg;return this.api.sendInvoice(I(this.chatId,"sendInvoice"),$,w,E,X,G,{...(N===null||N===void 0?void 0:N.is_topic_message)?{message_thread_id:N.message_thread_id}:{},direct_messages_topic_id:(D=N===null||N===void 0?void 0:N.direct_messages_topic)===null||D===void 0?void 0:D.topic_id,...J},A)}answerShippingQuery($,w,E){return this.api.answerShippingQuery(I(this.shippingQuery,"answerShippingQuery").id,$,w,E)}answerPreCheckoutQuery($,w,E){return this.api.answerPreCheckoutQuery(I(this.preCheckoutQuery,"answerPreCheckoutQuery").id,$,typeof w==="string"?{error_message:w}:w,E)}refundStarPayment($){var w;return this.api.refundStarPayment(I(this.from,"refundStarPayment").id,I((w=this.msg)===null||w===void 0?void 0:w.successful_payment,"refundStarPayment").telegram_payment_charge_id,$)}editUserStarSubscription($,w,E){return this.api.editUserStarSubscription(I(this.from,"editUserStarSubscription").id,$,w,E)}verifyUser($,w){return this.api.verifyUser(I(this.from,"verifyUser").id,$,w)}verifyChat($,w){return this.api.verifyChat(I(this.chatId,"verifyChat"),$,w)}removeUserVerification($){return this.api.removeUserVerification(I(this.from,"removeUserVerification").id,$)}removeChatVerification($){return this.api.removeChatVerification(I(this.chatId,"removeChatVerification"),$)}readBusinessMessage($){return this.api.readBusinessMessage(I(this.businessConnectionId,"readBusinessMessage"),I(this.chatId,"readBusinessMessage"),I(this.msgId,"readBusinessMessage"),$)}setPassportDataErrors($,w){return this.api.setPassportDataErrors(I(this.from,"setPassportDataErrors").id,$,w)}replyWithGame($,w,E){let X=this.msg;return this.api.sendGame(I(this.chatId,"sendGame"),$,{business_connection_id:this.businessConnectionId,...(X===null||X===void 0?void 0:X.is_topic_message)?{message_thread_id:X.message_thread_id}:{},...w},E)}}HH.Context=l$;l$.has=e1;function I($,w){if($===void 0)throw Error(`Missing information for API call to ${w}`);return $}function HE($){return JA($).map((w)=>typeof w==="string"?(E)=>E===w?w:null:(E)=>E.match(w))}function LE($,w,E){for(let X of E){let G=X(w);if(G)return $.match=G,!0}return!1}function JA($){return Array.isArray($)?$:[$]}});var wN=Z((MH)=>{Object.defineProperty(MH,"__esModule",{value:!0});MH.Composer=MH.BotError=void 0;MH.run=jH;var _1=AA();class $N extends Error{constructor($,w){super(DS($));if(this.error=$,this.ctx=w,this.name="BotError",$ instanceof Error)this.stack=$.stack}}MH.BotError=$N;function DS($){let w;if($ instanceof Error)w=`${$.name} in middleware: ${$.message}`;else{let E=typeof $;switch(w=`Non-error value of type ${E} thrown in middleware`,E){case"bigint":case"boolean":case"number":case"symbol":w+=`: ${$}`;break;case"string":w+=`: ${String($).substring(0,50)}`;break;default:w+="!";break}}return w}function yG($){return typeof $==="function"?$:(w,E)=>$.middleware()(w,E)}function FH($,w){return async(E,X)=>{let G=!1;await $(E,async()=>{if(G)throw Error("`next` already called before!");else G=!0;await w(E,X)})}}function e8($,w){return w()}var NS=()=>Promise.resolve();async function jH($,w){await $(w,NS)}class FE{constructor(...$){this.handler=$.length===0?e8:$.map(yG).reduce(FH)}middleware(){return this.handler}use(...$){let w=new FE(...$);return this.handler=FH(this.handler,yG(w)),w}on($,...w){return this.filter(_1.Context.has.filterQuery($),...w)}hears($,...w){return this.filter(_1.Context.has.text($),...w)}command($,...w){return this.filter(_1.Context.has.command($),...w)}reaction($,...w){return this.filter(_1.Context.has.reaction($),...w)}chatType($,...w){return this.filter(_1.Context.has.chatType($),...w)}callbackQuery($,...w){return this.filter(_1.Context.has.callbackQuery($),...w)}gameQuery($,...w){return this.filter(_1.Context.has.gameQuery($),...w)}inlineQuery($,...w){return this.filter(_1.Context.has.inlineQuery($),...w)}chosenInlineResult($,...w){return this.filter(_1.Context.has.chosenInlineResult($),...w)}preCheckoutQuery($,...w){return this.filter(_1.Context.has.preCheckoutQuery($),...w)}shippingQuery($,...w){return this.filter(_1.Context.has.shippingQuery($),...w)}filter($,...w){let E=new FE(...w);return this.branch($,E,e8),E}drop($,...w){return this.filter(async(E)=>!await $(E),...w)}fork(...$){let w=new FE(...$),E=yG(w);return this.use((X,G)=>Promise.all([G(),jH(E,X)])),w}lazy($){return this.use(async(w,E)=>{let X=await $(w),G=Array.isArray(X)?X:[X];await yG(new FE(...G))(w,E)})}route($,w,E=e8){return this.lazy(async(X)=>{var G;let J=await $(X);return(G=J===void 0||!w[J]?E:w[J])!==null&&G!==void 0?G:[]})}branch($,w,E){return this.lazy(async(X)=>await $(X)?w:E)}errorBoundary($,...w){let E=new FE(...w),X=yG(E);return this.use(async(G,J)=>{let A=!1,D=()=>(A=!0,Promise.resolve());try{await X(G,D)}catch(N){A=!1,await $(new $N(N,G),D)}if(A)await J()}),E}}MH.Composer=FE});var TH=Z((pe,zH)=>{var WX=1000,OX=WX*60,UX=OX*60,jE=UX*24,US=jE*7,YS=jE*365.25;zH.exports=function($,w){w=w||{};var E=typeof $;if(E==="string"&&$.length>0)return HS($);else if(E==="number"&&isFinite($))return w.long?FS($):LS($);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify($))};function HS($){if($=String($),$.length>100)return;var w=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec($);if(!w)return;var E=parseFloat(w[1]),X=(w[2]||"ms").toLowerCase();switch(X){case"years":case"year":case"yrs":case"yr":case"y":return E*YS;case"weeks":case"week":case"w":return E*US;case"days":case"day":case"d":return E*jE;case"hours":case"hour":case"hrs":case"hr":case"h":return E*UX;case"minutes":case"minute":case"mins":case"min":case"m":return E*OX;case"seconds":case"second":case"secs":case"sec":case"s":return E*WX;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return E;default:return}}function LS($){var w=Math.abs($);if(w>=jE)return Math.round($/jE)+"d";if(w>=UX)return Math.round($/UX)+"h";if(w>=OX)return Math.round($/OX)+"m";if(w>=WX)return Math.round($/WX)+"s";return $+"ms"}function FS($){var w=Math.abs($);if(w>=jE)return DA($,w,jE,"day");if(w>=UX)return DA($,w,UX,"hour");if(w>=OX)return DA($,w,OX,"minute");if(w>=WX)return DA($,w,WX,"second");return $+" ms"}function DA($,w,E,X){var G=w>=E*1.5;return Math.round($/E)+" "+X+(G?"s":"")}});var EN=Z((oe,BH)=>{function jS($){E.debug=E,E.default=E,E.coerce=N,E.disable=A,E.enable=G,E.enabled=D,E.humanize=TH(),E.destroy=W,Object.keys($).forEach((O)=>{E[O]=$[O]}),E.names=[],E.skips=[],E.formatters={};function w(O){let Y=0;for(let H=0;H<O.length;H++)Y=(Y<<5)-Y+O.charCodeAt(H),Y|=0;return E.colors[Math.abs(Y)%E.colors.length]}E.selectColor=w;function E(O){let Y,H=null,L,F;function j(...M){if(!j.enabled)return;let z=j,B=Number(new Date),Q=B-(Y||B);if(z.diff=Q,z.prev=Y,z.curr=B,Y=B,M[0]=E.coerce(M[0]),typeof M[0]!=="string")M.unshift("%O");let k=0;M[0]=M[0].replace(/%([a-zA-Z%])/g,(C,n)=>{if(C==="%%")return"%";k++;let T0=E.formatters[n];if(typeof T0==="function"){let f0=M[k];C=T0.call(z,f0),M.splice(k,1),k--}return C}),E.formatArgs.call(z,M),(z.log||E.log).apply(z,M)}if(j.namespace=O,j.useColors=E.useColors(),j.color=E.selectColor(O),j.extend=X,j.destroy=E.destroy,Object.defineProperty(j,"enabled",{enumerable:!0,configurable:!1,get:()=>{if(H!==null)return H;if(L!==E.namespaces)L=E.namespaces,F=E.enabled(O);return F},set:(M)=>{H=M}}),typeof E.init==="function")E.init(j);return j}function X(O,Y){let H=E(this.namespace+(typeof Y>"u"?":":Y)+O);return H.log=this.log,H}function G(O){E.save(O),E.namespaces=O,E.names=[],E.skips=[];let Y=(typeof O==="string"?O:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let H of Y)if(H[0]==="-")E.skips.push(H.slice(1));else E.names.push(H)}function J(O,Y){let H=0,L=0,F=-1,j=0;while(H<O.length)if(L<Y.length&&(Y[L]===O[H]||Y[L]==="*"))if(Y[L]==="*")F=L,j=H,L++;else H++,L++;else if(F!==-1)L=F+1,j++,H=j;else return!1;while(L<Y.length&&Y[L]==="*")L++;return L===Y.length}function A(){let O=[...E.names,...E.skips.map((Y)=>"-"+Y)].join(",");return E.enable(""),O}function D(O){for(let Y of E.skips)if(J(O,Y))return!1;for(let Y of E.names)if(J(O,Y))return!0;return!1}function N(O){if(O instanceof Error)return O.stack||O.message;return O}function W(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return E.enable(E.load()),E}BH.exports=jS});var IH=Z((QH,NA)=>{QH.formatArgs=RS;QH.save=zS;QH.load=TS;QH.useColors=MS;QH.storage=BS();QH.destroy=(()=>{let $=!1;return()=>{if(!$)$=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}})();QH.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function MS(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let $;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&($=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt($[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function RS($){if($[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+$[0]+(this.useColors?"%c ":" ")+"+"+NA.exports.humanize(this.diff),!this.useColors)return;let w="color: "+this.color;$.splice(1,0,w,"color: inherit");let E=0,X=0;$[0].replace(/%[a-zA-Z%]/g,(G)=>{if(G==="%%")return;if(E++,G==="%c")X=E}),$.splice(X,0,w)}QH.log=console.debug||console.log||(()=>{});function zS($){try{if($)QH.storage.setItem("debug",$);else QH.storage.removeItem("debug")}catch(w){}}function TS(){let $;try{$=QH.storage.getItem("debug")||QH.storage.getItem("DEBUG")}catch(w){}if(!$&&typeof process<"u"&&"env"in process)$=process.env.DEBUG;return $}function BS(){try{return localStorage}catch($){}}NA.exports=EN()(QH);var{formatters:QS}=NA.exports;QS.j=function($){try{return JSON.stringify($)}catch(w){return"[UnexpectedJSONParseError]: "+w.message}}});var VH={};Ww(VH,{default:()=>fS,createSupportsColor:()=>XN});import GN from"process";import bS from"os";import KH from"tty";function L1($,w=globalThis.Deno?globalThis.Deno.args:GN.argv){let E=$.startsWith("-")?"":$.length===1?"-":"--",X=w.indexOf(E+$),G=w.indexOf("--");return X!==-1&&(G===-1||X<G)}function ZS(){if(!("FORCE_COLOR"in m0))return;if(m0.FORCE_COLOR==="true")return 1;if(m0.FORCE_COLOR==="false")return 0;if(m0.FORCE_COLOR.length===0)return 1;let $=Math.min(Number.parseInt(m0.FORCE_COLOR,10),3);if(![0,1,2,3].includes($))return;return $}function CS($){if($===0)return!1;return{level:$,hasBasic:!0,has256:$>=2,has16m:$>=3}}function _S($,{streamIsTTY:w,sniffFlags:E=!0}={}){let X=ZS();if(X!==void 0)WA=X;let G=E?WA:X;if(G===0)return 0;if(E){if(L1("color=16m")||L1("color=full")||L1("color=truecolor"))return 3;if(L1("color=256"))return 2}if("TF_BUILD"in m0&&"AGENT_NAME"in m0)return 1;if($&&!w&&G===void 0)return 0;let J=G||0;if(m0.TERM==="dumb")return J;if(GN.platform==="win32"){let A=bS.release().split(".");if(Number(A[0])>=10&&Number(A[2])>=10586)return Number(A[2])>=14931?3:2;return 1}if("CI"in m0){if(["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some((A)=>(A in m0)))return 3;if(["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some((A)=>(A in m0))||m0.CI_NAME==="codeship")return 1;return J}if("TEAMCITY_VERSION"in m0)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(m0.TEAMCITY_VERSION)?1:0;if(m0.COLORTERM==="truecolor")return 3;if(m0.TERM==="xterm-kitty")return 3;if(m0.TERM==="xterm-ghostty")return 3;if(m0.TERM==="wezterm")return 3;if("TERM_PROGRAM"in m0){let A=Number.parseInt((m0.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(m0.TERM_PROGRAM){case"iTerm.app":return A>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(m0.TERM))return 2;if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(m0.TERM))return 1;if("COLORTERM"in m0)return 1;return J}function XN($,w={}){let E=_S($,{streamIsTTY:$&&$.isTTY,...w});return CS(E)}var m0,WA,vS,fS;var PH=R(()=>{({env:m0}=GN);if(L1("no-color")||L1("no-colors")||L1("color=false")||L1("color=never"))WA=0;else if(L1("color")||L1("colors")||L1("color=true")||L1("color=always"))WA=1;vS={stdout:XN({isTTY:KH.isatty(1)}),stderr:XN({isTTY:KH.isatty(2)})},fS=vS});var bH=Z((SH,UA)=>{var xS=V$("tty"),OA=V$("util");SH.init=mS;SH.log=hS;SH.formatArgs=gS;SH.save=cS;SH.load=nS;SH.useColors=yS;SH.destroy=OA.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");SH.colors=[6,2,3,4,5,1];try{let $=(PH(),CO(VH));if($&&($.stderr||$).level>=2)SH.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221]}catch($){}SH.inspectOpts=Object.keys(process.env).filter(($)=>{return/^debug_/i.test($)}).reduce(($,w)=>{let E=w.substring(6).toLowerCase().replace(/_([a-z])/g,(G,J)=>{return J.toUpperCase()}),X=process.env[w];if(/^(yes|on|true|enabled)$/i.test(X))X=!0;else if(/^(no|off|false|disabled)$/i.test(X))X=!1;else if(X==="null")X=null;else X=Number(X);return $[E]=X,$},{});function yS(){return"colors"in SH.inspectOpts?Boolean(SH.inspectOpts.colors):xS.isatty(process.stderr.fd)}function gS($){let{namespace:w,useColors:E}=this;if(E){let X=this.color,G="\x1B[3"+(X<8?X:"8;5;"+X),J=` ${G};1m${w} \x1B[0m`;$[0]=J+$[0].split(`
|
|
388
388
|
`).join(`
|
|
389
|
-
`+J),$.push(G+"m+"+
|
|
390
|
-
`)}function
|
|
391
|
-
`).map((w)=>w.trim()).join(" ")};
|
|
392
|
-
`);let X=
|
|
389
|
+
`+J),$.push(G+"m+"+UA.exports.humanize(this.diff)+"\x1B[0m")}else $[0]=uS()+w+" "+$[0]}function uS(){if(SH.inspectOpts.hideDate)return"";return new Date().toISOString()+" "}function hS(...$){return process.stderr.write(OA.formatWithOptions(SH.inspectOpts,...$)+`
|
|
390
|
+
`)}function cS($){if($)process.env.DEBUG=$;else delete process.env.DEBUG}function nS(){return process.env.DEBUG}function mS($){$.inspectOpts={};let w=Object.keys(SH.inspectOpts);for(let E=0;E<w.length;E++)$.inspectOpts[w[E]]=SH.inspectOpts[w[E]]}UA.exports=EN()(SH);var{formatters:qH}=UA.exports;qH.o=function($){return this.inspectOpts.colors=this.useColors,OA.inspect($,this.inspectOpts).split(`
|
|
391
|
+
`).map((w)=>w.trim()).join(" ")};qH.O=function($){return this.inspectOpts.colors=this.useColors,OA.inspect($,this.inspectOpts)}});var ZH=Z((ae,JN)=>{if(typeof process>"u"||process.type==="renderer"||!1||process.__nwjs)JN.exports=IH();else JN.exports=bH()});var mw=Z((AN)=>{Object.defineProperty(AN,"__esModule",{value:!0});AN.defaultAdapter=AN.itrToStream=AN.debug=void 0;AN.baseFetchConfig=Gk;var sS=V$("http"),aS=V$("https"),eS=V$("stream"),$k=ZH();Object.defineProperty(AN,"debug",{enumerable:!0,get:function(){return $k.debug}});var wk=($)=>eS.Readable.from($,{objectMode:!1});AN.itrToStream=wk;var Ek=new Map,Xk=new Map;function CH($,w,E){let X=$.get(w);if(X===void 0)X=E(),$.set(w,X);return X}function Gk($){if($.startsWith("https:"))return{compress:!0,agent:CH(Xk,$,()=>new aS.Agent({keepAlive:!0}))};else if($.startsWith("http:"))return{agent:CH(Ek,$,()=>new sS.Agent({keepAlive:!0}))};else return{}}AN.defaultAdapter="express"});var YA=Z((fH)=>{Object.defineProperty(fH,"__esModule",{value:!0});fH.HttpError=fH.GrammyError=void 0;fH.toGrammyError=Nk;fH.toHttpError=Ok;var Dk=mw(),vH=(0,Dk.debug)("grammy:warn");class DN extends Error{constructor($,w,E,X){var G;super(`${$} (${w.error_code}: ${w.description})`);this.method=E,this.payload=X,this.ok=!1,this.name="GrammyError",this.error_code=w.error_code,this.description=w.description,this.parameters=(G=w.parameters)!==null&&G!==void 0?G:{}}}fH.GrammyError=DN;function Nk($,w,E){switch($.error_code){case 401:vH("Error 401 means that your bot token is wrong, talk to https://t.me/BotFather to check it.");break;case 409:vH("Error 409 means that you are running your bot several times on long polling. Consider revoking the bot token if you believe that no other instance is running.");break}return new DN(`Call to '${w}' failed!`,$,w,E)}class NN extends Error{constructor($,w){super($);this.error=w,this.name="HttpError"}}fH.HttpError=NN;function Wk($){return typeof $==="object"&&$!==null&&"status"in $&&"statusText"in $}function Ok($,w,E){let X=`Network request for '${$}' failed!`;if(Wk(E))X+=` (${E.status}: ${E.statusText})`;if(w&&E instanceof Error)X+=` ${E.message}`;return new NN(X,E)}});var Lk={};var uH=Z((Mw)=>{var Fk=Mw&&Mw.__createBinding||(Object.create?function($,w,E,X){if(X===void 0)X=E;var G=Object.getOwnPropertyDescriptor(w,E);if(!G||("get"in G?!w.__esModule:G.writable||G.configurable))G={enumerable:!0,get:function(){return w[E]}};Object.defineProperty($,X,G)}:function($,w,E,X){if(X===void 0)X=E;$[X]=w[E]}),jk=Mw&&Mw.__exportStar||function($,w){for(var E in $)if(E!=="default"&&!Object.prototype.hasOwnProperty.call(w,E))Fk(w,$,E)};Object.defineProperty(Mw,"__esModule",{value:!0});Mw.InputFile=void 0;var yH=V$("fs"),Mk=V$("node-fetch"),HA=V$("path"),Rk=mw(),zk=(0,Rk.debug)("grammy:warn");jk(CO(Lk),Mw);class WN{constructor($,w){if(this.consumed=!1,this.fileData=$,w!==null&&w!==void 0||(w=this.guessFilename($)),this.filename=w,typeof $==="string"&&($.startsWith("http:")||$.startsWith("https:")))zk(`InputFile received the local file path '${$}' that looks like a URL. Is this a mistake?`)}guessFilename($){if(typeof $==="string")return(0,HA.basename)($);if("url"in $)return(0,HA.basename)($.url);if(!($ instanceof URL))return;if($.pathname!=="/"){let w=(0,HA.basename)($.pathname);if(w)return w}return(0,HA.basename)($.hostname)}async toRaw(){if(this.consumed)throw Error("Cannot reuse InputFile data source!");let $=this.fileData;if(typeof $==="string")return(0,yH.createReadStream)($);if($ instanceof URL)return $.protocol==="file"?(0,yH.createReadStream)($.pathname):gH($);if("url"in $)return gH($.url);if($ instanceof Uint8Array)return $;if(typeof $==="function")return new WN(await $()).toRaw();return this.consumed=!0,$}toJSON(){throw Error("InputFile instances must be sent via grammY")}}Mw.InputFile=WN;async function*gH($){let{body:w}=await(0,Mk.default)($);for await(let E of w){if(typeof E==="string")throw Error(`Could not transfer file, received string data instead of bytes from '${$}'`);yield E}}});var ON=Z((RE)=>{var Tk=RE&&RE.__createBinding||(Object.create?function($,w,E,X){if(X===void 0)X=E;var G=Object.getOwnPropertyDescriptor(w,E);if(!G||("get"in G?!w.__esModule:G.writable||G.configurable))G={enumerable:!0,get:function(){return w[E]}};Object.defineProperty($,X,G)}:function($,w,E,X){if(X===void 0)X=E;$[X]=w[E]}),Bk=RE&&RE.__exportStar||function($,w){for(var E in $)if(E!=="default"&&!Object.prototype.hasOwnProperty.call(w,E))Tk(w,$,E)};Object.defineProperty(RE,"__esModule",{value:!0});Bk(uH(),RE)});var mH=Z((nH)=>{Object.defineProperty(nH,"__esModule",{value:!0});nH.requiresFormDataUpload=UN;nH.createJsonPayload=Ik;nH.createFormDataPayload=Vk;var Qk=mw(),LA=ON();function UN($){return $ instanceof LA.InputFile||typeof $==="object"&&$!==null&&Object.values($).some((w)=>Array.isArray(w)?w.some(UN):w instanceof LA.InputFile||UN(w))}function hH($){return JSON.stringify($,(w,E)=>E!==null&&E!==void 0?E:void 0)}function Ik($){return{method:"POST",headers:{"content-type":"application/json",connection:"keep-alive"},body:hH($)}}async function*Kk($,w){try{yield*$}catch(E){w(E)}}function Vk($,w){let E=Pk(),X=qk($,E),G=Kk(X,w),J=(0,Qk.itrToStream)(G);return{method:"POST",headers:{"content-type":`multipart/form-data; boundary=${E}`,connection:"keep-alive"},body:J}}function Pk(){return"----------"+cH(32)}function cH($=16){return Array.from(Array($)).map(()=>Math.random().toString(36)[2]||0).join("")}var uG=new TextEncoder;async function*qk($,w){let E=YN($);yield uG.encode(`--${w}\r
|
|
392
|
+
`);let X=uG.encode(`\r
|
|
393
393
|
--${w}\r
|
|
394
|
-
`),G=!0;for(let[J,A]of Object.entries($)){if(A==null)continue;if(!G)yield X;yield
|
|
394
|
+
`),G=!0;for(let[J,A]of Object.entries($)){if(A==null)continue;if(!G)yield X;yield Sk(J,A instanceof LA.InputFile?A.toJSON():typeof A==="object"?hH(A):A),G=!1}for(let{id:J,origin:A,file:D}of E){if(!G)yield X;yield*kk(J,A,D),G=!1}yield uG.encode(`\r
|
|
395
395
|
--${w}--\r
|
|
396
|
-
`)}function
|
|
396
|
+
`)}function YN($){if(typeof $!=="object"||$===null)return[];return Object.entries($).flatMap(([w,E])=>{if(Array.isArray(E))return E.flatMap((X)=>YN(X));else if(E instanceof LA.InputFile){let X=cH();Object.assign(E,{toJSON:()=>`attach://${X}`});let G=w==="media"&&"type"in $&&typeof $.type==="string"?$.type:w;return{id:X,origin:G,file:E}}else return YN(E)})}function Sk($,w){return uG.encode(`content-disposition:form-data;name="${$}"\r
|
|
397
397
|
\r
|
|
398
|
-
${w}`)}async function*
|
|
398
|
+
${w}`)}async function*kk($,w,E){let X=E.filename||`${w}.${bk(w)}`;if(X.includes("\r")||X.includes(`
|
|
399
399
|
`))throw Error(`File paths cannot contain carriage-return (\\r) or newline (\\n) characters! Filename for property '${w}' was:
|
|
400
400
|
"""
|
|
401
401
|
${X}
|
|
402
|
-
"""`);yield
|
|
402
|
+
"""`);yield uG.encode(`content-disposition:form-data;name="${$}";filename=${X}\r
|
|
403
403
|
content-type:application/octet-stream\r
|
|
404
404
|
\r
|
|
405
|
-
`);let G=await E.toRaw();if(G instanceof Uint8Array)yield G;else yield*G}function
|
|
405
|
+
`);let G=await E.toRaw();if(G instanceof Uint8Array)yield G;else yield*G}function bk($){switch($){case"certificate":return"pem";case"photo":case"thumbnail":return"jpg";case"voice":return"ogg";case"audio":return"mp3";case"animation":case"video":case"video_note":return"mp4";case"sticker":return"webp";default:return"dat"}}});var HN=Z((FA)=>{Object.defineProperty(FA,"__esModule",{value:!0});FA.fetch=FA.AbortController=void 0;var vk=V$("abort-controller");Object.defineProperty(FA,"AbortController",{enumerable:!0,get:function(){return vk.AbortController}});var fk=V$("node-fetch");Object.defineProperty(FA,"fetch",{enumerable:!0,get:function(){return fk.default}})});var dH=Z((iH)=>{Object.defineProperty(iH,"__esModule",{value:!0});iH.createRawApi=uk;var pH=mw(),rH=YA(),jA=mH(),yk=(0,pH.debug)("grammy:core");function gk($,w){return(E,X,G)=>w($,E,X,G)}class oH{constructor($,w={},E={}){var X,G,J,A,D,N;this.token=$,this.webhookReplyEnvelope=E,this.hasUsedWebhookReply=!1,this.installedTransformers=[],this.call=async(L,F,j)=>{let M=F!==null&&F!==void 0?F:{};if(yk(`Calling ${L}`),j!==void 0)pk(L,M,j);let z=this.options,B=(0,jA.requiresFormDataUpload)(M);if(this.webhookReplyEnvelope.send!==void 0&&!this.hasUsedWebhookReply&&!B&&z.canUseWebhookReply(L)){this.hasUsedWebhookReply=!0;let K0=(0,jA.createJsonPayload)({...M,method:L});return await this.webhookReplyEnvelope.send(K0.body),{ok:!0,result:!0}}let Q=rk(j),k=nk(Q,z.timeoutSeconds,L),v=mk(Q),C=z.buildUrl(z.apiRoot,this.token,L,z.environment),n=B?(0,jA.createFormDataPayload)(M,(K0)=>v.catch(K0)):(0,jA.createJsonPayload)(M),T0=Q.signal,f0={...z.baseFetchConfig,signal:T0,...n},d0=[this.fetch(C,f0).then((K0)=>K0.json()),v.promise,k.promise];try{return await Promise.race(d0)}catch(K0){throw(0,rH.toHttpError)(L,z.sensitiveLogs,K0)}finally{if(k.handle!==void 0)clearTimeout(k.handle)}};let W=(X=w.apiRoot)!==null&&X!==void 0?X:"https://api.telegram.org",O=(G=w.environment)!==null&&G!==void 0?G:"prod",{fetch:Y}=w,H=Y!==null&&Y!==void 0?Y:tH.fetch;if(this.options={apiRoot:W,environment:O,buildUrl:(J=w.buildUrl)!==null&&J!==void 0?J:hk,timeoutSeconds:(A=w.timeoutSeconds)!==null&&A!==void 0?A:500,baseFetchConfig:{...(0,pH.baseFetchConfig)(W),...w.baseFetchConfig},canUseWebhookReply:(D=w.canUseWebhookReply)!==null&&D!==void 0?D:()=>!1,sensitiveLogs:(N=w.sensitiveLogs)!==null&&N!==void 0?N:!1,fetch:(...L)=>H(...L)},this.fetch=this.options.fetch,this.options.apiRoot.endsWith("/"))throw Error(`Remove the trailing '/' from the 'apiRoot' option (use '${this.options.apiRoot.substring(0,this.options.apiRoot.length-1)}' instead of '${this.options.apiRoot}')`)}use(...$){return this.call=$.reduce(gk,this.call),this.installedTransformers.push(...$),this}async callApi($,w,E){let X=await this.call($,w,E);if(X.ok)return X.result;else throw(0,rH.toGrammyError)(X,$,w)}}function uk($,w,E){let X=new oH($,w,E),G={get(N,W){return W==="toJSON"?"__internal":W==="getMe"||W==="getWebhookInfo"||W==="getForumTopicIconStickers"||W==="getAvailableGifts"||W==="logOut"||W==="close"||W==="getMyStarBalance"||W==="removeMyProfilePhoto"?X.callApi.bind(X,W,{}):X.callApi.bind(X,W)},...ck},J=new Proxy({},G),A=X.installedTransformers,D={raw:J,installedTransformers:A,use:(...N)=>{return X.use(...N),D}};return D}var hk=($,w,E,X)=>{return`${$}/bot${w}/${X==="test"?"test/":""}${E}`},ck={set(){return!1},defineProperty(){return!1},deleteProperty(){return!1},ownKeys(){return[]}};function nk($,w,E){let X=void 0;return{promise:new Promise((J,A)=>{X=setTimeout(()=>{let D=`Request to '${E}' timed out after ${w} seconds`;A(Error(D)),$.abort()},1000*w)}),handle:X}}function mk($){let w=(X)=>{throw X};return{promise:new Promise((X,G)=>{w=(J)=>{G(J),$.abort()}}),catch:w}}function rk($){let w=new tH.AbortController;if($===void 0)return w;let E=$;function X(){w.abort(),E.removeEventListener("abort",X)}if(E.aborted)X();else E.addEventListener("abort",X);return{abort:X,signal:w.signal}}function pk($,w,E){if(typeof(E===null||E===void 0?void 0:E.addEventListener)==="function")return;let X=JSON.stringify(w);if(X.length>20)X=X.substring(0,16)+" ...";let G=JSON.stringify(E);if(G.length>20)G=G.substring(0,16)+" ...";throw Error(`Incorrect abort signal instance found! You passed two payloads to '${$}' but you should merge the second one containing '${G}' into the first one containing '${X}'! If you are using context shortcuts, you may want to use a method on 'ctx.api' instead.
|
|
406
406
|
|
|
407
|
-
If you want to prevent such mistakes in the future, consider using TypeScript. https://www.typescriptlang.org/`)}var rH=ON()});var UN=Z((iH)=>{Object.defineProperty(iH,"__esModule",{value:!0});iH.Api=void 0;var hk=oH();class tH{constructor($,w,E){this.token=$,this.options=w;let{raw:X,use:G,installedTransformers:J}=(0,hk.createRawApi)($,w,E);this.raw=X,this.config={use:G,installedTransformers:()=>J.slice()}}getUpdates($,w){return this.raw.getUpdates({...$},w)}setWebhook($,w,E){return this.raw.setWebhook({url:$,...w},E)}deleteWebhook($,w){return this.raw.deleteWebhook({...$},w)}getWebhookInfo($){return this.raw.getWebhookInfo($)}getMe($){return this.raw.getMe($)}logOut($){return this.raw.logOut($)}close($){return this.raw.close($)}sendMessage($,w,E,X){return this.raw.sendMessage({chat_id:$,text:w,...E},X)}sendMessageDraft($,w,E,X,G){return this.raw.sendMessageDraft({chat_id:$,draft_id:w,text:E,...X},G)}forwardMessage($,w,E,X,G){return this.raw.forwardMessage({chat_id:$,from_chat_id:w,message_id:E,...X},G)}forwardMessages($,w,E,X,G){return this.raw.forwardMessages({chat_id:$,from_chat_id:w,message_ids:E,...X},G)}copyMessage($,w,E,X,G){return this.raw.copyMessage({chat_id:$,from_chat_id:w,message_id:E,...X},G)}copyMessages($,w,E,X,G){return this.raw.copyMessages({chat_id:$,from_chat_id:w,message_ids:E,...X},G)}sendPhoto($,w,E,X){return this.raw.sendPhoto({chat_id:$,photo:w,...E},X)}sendAudio($,w,E,X){return this.raw.sendAudio({chat_id:$,audio:w,...E},X)}sendDocument($,w,E,X){return this.raw.sendDocument({chat_id:$,document:w,...E},X)}sendVideo($,w,E,X){return this.raw.sendVideo({chat_id:$,video:w,...E},X)}sendAnimation($,w,E,X){return this.raw.sendAnimation({chat_id:$,animation:w,...E},X)}sendVoice($,w,E,X){return this.raw.sendVoice({chat_id:$,voice:w,...E},X)}sendVideoNote($,w,E,X){return this.raw.sendVideoNote({chat_id:$,video_note:w,...E},X)}sendMediaGroup($,w,E,X){return this.raw.sendMediaGroup({chat_id:$,media:w,...E},X)}sendLocation($,w,E,X,G){return this.raw.sendLocation({chat_id:$,latitude:w,longitude:E,...X},G)}editMessageLiveLocation($,w,E,X,G,J){return this.raw.editMessageLiveLocation({chat_id:$,message_id:w,latitude:E,longitude:X,...G},J)}editMessageLiveLocationInline($,w,E,X,G){return this.raw.editMessageLiveLocation({inline_message_id:$,latitude:w,longitude:E,...X},G)}stopMessageLiveLocation($,w,E,X){return this.raw.stopMessageLiveLocation({chat_id:$,message_id:w,...E},X)}stopMessageLiveLocationInline($,w,E){return this.raw.stopMessageLiveLocation({inline_message_id:$,...w},E)}sendPaidMedia($,w,E,X,G){return this.raw.sendPaidMedia({chat_id:$,star_count:w,media:E,...X},G)}sendVenue($,w,E,X,G,J,A){return this.raw.sendVenue({chat_id:$,latitude:w,longitude:E,title:X,address:G,...J},A)}sendContact($,w,E,X,G){return this.raw.sendContact({chat_id:$,phone_number:w,first_name:E,...X},G)}sendPoll($,w,E,X,G){let J=E.map((A)=>typeof A==="string"?{text:A}:A);return this.raw.sendPoll({chat_id:$,question:w,options:J,...X},G)}sendChecklist($,w,E,X,G){return this.raw.sendChecklist({business_connection_id:$,chat_id:w,checklist:E,...X},G)}editMessageChecklist($,w,E,X,G,J){return this.raw.editMessageChecklist({business_connection_id:$,chat_id:w,message_id:E,checklist:X,...G},J)}sendDice($,w,E,X){return this.raw.sendDice({chat_id:$,emoji:w,...E},X)}setMessageReaction($,w,E,X,G){return this.raw.setMessageReaction({chat_id:$,message_id:w,reaction:E,...X},G)}sendChatAction($,w,E,X){return this.raw.sendChatAction({chat_id:$,action:w,...E},X)}getUserProfilePhotos($,w,E){return this.raw.getUserProfilePhotos({user_id:$,...w},E)}getUserProfileAudios($,w,E){return this.raw.getUserProfileAudios({user_id:$,...w},E)}setUserEmojiStatus($,w,E){return this.raw.setUserEmojiStatus({user_id:$,...w},E)}getUserChatBoosts($,w,E){return this.raw.getUserChatBoosts({chat_id:$,user_id:w},E)}getUserGifts($,w,E){return this.raw.getUserGifts({user_id:$,...w},E)}getChatGifts($,w,E){return this.raw.getChatGifts({chat_id:$,...w},E)}getBusinessConnection($,w){return this.raw.getBusinessConnection({business_connection_id:$},w)}getFile($,w){return this.raw.getFile({file_id:$},w)}kickChatMember(...$){return this.banChatMember(...$)}banChatMember($,w,E,X){return this.raw.banChatMember({chat_id:$,user_id:w,...E},X)}unbanChatMember($,w,E,X){return this.raw.unbanChatMember({chat_id:$,user_id:w,...E},X)}restrictChatMember($,w,E,X,G){return this.raw.restrictChatMember({chat_id:$,user_id:w,permissions:E,...X},G)}promoteChatMember($,w,E,X){return this.raw.promoteChatMember({chat_id:$,user_id:w,...E},X)}setChatAdministratorCustomTitle($,w,E,X){return this.raw.setChatAdministratorCustomTitle({chat_id:$,user_id:w,custom_title:E},X)}setChatMemberTag($,w,E,X){return this.raw.setChatMemberTag({chat_id:$,user_id:w,tag:E},X)}banChatSenderChat($,w,E){return this.raw.banChatSenderChat({chat_id:$,sender_chat_id:w},E)}unbanChatSenderChat($,w,E){return this.raw.unbanChatSenderChat({chat_id:$,sender_chat_id:w},E)}setChatPermissions($,w,E,X){return this.raw.setChatPermissions({chat_id:$,permissions:w,...E},X)}exportChatInviteLink($,w){return this.raw.exportChatInviteLink({chat_id:$},w)}createChatInviteLink($,w,E){return this.raw.createChatInviteLink({chat_id:$,...w},E)}editChatInviteLink($,w,E,X){return this.raw.editChatInviteLink({chat_id:$,invite_link:w,...E},X)}createChatSubscriptionInviteLink($,w,E,X,G){return this.raw.createChatSubscriptionInviteLink({chat_id:$,subscription_period:w,subscription_price:E,...X},G)}editChatSubscriptionInviteLink($,w,E,X){return this.raw.editChatSubscriptionInviteLink({chat_id:$,invite_link:w,...E},X)}revokeChatInviteLink($,w,E){return this.raw.revokeChatInviteLink({chat_id:$,invite_link:w},E)}approveChatJoinRequest($,w,E){return this.raw.approveChatJoinRequest({chat_id:$,user_id:w},E)}declineChatJoinRequest($,w,E){return this.raw.declineChatJoinRequest({chat_id:$,user_id:w},E)}approveSuggestedPost($,w,E,X){return this.raw.approveSuggestedPost({chat_id:$,message_id:w,...E},X)}declineSuggestedPost($,w,E,X){return this.raw.declineSuggestedPost({chat_id:$,message_id:w,...E},X)}setChatPhoto($,w,E){return this.raw.setChatPhoto({chat_id:$,photo:w},E)}deleteChatPhoto($,w){return this.raw.deleteChatPhoto({chat_id:$},w)}setChatTitle($,w,E){return this.raw.setChatTitle({chat_id:$,title:w},E)}setChatDescription($,w,E){return this.raw.setChatDescription({chat_id:$,description:w},E)}pinChatMessage($,w,E,X){return this.raw.pinChatMessage({chat_id:$,message_id:w,...E},X)}unpinChatMessage($,w,E,X){return this.raw.unpinChatMessage({chat_id:$,message_id:w,...E},X)}unpinAllChatMessages($,w){return this.raw.unpinAllChatMessages({chat_id:$},w)}leaveChat($,w){return this.raw.leaveChat({chat_id:$},w)}getChat($,w){return this.raw.getChat({chat_id:$},w)}getChatAdministrators($,w){return this.raw.getChatAdministrators({chat_id:$},w)}getChatMembersCount(...$){return this.getChatMemberCount(...$)}getChatMemberCount($,w){return this.raw.getChatMemberCount({chat_id:$},w)}getChatMember($,w,E){return this.raw.getChatMember({chat_id:$,user_id:w},E)}setChatStickerSet($,w,E){return this.raw.setChatStickerSet({chat_id:$,sticker_set_name:w},E)}deleteChatStickerSet($,w){return this.raw.deleteChatStickerSet({chat_id:$},w)}getForumTopicIconStickers($){return this.raw.getForumTopicIconStickers($)}createForumTopic($,w,E,X){return this.raw.createForumTopic({chat_id:$,name:w,...E},X)}editForumTopic($,w,E,X){return this.raw.editForumTopic({chat_id:$,message_thread_id:w,...E},X)}closeForumTopic($,w,E){return this.raw.closeForumTopic({chat_id:$,message_thread_id:w},E)}reopenForumTopic($,w,E){return this.raw.reopenForumTopic({chat_id:$,message_thread_id:w},E)}deleteForumTopic($,w,E){return this.raw.deleteForumTopic({chat_id:$,message_thread_id:w},E)}unpinAllForumTopicMessages($,w,E){return this.raw.unpinAllForumTopicMessages({chat_id:$,message_thread_id:w},E)}editGeneralForumTopic($,w,E){return this.raw.editGeneralForumTopic({chat_id:$,name:w},E)}closeGeneralForumTopic($,w){return this.raw.closeGeneralForumTopic({chat_id:$},w)}reopenGeneralForumTopic($,w){return this.raw.reopenGeneralForumTopic({chat_id:$},w)}hideGeneralForumTopic($,w){return this.raw.hideGeneralForumTopic({chat_id:$},w)}unhideGeneralForumTopic($,w){return this.raw.unhideGeneralForumTopic({chat_id:$},w)}unpinAllGeneralForumTopicMessages($,w){return this.raw.unpinAllGeneralForumTopicMessages({chat_id:$},w)}answerCallbackQuery($,w,E){return this.raw.answerCallbackQuery({callback_query_id:$,...w},E)}setMyName($,w,E){return this.raw.setMyName({name:$,...w},E)}getMyName($,w){return this.raw.getMyName($!==null&&$!==void 0?$:{},w)}setMyCommands($,w,E){return this.raw.setMyCommands({commands:$,...w},E)}deleteMyCommands($,w){return this.raw.deleteMyCommands({...$},w)}getMyCommands($,w){return this.raw.getMyCommands({...$},w)}setMyDescription($,w,E){return this.raw.setMyDescription({description:$,...w},E)}getMyDescription($,w){return this.raw.getMyDescription({...$},w)}setMyShortDescription($,w,E){return this.raw.setMyShortDescription({short_description:$,...w},E)}getMyShortDescription($,w){return this.raw.getMyShortDescription({...$},w)}setMyProfilePhoto($,w){return this.raw.setMyProfilePhoto({photo:$},w)}removeMyProfilePhoto($){return this.raw.removeMyProfilePhoto($)}setChatMenuButton($,w){return this.raw.setChatMenuButton({...$},w)}getChatMenuButton($,w){return this.raw.getChatMenuButton({...$},w)}setMyDefaultAdministratorRights($,w){return this.raw.setMyDefaultAdministratorRights({...$},w)}getMyDefaultAdministratorRights($,w){return this.raw.getMyDefaultAdministratorRights({...$},w)}getMyStarBalance($){return this.raw.getMyStarBalance($)}editMessageText($,w,E,X,G){return this.raw.editMessageText({chat_id:$,message_id:w,text:E,...X},G)}editMessageTextInline($,w,E,X){return this.raw.editMessageText({inline_message_id:$,text:w,...E},X)}editMessageCaption($,w,E,X){return this.raw.editMessageCaption({chat_id:$,message_id:w,...E},X)}editMessageCaptionInline($,w,E){return this.raw.editMessageCaption({inline_message_id:$,...w},E)}editMessageMedia($,w,E,X,G){return this.raw.editMessageMedia({chat_id:$,message_id:w,media:E,...X},G)}editMessageMediaInline($,w,E,X){return this.raw.editMessageMedia({inline_message_id:$,media:w,...E},X)}editMessageReplyMarkup($,w,E,X){return this.raw.editMessageReplyMarkup({chat_id:$,message_id:w,...E},X)}editMessageReplyMarkupInline($,w,E){return this.raw.editMessageReplyMarkup({inline_message_id:$,...w},E)}stopPoll($,w,E,X){return this.raw.stopPoll({chat_id:$,message_id:w,...E},X)}deleteMessage($,w,E){return this.raw.deleteMessage({chat_id:$,message_id:w},E)}deleteMessages($,w,E){return this.raw.deleteMessages({chat_id:$,message_ids:w},E)}deleteBusinessMessages($,w,E){return this.raw.deleteBusinessMessages({business_connection_id:$,message_ids:w},E)}setBusinessAccountName($,w,E,X){return this.raw.setBusinessAccountName({business_connection_id:$,first_name:w,...E},X)}setBusinessAccountUsername($,w,E){return this.raw.setBusinessAccountUsername({business_connection_id:$,username:w},E)}setBusinessAccountBio($,w,E){return this.raw.setBusinessAccountBio({business_connection_id:$,bio:w},E)}setBusinessAccountProfilePhoto($,w,E,X){return this.raw.setBusinessAccountProfilePhoto({business_connection_id:$,photo:w,...E},X)}removeBusinessAccountProfilePhoto($,w,E){return this.raw.removeBusinessAccountProfilePhoto({business_connection_id:$,...w},E)}setBusinessAccountGiftSettings($,w,E,X){return this.raw.setBusinessAccountGiftSettings({business_connection_id:$,show_gift_button:w,accepted_gift_types:E},X)}getBusinessAccountStarBalance($,w){return this.raw.getBusinessAccountStarBalance({business_connection_id:$},w)}transferBusinessAccountStars($,w,E){return this.raw.transferBusinessAccountStars({business_connection_id:$,star_count:w},E)}getBusinessAccountGifts($,w,E){return this.raw.getBusinessAccountGifts({business_connection_id:$,...w},E)}convertGiftToStars($,w,E){return this.raw.convertGiftToStars({business_connection_id:$,owned_gift_id:w},E)}upgradeGift($,w,E,X){return this.raw.upgradeGift({business_connection_id:$,owned_gift_id:w,...E},X)}transferGift($,w,E,X,G){return this.raw.transferGift({business_connection_id:$,owned_gift_id:w,new_owner_chat_id:E,star_count:X},G)}postStory($,w,E,X,G){return this.raw.postStory({business_connection_id:$,content:w,active_period:E,...X},G)}repostStory($,w,E,X,G,J){return this.raw.repostStory({business_connection_id:$,from_chat_id:w,from_story_id:E,active_period:X,...G},J)}editStory($,w,E,X,G){return this.raw.editStory({business_connection_id:$,story_id:w,content:E,...X},G)}deleteStory($,w,E){return this.raw.deleteStory({business_connection_id:$,story_id:w},E)}sendSticker($,w,E,X){return this.raw.sendSticker({chat_id:$,sticker:w,...E},X)}getStickerSet($,w){return this.raw.getStickerSet({name:$},w)}getCustomEmojiStickers($,w){return this.raw.getCustomEmojiStickers({custom_emoji_ids:$},w)}uploadStickerFile($,w,E,X){return this.raw.uploadStickerFile({user_id:$,sticker_format:w,sticker:E},X)}createNewStickerSet($,w,E,X,G,J){return this.raw.createNewStickerSet({user_id:$,name:w,title:E,stickers:X,...G},J)}addStickerToSet($,w,E,X){return this.raw.addStickerToSet({user_id:$,name:w,sticker:E},X)}setStickerPositionInSet($,w,E){return this.raw.setStickerPositionInSet({sticker:$,position:w},E)}deleteStickerFromSet($,w){return this.raw.deleteStickerFromSet({sticker:$},w)}replaceStickerInSet($,w,E,X,G){return this.raw.replaceStickerInSet({user_id:$,name:w,old_sticker:E,sticker:X},G)}setStickerEmojiList($,w,E){return this.raw.setStickerEmojiList({sticker:$,emoji_list:w},E)}setStickerKeywords($,w,E){return this.raw.setStickerKeywords({sticker:$,keywords:w},E)}setStickerMaskPosition($,w,E){return this.raw.setStickerMaskPosition({sticker:$,mask_position:w},E)}setStickerSetTitle($,w,E){return this.raw.setStickerSetTitle({name:$,title:w},E)}deleteStickerSet($,w){return this.raw.deleteStickerSet({name:$},w)}setStickerSetThumbnail($,w,E,X,G){return this.raw.setStickerSetThumbnail({name:$,user_id:w,thumbnail:E,format:X},G)}setCustomEmojiStickerSetThumbnail($,w,E){return this.raw.setCustomEmojiStickerSetThumbnail({name:$,custom_emoji_id:w},E)}getAvailableGifts($){return this.raw.getAvailableGifts($)}sendGift($,w,E,X){return this.raw.sendGift({user_id:$,gift_id:w,...E},X)}giftPremiumSubscription($,w,E,X,G){return this.raw.giftPremiumSubscription({user_id:$,month_count:w,star_count:E,...X},G)}sendGiftToChannel($,w,E,X){return this.raw.sendGift({chat_id:$,gift_id:w,...E},X)}answerInlineQuery($,w,E,X){return this.raw.answerInlineQuery({inline_query_id:$,results:w,...E},X)}answerWebAppQuery($,w,E){return this.raw.answerWebAppQuery({web_app_query_id:$,result:w},E)}savePreparedInlineMessage($,w,E,X){return this.raw.savePreparedInlineMessage({user_id:$,result:w,...E},X)}sendInvoice($,w,E,X,G,J,A,D){return this.raw.sendInvoice({chat_id:$,title:w,description:E,payload:X,currency:G,prices:J,...A},D)}createInvoiceLink($,w,E,X,G,J,A,D){return this.raw.createInvoiceLink({title:$,description:w,payload:E,provider_token:X,currency:G,prices:J,...A},D)}answerShippingQuery($,w,E,X){return this.raw.answerShippingQuery({shipping_query_id:$,ok:w,...E},X)}answerPreCheckoutQuery($,w,E,X){return this.raw.answerPreCheckoutQuery({pre_checkout_query_id:$,ok:w,...E},X)}getStarTransactions($,w){return this.raw.getStarTransactions({...$},w)}refundStarPayment($,w,E){return this.raw.refundStarPayment({user_id:$,telegram_payment_charge_id:w},E)}editUserStarSubscription($,w,E,X){return this.raw.editUserStarSubscription({user_id:$,telegram_payment_charge_id:w,is_canceled:E},X)}verifyUser($,w,E){return this.raw.verifyUser({user_id:$,...w},E)}verifyChat($,w,E){return this.raw.verifyChat({chat_id:$,...w},E)}removeUserVerification($,w){return this.raw.removeUserVerification({user_id:$},w)}removeChatVerification($,w){return this.raw.removeChatVerification({chat_id:$},w)}readBusinessMessage($,w,E,X){return this.raw.readBusinessMessage({business_connection_id:$,chat_id:w,message_id:E},X)}setPassportDataErrors($,w,E){return this.raw.setPassportDataErrors({user_id:$,errors:w},E)}sendGame($,w,E,X){return this.raw.sendGame({chat_id:$,game_short_name:w,...E},X)}setGameScore($,w,E,X,G,J){return this.raw.setGameScore({chat_id:$,message_id:w,user_id:E,score:X,...G},J)}setGameScoreInline($,w,E,X,G){return this.raw.setGameScore({inline_message_id:$,user_id:w,score:E,...X},G)}getGameHighScores($,w,E,X){return this.raw.getGameHighScores({chat_id:$,message_id:w,user_id:E},X)}getGameHighScoresInline($,w,E){return this.raw.getGameHighScores({inline_message_id:$,user_id:w},E)}}iH.Api=tH});var jN=Z((FN)=>{Object.defineProperty(FN,"__esModule",{value:!0});FN.Bot=FN.BotError=FN.DEFAULT_UPDATE_TYPES=void 0;var uG=a8();Object.defineProperty(FN,"BotError",{enumerable:!0,get:function(){return uG.BotError}});var ck=GA(),lH=UN(),YN=OA(),sH=EA(),LN=mw(),$w=(0,LN.debug)("grammy:bot"),nk=(0,LN.debug)("grammy:warn"),UX=(0,LN.debug)("grammy:error");FN.DEFAULT_UPDATE_TYPES=["message","edited_message","channel_post","edited_channel_post","business_connection","business_message","edited_business_message","deleted_business_messages","inline_query","chosen_inline_result","callback_query","shipping_query","pre_checkout_query","purchased_paid_media","poll","poll_answer","my_chat_member","chat_join_request","chat_boost","removed_chat_boost"];class eH extends uG.Composer{constructor($,w){var E;super();if(this.token=$,this.pollingRunning=!1,this.lastTriedUpdateId=0,this.observedUpdateTypes=new Set,this.errorHandler=async(X)=>{var G,J;if(console.error("Error in middleware while handling update",(J=(G=X.ctx)===null||G===void 0?void 0:G.update)===null||J===void 0?void 0:J.update_id,X.error),console.error("No error handler was set!"),console.error("Set your own error handler with `bot.catch = ...`"),this.pollingRunning)console.error("Stopping bot"),await this.stop();throw X},!$)throw Error("Empty token!");this.me=w===null||w===void 0?void 0:w.botInfo,this.clientConfig=w===null||w===void 0?void 0:w.client,this.ContextConstructor=(E=w===null||w===void 0?void 0:w.ContextConstructor)!==null&&E!==void 0?E:ck.Context,this.api=new lH.Api($,this.clientConfig)}set botInfo($){this.me=$}get botInfo(){if(this.me===void 0)throw Error("Bot information unavailable! Make sure to call `await bot.init()` before accessing `bot.botInfo`!");return this.me}on($,...w){for(let[E]of(0,sH.parse)($).flatMap(sH.preprocess))this.observedUpdateTypes.add(E);return super.on($,...w)}reaction($,...w){return this.observedUpdateTypes.add("message_reaction"),super.reaction($,...w)}isInited(){return this.me!==void 0}async init($){var w;if(!this.isInited()){$w("Initializing bot"),(w=this.mePromise)!==null&&w!==void 0||(this.mePromise=aH(()=>this.api.getMe($),$));let E;try{E=await this.mePromise}finally{this.mePromise=void 0}if(this.me===void 0)this.me=E;else $w("Bot info was set by now, will not overwrite")}$w(`I am ${this.me.username}!`)}async handleUpdates($){for(let w of $){this.lastTriedUpdateId=w.update_id;try{await this.handleUpdate(w)}catch(E){if(E instanceof uG.BotError)await this.errorHandler(E);else throw console.error("FATAL: grammY unable to handle:",E),E}}}async handleUpdate($,w){if(this.me===void 0)throw Error("Bot not initialized! Either call `await bot.init()`, or directly set the `botInfo` option in the `Bot` constructor to specify a known bot info object.");$w(`Processing update ${$.update_id}`);let E=new lH.Api(this.token,this.clientConfig,w),X=this.api.config.installedTransformers();if(X.length>0)E.config.use(...X);let G=new this.ContextConstructor($,E,this.me);try{await(0,uG.run)(this.middleware(),G)}catch(J){throw UX(`Error in middleware for update ${$.update_id}`),new uG.BotError(J,G)}}async start($){var w,E,X;let G=[];if(!this.isInited())G.push(this.init((w=this.pollingAbortController)===null||w===void 0?void 0:w.signal));if(this.pollingRunning){await Promise.all(G),$w("Simple long polling already running!");return}this.pollingRunning=!0,this.pollingAbortController=new pk.AbortController;try{G.push(aH(async()=>{var J;await this.api.deleteWebhook({drop_pending_updates:$===null||$===void 0?void 0:$.drop_pending_updates},(J=this.pollingAbortController)===null||J===void 0?void 0:J.signal)},(E=this.pollingAbortController)===null||E===void 0?void 0:E.signal)),await Promise.all(G),await((X=$===null||$===void 0?void 0:$.onStart)===null||X===void 0?void 0:X.call($,this.botInfo))}catch(J){throw this.pollingRunning=!1,this.pollingAbortController=void 0,J}if(!this.pollingRunning)return;mk(this.observedUpdateTypes,$===null||$===void 0?void 0:$.allowed_updates),this.use=rk,$w("Starting simple long polling"),await this.loop($),$w("Middleware is done running")}async stop(){var $;if(this.pollingRunning){$w("Stopping bot, saving update offset"),this.pollingRunning=!1,($=this.pollingAbortController)===null||$===void 0||$.abort();let w=this.lastTriedUpdateId+1;await this.api.getUpdates({offset:w,limit:1}).finally(()=>this.pollingAbortController=void 0)}else $w("Bot is not running!")}isRunning(){return this.pollingRunning}catch($){this.errorHandler=$}async loop($){var w,E;let X=$===null||$===void 0?void 0:$.limit,G=(w=$===null||$===void 0?void 0:$.timeout)!==null&&w!==void 0?w:30,J=(E=$===null||$===void 0?void 0:$.allowed_updates)!==null&&E!==void 0?E:[];try{while(this.pollingRunning){let A=await this.fetchUpdates({limit:X,timeout:G,allowed_updates:J});if(A===void 0)break;await this.handleUpdates(A),J=void 0}}finally{this.pollingRunning=!1}}async fetchUpdates({limit:$,timeout:w,allowed_updates:E}){var X;let G=this.lastTriedUpdateId+1,J=void 0;do try{J=await this.api.getUpdates({offset:G,limit:$,timeout:w,allowed_updates:E},(X=this.pollingAbortController)===null||X===void 0?void 0:X.signal)}catch(A){await this.handlePollingError(A)}while(J===void 0&&this.pollingRunning);return J}async handlePollingError($){var w;if(!this.pollingRunning){$w("Pending getUpdates request cancelled");return}let E=3;if($ instanceof YN.GrammyError){if(UX($.message),$.error_code===401||$.error_code===409)throw $;else if($.error_code===429)UX("Bot API server is closing."),E=(w=$.parameters.retry_after)!==null&&w!==void 0?w:E}else UX($);UX(`Call to getUpdates failed, retrying in ${E} seconds ...`),await HN(E)}}FN.Bot=eH;async function aH($,w){let X=50;async function G(A){let D=!1,N="rethrow";if(A instanceof YN.HttpError)D=!0,N="retry";else if(A instanceof YN.GrammyError){if(A.error_code>=500)D=!0,N="retry";else if(A.error_code===429){let W=A.parameters.retry_after;if(typeof W==="number")await HN(W,w),X=50;else D=!0;N="retry"}}if(D){if(X!==50)await HN(X,w);X=Math.min(1200000,2*X)}return N}let J={ok:!1};while(!J.ok)try{J={ok:!0,value:await $()}}catch(A){switch(UX(A),await G(A)){case"retry":continue;case"rethrow":throw A}}return J.value}async function HN($,w){let E,X;function G(){if(X===null||X===void 0||X(Error("Aborted delay")),E!==void 0)clearTimeout(E)}try{await new Promise((J,A)=>{if(X=A,w===null||w===void 0?void 0:w.aborted){G();return}w===null||w===void 0||w.addEventListener("abort",G),E=setTimeout(J,1000*$)})}finally{w===null||w===void 0||w.removeEventListener("abort",G)}}function mk($,w=FN.DEFAULT_UPDATE_TYPES){let E=Array.from($).filter((X)=>!w.includes(X));if(E.length>0)nk(`You registered listeners for the following update types, but you did not specify them in \`allowed_updates\` so they may not be received: ${E.map((X)=>`'${X}'`).join(", ")}`)}function rk(){throw Error(`It looks like you are registering more listeners on your bot from within other listeners! This means that every time your bot handles a message like this one, new listeners will be added. This list grows until your machine crashes, so grammY throws this error to tell you that you should probably do things a bit differently. If you're unsure how to resolve this problem, you can ask in the group chat: https://telegram.me/grammyjs
|
|
407
|
+
If you want to prevent such mistakes in the future, consider using TypeScript. https://www.typescriptlang.org/`)}var tH=HN()});var LN=Z((sH)=>{Object.defineProperty(sH,"__esModule",{value:!0});sH.Api=void 0;var tk=dH();class lH{constructor($,w,E){this.token=$,this.options=w;let{raw:X,use:G,installedTransformers:J}=(0,tk.createRawApi)($,w,E);this.raw=X,this.config={use:G,installedTransformers:()=>J.slice()}}getUpdates($,w){return this.raw.getUpdates({...$},w)}setWebhook($,w,E){return this.raw.setWebhook({url:$,...w},E)}deleteWebhook($,w){return this.raw.deleteWebhook({...$},w)}getWebhookInfo($){return this.raw.getWebhookInfo($)}getMe($){return this.raw.getMe($)}logOut($){return this.raw.logOut($)}close($){return this.raw.close($)}sendMessage($,w,E,X){return this.raw.sendMessage({chat_id:$,text:w,...E},X)}sendMessageDraft($,w,E,X,G){return this.raw.sendMessageDraft({chat_id:$,draft_id:w,text:E,...X},G)}forwardMessage($,w,E,X,G){return this.raw.forwardMessage({chat_id:$,from_chat_id:w,message_id:E,...X},G)}forwardMessages($,w,E,X,G){return this.raw.forwardMessages({chat_id:$,from_chat_id:w,message_ids:E,...X},G)}copyMessage($,w,E,X,G){return this.raw.copyMessage({chat_id:$,from_chat_id:w,message_id:E,...X},G)}copyMessages($,w,E,X,G){return this.raw.copyMessages({chat_id:$,from_chat_id:w,message_ids:E,...X},G)}sendPhoto($,w,E,X){return this.raw.sendPhoto({chat_id:$,photo:w,...E},X)}sendAudio($,w,E,X){return this.raw.sendAudio({chat_id:$,audio:w,...E},X)}sendDocument($,w,E,X){return this.raw.sendDocument({chat_id:$,document:w,...E},X)}sendVideo($,w,E,X){return this.raw.sendVideo({chat_id:$,video:w,...E},X)}sendAnimation($,w,E,X){return this.raw.sendAnimation({chat_id:$,animation:w,...E},X)}sendVoice($,w,E,X){return this.raw.sendVoice({chat_id:$,voice:w,...E},X)}sendVideoNote($,w,E,X){return this.raw.sendVideoNote({chat_id:$,video_note:w,...E},X)}sendMediaGroup($,w,E,X){return this.raw.sendMediaGroup({chat_id:$,media:w,...E},X)}sendLocation($,w,E,X,G){return this.raw.sendLocation({chat_id:$,latitude:w,longitude:E,...X},G)}editMessageLiveLocation($,w,E,X,G,J){return this.raw.editMessageLiveLocation({chat_id:$,message_id:w,latitude:E,longitude:X,...G},J)}editMessageLiveLocationInline($,w,E,X,G){return this.raw.editMessageLiveLocation({inline_message_id:$,latitude:w,longitude:E,...X},G)}stopMessageLiveLocation($,w,E,X){return this.raw.stopMessageLiveLocation({chat_id:$,message_id:w,...E},X)}stopMessageLiveLocationInline($,w,E){return this.raw.stopMessageLiveLocation({inline_message_id:$,...w},E)}sendPaidMedia($,w,E,X,G){return this.raw.sendPaidMedia({chat_id:$,star_count:w,media:E,...X},G)}sendVenue($,w,E,X,G,J,A){return this.raw.sendVenue({chat_id:$,latitude:w,longitude:E,title:X,address:G,...J},A)}sendContact($,w,E,X,G){return this.raw.sendContact({chat_id:$,phone_number:w,first_name:E,...X},G)}sendPoll($,w,E,X,G){let J=E.map((A)=>typeof A==="string"?{text:A}:A);return this.raw.sendPoll({chat_id:$,question:w,options:J,...X},G)}sendChecklist($,w,E,X,G){return this.raw.sendChecklist({business_connection_id:$,chat_id:w,checklist:E,...X},G)}editMessageChecklist($,w,E,X,G,J){return this.raw.editMessageChecklist({business_connection_id:$,chat_id:w,message_id:E,checklist:X,...G},J)}sendDice($,w,E,X){return this.raw.sendDice({chat_id:$,emoji:w,...E},X)}setMessageReaction($,w,E,X,G){return this.raw.setMessageReaction({chat_id:$,message_id:w,reaction:E,...X},G)}sendChatAction($,w,E,X){return this.raw.sendChatAction({chat_id:$,action:w,...E},X)}getUserProfilePhotos($,w,E){return this.raw.getUserProfilePhotos({user_id:$,...w},E)}getUserProfileAudios($,w,E){return this.raw.getUserProfileAudios({user_id:$,...w},E)}setUserEmojiStatus($,w,E){return this.raw.setUserEmojiStatus({user_id:$,...w},E)}getUserChatBoosts($,w,E){return this.raw.getUserChatBoosts({chat_id:$,user_id:w},E)}getUserGifts($,w,E){return this.raw.getUserGifts({user_id:$,...w},E)}getChatGifts($,w,E){return this.raw.getChatGifts({chat_id:$,...w},E)}getBusinessConnection($,w){return this.raw.getBusinessConnection({business_connection_id:$},w)}getFile($,w){return this.raw.getFile({file_id:$},w)}kickChatMember(...$){return this.banChatMember(...$)}banChatMember($,w,E,X){return this.raw.banChatMember({chat_id:$,user_id:w,...E},X)}unbanChatMember($,w,E,X){return this.raw.unbanChatMember({chat_id:$,user_id:w,...E},X)}restrictChatMember($,w,E,X,G){return this.raw.restrictChatMember({chat_id:$,user_id:w,permissions:E,...X},G)}promoteChatMember($,w,E,X){return this.raw.promoteChatMember({chat_id:$,user_id:w,...E},X)}setChatAdministratorCustomTitle($,w,E,X){return this.raw.setChatAdministratorCustomTitle({chat_id:$,user_id:w,custom_title:E},X)}setChatMemberTag($,w,E,X){return this.raw.setChatMemberTag({chat_id:$,user_id:w,tag:E},X)}banChatSenderChat($,w,E){return this.raw.banChatSenderChat({chat_id:$,sender_chat_id:w},E)}unbanChatSenderChat($,w,E){return this.raw.unbanChatSenderChat({chat_id:$,sender_chat_id:w},E)}setChatPermissions($,w,E,X){return this.raw.setChatPermissions({chat_id:$,permissions:w,...E},X)}exportChatInviteLink($,w){return this.raw.exportChatInviteLink({chat_id:$},w)}createChatInviteLink($,w,E){return this.raw.createChatInviteLink({chat_id:$,...w},E)}editChatInviteLink($,w,E,X){return this.raw.editChatInviteLink({chat_id:$,invite_link:w,...E},X)}createChatSubscriptionInviteLink($,w,E,X,G){return this.raw.createChatSubscriptionInviteLink({chat_id:$,subscription_period:w,subscription_price:E,...X},G)}editChatSubscriptionInviteLink($,w,E,X){return this.raw.editChatSubscriptionInviteLink({chat_id:$,invite_link:w,...E},X)}revokeChatInviteLink($,w,E){return this.raw.revokeChatInviteLink({chat_id:$,invite_link:w},E)}approveChatJoinRequest($,w,E){return this.raw.approveChatJoinRequest({chat_id:$,user_id:w},E)}declineChatJoinRequest($,w,E){return this.raw.declineChatJoinRequest({chat_id:$,user_id:w},E)}approveSuggestedPost($,w,E,X){return this.raw.approveSuggestedPost({chat_id:$,message_id:w,...E},X)}declineSuggestedPost($,w,E,X){return this.raw.declineSuggestedPost({chat_id:$,message_id:w,...E},X)}setChatPhoto($,w,E){return this.raw.setChatPhoto({chat_id:$,photo:w},E)}deleteChatPhoto($,w){return this.raw.deleteChatPhoto({chat_id:$},w)}setChatTitle($,w,E){return this.raw.setChatTitle({chat_id:$,title:w},E)}setChatDescription($,w,E){return this.raw.setChatDescription({chat_id:$,description:w},E)}pinChatMessage($,w,E,X){return this.raw.pinChatMessage({chat_id:$,message_id:w,...E},X)}unpinChatMessage($,w,E,X){return this.raw.unpinChatMessage({chat_id:$,message_id:w,...E},X)}unpinAllChatMessages($,w){return this.raw.unpinAllChatMessages({chat_id:$},w)}leaveChat($,w){return this.raw.leaveChat({chat_id:$},w)}getChat($,w){return this.raw.getChat({chat_id:$},w)}getChatAdministrators($,w){return this.raw.getChatAdministrators({chat_id:$},w)}getChatMembersCount(...$){return this.getChatMemberCount(...$)}getChatMemberCount($,w){return this.raw.getChatMemberCount({chat_id:$},w)}getChatMember($,w,E){return this.raw.getChatMember({chat_id:$,user_id:w},E)}setChatStickerSet($,w,E){return this.raw.setChatStickerSet({chat_id:$,sticker_set_name:w},E)}deleteChatStickerSet($,w){return this.raw.deleteChatStickerSet({chat_id:$},w)}getForumTopicIconStickers($){return this.raw.getForumTopicIconStickers($)}createForumTopic($,w,E,X){return this.raw.createForumTopic({chat_id:$,name:w,...E},X)}editForumTopic($,w,E,X){return this.raw.editForumTopic({chat_id:$,message_thread_id:w,...E},X)}closeForumTopic($,w,E){return this.raw.closeForumTopic({chat_id:$,message_thread_id:w},E)}reopenForumTopic($,w,E){return this.raw.reopenForumTopic({chat_id:$,message_thread_id:w},E)}deleteForumTopic($,w,E){return this.raw.deleteForumTopic({chat_id:$,message_thread_id:w},E)}unpinAllForumTopicMessages($,w,E){return this.raw.unpinAllForumTopicMessages({chat_id:$,message_thread_id:w},E)}editGeneralForumTopic($,w,E){return this.raw.editGeneralForumTopic({chat_id:$,name:w},E)}closeGeneralForumTopic($,w){return this.raw.closeGeneralForumTopic({chat_id:$},w)}reopenGeneralForumTopic($,w){return this.raw.reopenGeneralForumTopic({chat_id:$},w)}hideGeneralForumTopic($,w){return this.raw.hideGeneralForumTopic({chat_id:$},w)}unhideGeneralForumTopic($,w){return this.raw.unhideGeneralForumTopic({chat_id:$},w)}unpinAllGeneralForumTopicMessages($,w){return this.raw.unpinAllGeneralForumTopicMessages({chat_id:$},w)}answerCallbackQuery($,w,E){return this.raw.answerCallbackQuery({callback_query_id:$,...w},E)}setMyName($,w,E){return this.raw.setMyName({name:$,...w},E)}getMyName($,w){return this.raw.getMyName($!==null&&$!==void 0?$:{},w)}setMyCommands($,w,E){return this.raw.setMyCommands({commands:$,...w},E)}deleteMyCommands($,w){return this.raw.deleteMyCommands({...$},w)}getMyCommands($,w){return this.raw.getMyCommands({...$},w)}setMyDescription($,w,E){return this.raw.setMyDescription({description:$,...w},E)}getMyDescription($,w){return this.raw.getMyDescription({...$},w)}setMyShortDescription($,w,E){return this.raw.setMyShortDescription({short_description:$,...w},E)}getMyShortDescription($,w){return this.raw.getMyShortDescription({...$},w)}setMyProfilePhoto($,w){return this.raw.setMyProfilePhoto({photo:$},w)}removeMyProfilePhoto($){return this.raw.removeMyProfilePhoto($)}setChatMenuButton($,w){return this.raw.setChatMenuButton({...$},w)}getChatMenuButton($,w){return this.raw.getChatMenuButton({...$},w)}setMyDefaultAdministratorRights($,w){return this.raw.setMyDefaultAdministratorRights({...$},w)}getMyDefaultAdministratorRights($,w){return this.raw.getMyDefaultAdministratorRights({...$},w)}getMyStarBalance($){return this.raw.getMyStarBalance($)}editMessageText($,w,E,X,G){return this.raw.editMessageText({chat_id:$,message_id:w,text:E,...X},G)}editMessageTextInline($,w,E,X){return this.raw.editMessageText({inline_message_id:$,text:w,...E},X)}editMessageCaption($,w,E,X){return this.raw.editMessageCaption({chat_id:$,message_id:w,...E},X)}editMessageCaptionInline($,w,E){return this.raw.editMessageCaption({inline_message_id:$,...w},E)}editMessageMedia($,w,E,X,G){return this.raw.editMessageMedia({chat_id:$,message_id:w,media:E,...X},G)}editMessageMediaInline($,w,E,X){return this.raw.editMessageMedia({inline_message_id:$,media:w,...E},X)}editMessageReplyMarkup($,w,E,X){return this.raw.editMessageReplyMarkup({chat_id:$,message_id:w,...E},X)}editMessageReplyMarkupInline($,w,E){return this.raw.editMessageReplyMarkup({inline_message_id:$,...w},E)}stopPoll($,w,E,X){return this.raw.stopPoll({chat_id:$,message_id:w,...E},X)}deleteMessage($,w,E){return this.raw.deleteMessage({chat_id:$,message_id:w},E)}deleteMessages($,w,E){return this.raw.deleteMessages({chat_id:$,message_ids:w},E)}deleteBusinessMessages($,w,E){return this.raw.deleteBusinessMessages({business_connection_id:$,message_ids:w},E)}setBusinessAccountName($,w,E,X){return this.raw.setBusinessAccountName({business_connection_id:$,first_name:w,...E},X)}setBusinessAccountUsername($,w,E){return this.raw.setBusinessAccountUsername({business_connection_id:$,username:w},E)}setBusinessAccountBio($,w,E){return this.raw.setBusinessAccountBio({business_connection_id:$,bio:w},E)}setBusinessAccountProfilePhoto($,w,E,X){return this.raw.setBusinessAccountProfilePhoto({business_connection_id:$,photo:w,...E},X)}removeBusinessAccountProfilePhoto($,w,E){return this.raw.removeBusinessAccountProfilePhoto({business_connection_id:$,...w},E)}setBusinessAccountGiftSettings($,w,E,X){return this.raw.setBusinessAccountGiftSettings({business_connection_id:$,show_gift_button:w,accepted_gift_types:E},X)}getBusinessAccountStarBalance($,w){return this.raw.getBusinessAccountStarBalance({business_connection_id:$},w)}transferBusinessAccountStars($,w,E){return this.raw.transferBusinessAccountStars({business_connection_id:$,star_count:w},E)}getBusinessAccountGifts($,w,E){return this.raw.getBusinessAccountGifts({business_connection_id:$,...w},E)}convertGiftToStars($,w,E){return this.raw.convertGiftToStars({business_connection_id:$,owned_gift_id:w},E)}upgradeGift($,w,E,X){return this.raw.upgradeGift({business_connection_id:$,owned_gift_id:w,...E},X)}transferGift($,w,E,X,G){return this.raw.transferGift({business_connection_id:$,owned_gift_id:w,new_owner_chat_id:E,star_count:X},G)}postStory($,w,E,X,G){return this.raw.postStory({business_connection_id:$,content:w,active_period:E,...X},G)}repostStory($,w,E,X,G,J){return this.raw.repostStory({business_connection_id:$,from_chat_id:w,from_story_id:E,active_period:X,...G},J)}editStory($,w,E,X,G){return this.raw.editStory({business_connection_id:$,story_id:w,content:E,...X},G)}deleteStory($,w,E){return this.raw.deleteStory({business_connection_id:$,story_id:w},E)}sendSticker($,w,E,X){return this.raw.sendSticker({chat_id:$,sticker:w,...E},X)}getStickerSet($,w){return this.raw.getStickerSet({name:$},w)}getCustomEmojiStickers($,w){return this.raw.getCustomEmojiStickers({custom_emoji_ids:$},w)}uploadStickerFile($,w,E,X){return this.raw.uploadStickerFile({user_id:$,sticker_format:w,sticker:E},X)}createNewStickerSet($,w,E,X,G,J){return this.raw.createNewStickerSet({user_id:$,name:w,title:E,stickers:X,...G},J)}addStickerToSet($,w,E,X){return this.raw.addStickerToSet({user_id:$,name:w,sticker:E},X)}setStickerPositionInSet($,w,E){return this.raw.setStickerPositionInSet({sticker:$,position:w},E)}deleteStickerFromSet($,w){return this.raw.deleteStickerFromSet({sticker:$},w)}replaceStickerInSet($,w,E,X,G){return this.raw.replaceStickerInSet({user_id:$,name:w,old_sticker:E,sticker:X},G)}setStickerEmojiList($,w,E){return this.raw.setStickerEmojiList({sticker:$,emoji_list:w},E)}setStickerKeywords($,w,E){return this.raw.setStickerKeywords({sticker:$,keywords:w},E)}setStickerMaskPosition($,w,E){return this.raw.setStickerMaskPosition({sticker:$,mask_position:w},E)}setStickerSetTitle($,w,E){return this.raw.setStickerSetTitle({name:$,title:w},E)}deleteStickerSet($,w){return this.raw.deleteStickerSet({name:$},w)}setStickerSetThumbnail($,w,E,X,G){return this.raw.setStickerSetThumbnail({name:$,user_id:w,thumbnail:E,format:X},G)}setCustomEmojiStickerSetThumbnail($,w,E){return this.raw.setCustomEmojiStickerSetThumbnail({name:$,custom_emoji_id:w},E)}getAvailableGifts($){return this.raw.getAvailableGifts($)}sendGift($,w,E,X){return this.raw.sendGift({user_id:$,gift_id:w,...E},X)}giftPremiumSubscription($,w,E,X,G){return this.raw.giftPremiumSubscription({user_id:$,month_count:w,star_count:E,...X},G)}sendGiftToChannel($,w,E,X){return this.raw.sendGift({chat_id:$,gift_id:w,...E},X)}answerInlineQuery($,w,E,X){return this.raw.answerInlineQuery({inline_query_id:$,results:w,...E},X)}answerWebAppQuery($,w,E){return this.raw.answerWebAppQuery({web_app_query_id:$,result:w},E)}savePreparedInlineMessage($,w,E,X){return this.raw.savePreparedInlineMessage({user_id:$,result:w,...E},X)}sendInvoice($,w,E,X,G,J,A,D){return this.raw.sendInvoice({chat_id:$,title:w,description:E,payload:X,currency:G,prices:J,...A},D)}createInvoiceLink($,w,E,X,G,J,A,D){return this.raw.createInvoiceLink({title:$,description:w,payload:E,provider_token:X,currency:G,prices:J,...A},D)}answerShippingQuery($,w,E,X){return this.raw.answerShippingQuery({shipping_query_id:$,ok:w,...E},X)}answerPreCheckoutQuery($,w,E,X){return this.raw.answerPreCheckoutQuery({pre_checkout_query_id:$,ok:w,...E},X)}getStarTransactions($,w){return this.raw.getStarTransactions({...$},w)}refundStarPayment($,w,E){return this.raw.refundStarPayment({user_id:$,telegram_payment_charge_id:w},E)}editUserStarSubscription($,w,E,X){return this.raw.editUserStarSubscription({user_id:$,telegram_payment_charge_id:w,is_canceled:E},X)}verifyUser($,w,E){return this.raw.verifyUser({user_id:$,...w},E)}verifyChat($,w,E){return this.raw.verifyChat({chat_id:$,...w},E)}removeUserVerification($,w){return this.raw.removeUserVerification({user_id:$},w)}removeChatVerification($,w){return this.raw.removeChatVerification({chat_id:$},w)}readBusinessMessage($,w,E,X){return this.raw.readBusinessMessage({business_connection_id:$,chat_id:w,message_id:E},X)}setPassportDataErrors($,w,E){return this.raw.setPassportDataErrors({user_id:$,errors:w},E)}sendGame($,w,E,X){return this.raw.sendGame({chat_id:$,game_short_name:w,...E},X)}setGameScore($,w,E,X,G,J){return this.raw.setGameScore({chat_id:$,message_id:w,user_id:E,score:X,...G},J)}setGameScoreInline($,w,E,X,G){return this.raw.setGameScore({inline_message_id:$,user_id:w,score:E,...X},G)}getGameHighScores($,w,E,X){return this.raw.getGameHighScores({chat_id:$,message_id:w,user_id:E},X)}getGameHighScoresInline($,w,E){return this.raw.getGameHighScores({inline_message_id:$,user_id:w},E)}}sH.Api=lH});var zN=Z((RN)=>{Object.defineProperty(RN,"__esModule",{value:!0});RN.Bot=RN.BotError=RN.DEFAULT_UPDATE_TYPES=void 0;var hG=wN();Object.defineProperty(RN,"BotError",{enumerable:!0,get:function(){return hG.BotError}});var ik=AA(),eH=LN(),FN=YA(),$L=GA(),MN=mw(),$w=(0,MN.debug)("grammy:bot"),dk=(0,MN.debug)("grammy:warn"),YX=(0,MN.debug)("grammy:error");RN.DEFAULT_UPDATE_TYPES=["message","edited_message","channel_post","edited_channel_post","business_connection","business_message","edited_business_message","deleted_business_messages","inline_query","chosen_inline_result","callback_query","shipping_query","pre_checkout_query","purchased_paid_media","poll","poll_answer","my_chat_member","chat_join_request","chat_boost","removed_chat_boost"];class EL extends hG.Composer{constructor($,w){var E;super();if(this.token=$,this.pollingRunning=!1,this.lastTriedUpdateId=0,this.observedUpdateTypes=new Set,this.errorHandler=async(X)=>{var G,J;if(console.error("Error in middleware while handling update",(J=(G=X.ctx)===null||G===void 0?void 0:G.update)===null||J===void 0?void 0:J.update_id,X.error),console.error("No error handler was set!"),console.error("Set your own error handler with `bot.catch = ...`"),this.pollingRunning)console.error("Stopping bot"),await this.stop();throw X},!$)throw Error("Empty token!");this.me=w===null||w===void 0?void 0:w.botInfo,this.clientConfig=w===null||w===void 0?void 0:w.client,this.ContextConstructor=(E=w===null||w===void 0?void 0:w.ContextConstructor)!==null&&E!==void 0?E:ik.Context,this.api=new eH.Api($,this.clientConfig)}set botInfo($){this.me=$}get botInfo(){if(this.me===void 0)throw Error("Bot information unavailable! Make sure to call `await bot.init()` before accessing `bot.botInfo`!");return this.me}on($,...w){for(let[E]of(0,$L.parse)($).flatMap($L.preprocess))this.observedUpdateTypes.add(E);return super.on($,...w)}reaction($,...w){return this.observedUpdateTypes.add("message_reaction"),super.reaction($,...w)}isInited(){return this.me!==void 0}async init($){var w;if(!this.isInited()){$w("Initializing bot"),(w=this.mePromise)!==null&&w!==void 0||(this.mePromise=wL(()=>this.api.getMe($),$));let E;try{E=await this.mePromise}finally{this.mePromise=void 0}if(this.me===void 0)this.me=E;else $w("Bot info was set by now, will not overwrite")}$w(`I am ${this.me.username}!`)}async handleUpdates($){for(let w of $){this.lastTriedUpdateId=w.update_id;try{await this.handleUpdate(w)}catch(E){if(E instanceof hG.BotError)await this.errorHandler(E);else throw console.error("FATAL: grammY unable to handle:",E),E}}}async handleUpdate($,w){if(this.me===void 0)throw Error("Bot not initialized! Either call `await bot.init()`, or directly set the `botInfo` option in the `Bot` constructor to specify a known bot info object.");$w(`Processing update ${$.update_id}`);let E=new eH.Api(this.token,this.clientConfig,w),X=this.api.config.installedTransformers();if(X.length>0)E.config.use(...X);let G=new this.ContextConstructor($,E,this.me);try{await(0,hG.run)(this.middleware(),G)}catch(J){throw YX(`Error in middleware for update ${$.update_id}`),new hG.BotError(J,G)}}async start($){var w,E,X;let G=[];if(!this.isInited())G.push(this.init((w=this.pollingAbortController)===null||w===void 0?void 0:w.signal));if(this.pollingRunning){await Promise.all(G),$w("Simple long polling already running!");return}this.pollingRunning=!0,this.pollingAbortController=new ak.AbortController;try{G.push(wL(async()=>{var J;await this.api.deleteWebhook({drop_pending_updates:$===null||$===void 0?void 0:$.drop_pending_updates},(J=this.pollingAbortController)===null||J===void 0?void 0:J.signal)},(E=this.pollingAbortController)===null||E===void 0?void 0:E.signal)),await Promise.all(G),await((X=$===null||$===void 0?void 0:$.onStart)===null||X===void 0?void 0:X.call($,this.botInfo))}catch(J){throw this.pollingRunning=!1,this.pollingAbortController=void 0,J}if(!this.pollingRunning)return;lk(this.observedUpdateTypes,$===null||$===void 0?void 0:$.allowed_updates),this.use=sk,$w("Starting simple long polling"),await this.loop($),$w("Middleware is done running")}async stop(){var $;if(this.pollingRunning){$w("Stopping bot, saving update offset"),this.pollingRunning=!1,($=this.pollingAbortController)===null||$===void 0||$.abort();let w=this.lastTriedUpdateId+1;await this.api.getUpdates({offset:w,limit:1}).finally(()=>this.pollingAbortController=void 0)}else $w("Bot is not running!")}isRunning(){return this.pollingRunning}catch($){this.errorHandler=$}async loop($){var w,E;let X=$===null||$===void 0?void 0:$.limit,G=(w=$===null||$===void 0?void 0:$.timeout)!==null&&w!==void 0?w:30,J=(E=$===null||$===void 0?void 0:$.allowed_updates)!==null&&E!==void 0?E:[];try{while(this.pollingRunning){let A=await this.fetchUpdates({limit:X,timeout:G,allowed_updates:J});if(A===void 0)break;await this.handleUpdates(A),J=void 0}}finally{this.pollingRunning=!1}}async fetchUpdates({limit:$,timeout:w,allowed_updates:E}){var X;let G=this.lastTriedUpdateId+1,J=void 0;do try{J=await this.api.getUpdates({offset:G,limit:$,timeout:w,allowed_updates:E},(X=this.pollingAbortController)===null||X===void 0?void 0:X.signal)}catch(A){await this.handlePollingError(A)}while(J===void 0&&this.pollingRunning);return J}async handlePollingError($){var w;if(!this.pollingRunning){$w("Pending getUpdates request cancelled");return}let E=3;if($ instanceof FN.GrammyError){if(YX($.message),$.error_code===401||$.error_code===409)throw $;else if($.error_code===429)YX("Bot API server is closing."),E=(w=$.parameters.retry_after)!==null&&w!==void 0?w:E}else YX($);YX(`Call to getUpdates failed, retrying in ${E} seconds ...`),await jN(E)}}RN.Bot=EL;async function wL($,w){let X=50;async function G(A){let D=!1,N="rethrow";if(A instanceof FN.HttpError)D=!0,N="retry";else if(A instanceof FN.GrammyError){if(A.error_code>=500)D=!0,N="retry";else if(A.error_code===429){let W=A.parameters.retry_after;if(typeof W==="number")await jN(W,w),X=50;else D=!0;N="retry"}}if(D){if(X!==50)await jN(X,w);X=Math.min(1200000,2*X)}return N}let J={ok:!1};while(!J.ok)try{J={ok:!0,value:await $()}}catch(A){switch(YX(A),await G(A)){case"retry":continue;case"rethrow":throw A}}return J.value}async function jN($,w){let E,X;function G(){if(X===null||X===void 0||X(Error("Aborted delay")),E!==void 0)clearTimeout(E)}try{await new Promise((J,A)=>{if(X=A,w===null||w===void 0?void 0:w.aborted){G();return}w===null||w===void 0||w.addEventListener("abort",G),E=setTimeout(J,1000*$)})}finally{w===null||w===void 0||w.removeEventListener("abort",G)}}function lk($,w=RN.DEFAULT_UPDATE_TYPES){let E=Array.from($).filter((X)=>!w.includes(X));if(E.length>0)dk(`You registered listeners for the following update types, but you did not specify them in \`allowed_updates\` so they may not be received: ${E.map((X)=>`'${X}'`).join(", ")}`)}function sk(){throw Error(`It looks like you are registering more listeners on your bot from within other listeners! This means that every time your bot handles a message like this one, new listeners will be added. This list grows until your machine crashes, so grammY throws this error to tell you that you should probably do things a bit differently. If you're unsure how to resolve this problem, you can ask in the group chat: https://telegram.me/grammyjs
|
|
408
408
|
|
|
409
|
-
On the other hand, if you actually know what you're doing and you do need to install further middleware while your bot is running, consider installing a composer instance on your bot, and in turn augment the composer after the fact. This way, you can circumvent this protection against memory leaks.`)}var pk=ON()});var GL=Z((XL)=>{Object.defineProperty(XL,"__esModule",{value:!0});XL.API_CONSTANTS=void 0;var EL=jN(),ok=[...EL.DEFAULT_UPDATE_TYPES,"chat_member","message_reaction","message_reaction_count"],tk={can_send_messages:!0,can_send_audios:!0,can_send_documents:!0,can_send_photos:!0,can_send_videos:!0,can_send_video_notes:!0,can_send_voice_notes:!0,can_send_polls:!0,can_send_other_messages:!0,can_add_web_page_previews:!0,can_change_info:!0,can_invite_users:!0,can_edit_tag:!0,can_pin_messages:!0,can_manage_topics:!0};XL.API_CONSTANTS={DEFAULT_UPDATE_TYPES:EL.DEFAULT_UPDATE_TYPES,ALL_UPDATE_TYPES:ok,ALL_CHAT_PERMISSIONS:tk};Object.freeze(XL.API_CONSTANTS)});var DL=Z((JL)=>{Object.defineProperty(JL,"__esModule",{value:!0});JL.InlineQueryResultBuilder=void 0;function O$($){return{...$,...RN($)}}function RN($){return{text(w,E={}){let X={message_text:w,...E};return{...$,input_message_content:X}},location(w,E,X={}){let G={latitude:w,longitude:E,...X};return{...$,input_message_content:G}},venue(w,E,X,G,J){let A={title:w,latitude:E,longitude:X,address:G,...J};return{...$,input_message_content:A}},contact(w,E,X={}){let G={first_name:w,phone_number:E,...X};return{...$,input_message_content:G}},invoice(w,E,X,G,J,A,D={}){let N={title:w,description:E,payload:X,provider_token:G,currency:J,prices:A,...D};return{...$,input_message_content:N}}}}JL.InlineQueryResultBuilder={article($,w,E={}){return RN({type:"article",id:$,title:w,...E})},audio($,w,E,X={}){return O$({type:"audio",id:$,title:w,audio_url:typeof E==="string"?E:E.href,...X})},audioCached($,w,E={}){return O$({type:"audio",id:$,audio_file_id:w,...E})},contact($,w,E,X={}){return O$({type:"contact",id:$,phone_number:w,first_name:E,...X})},documentPdf($,w,E,X={}){return O$({type:"document",mime_type:"application/pdf",id:$,title:w,document_url:typeof E==="string"?E:E.href,...X})},documentZip($,w,E,X={}){return O$({type:"document",mime_type:"application/zip",id:$,title:w,document_url:typeof E==="string"?E:E.href,...X})},documentCached($,w,E,X={}){return O$({type:"document",id:$,title:w,document_file_id:E,...X})},game($,w,E={}){return{type:"game",id:$,game_short_name:w,...E}},gif($,w,E,X={}){return O$({type:"gif",id:$,gif_url:typeof w==="string"?w:w.href,thumbnail_url:typeof E==="string"?E:E.href,...X})},gifCached($,w,E={}){return O$({type:"gif",id:$,gif_file_id:w,...E})},location($,w,E,X,G={}){return O$({type:"location",id:$,title:w,latitude:E,longitude:X,...G})},mpeg4gif($,w,E,X={}){return O$({type:"mpeg4_gif",id:$,mpeg4_url:typeof w==="string"?w:w.href,thumbnail_url:typeof E==="string"?E:E.href,...X})},mpeg4gifCached($,w,E={}){return O$({type:"mpeg4_gif",id:$,mpeg4_file_id:w,...E})},photo($,w,E={}){let X=typeof w==="string"?w:w.href;return O$({type:"photo",id:$,photo_url:X,thumbnail_url:X,...E})},photoCached($,w,E={}){return O$({type:"photo",id:$,photo_file_id:w,...E})},stickerCached($,w,E={}){return O$({type:"sticker",id:$,sticker_file_id:w,...E})},venue($,w,E,X,G,J={}){return O$({type:"venue",id:$,title:w,latitude:E,longitude:X,address:G,...J})},videoHtml($,w,E,X,G={}){return RN({type:"video",mime_type:"text/html",id:$,title:w,video_url:typeof E==="string"?E:E.href,thumbnail_url:typeof X==="string"?X:X.href,...G})},videoMp4($,w,E,X,G={}){return O$({type:"video",mime_type:"video/mp4",id:$,title:w,video_url:typeof E==="string"?E:E.href,thumbnail_url:typeof X==="string"?X:X.href,...G})},videoCached($,w,E,X={}){return O$({type:"video",id:$,title:w,video_file_id:E,...X})},voice($,w,E,X={}){return O$({type:"voice",id:$,title:w,voice_url:typeof E==="string"?E:E.href,...X})},voiceCached($,w,E,X={}){return O$({type:"voice",id:$,title:w,voice_file_id:E,...X})}}});var OL=Z((NL)=>{Object.defineProperty(NL,"__esModule",{value:!0});NL.InputMediaBuilder=void 0;NL.InputMediaBuilder={photo($,w={}){return{type:"photo",media:$,...w}},video($,w={}){return{type:"video",media:$,...w}},animation($,w={}){return{type:"animation",media:$,...w}},audio($,w={}){return{type:"audio",media:$,...w}},document($,w={}){return{type:"document",media:$,...w}}}});var FL=Z((HL)=>{Object.defineProperty(HL,"__esModule",{value:!0});HL.InlineKeyboard=HL.Keyboard=void 0;class s${constructor($=[[]]){this.keyboard=$}add(...$){var w;return(w=this.keyboard[this.keyboard.length-1])===null||w===void 0||w.push(...$),this}row(...$){return this.keyboard.push($),this}text($,w){return this.add(s$.text($,w))}static text($,w){return typeof w==="string"?{text:$,style:w}:{text:$,...w}}requestUsers($,w,E={}){return this.add(s$.requestUsers($,w,E))}static requestUsers($,w,E={}){return typeof $==="string"?{text:$,request_users:{request_id:w,...E}}:{...$,request_users:{request_id:w,...E}}}requestChat($,w,E={chat_is_channel:!1}){return this.add(s$.requestChat($,w,E))}static requestChat($,w,E={chat_is_channel:!1}){let X={request_id:w,...E};return typeof $==="string"?{text:$,request_chat:X}:{...$,request_chat:X}}requestContact($){return this.add(s$.requestContact($))}static requestContact($){return typeof $==="string"?{text:$,request_contact:!0}:{...$,request_contact:!0}}requestLocation($){return this.add(s$.requestLocation($))}static requestLocation($){return typeof $==="string"?{text:$,request_location:!0}:{...$,request_location:!0}}requestPoll($,w){return this.add(s$.requestPoll($,w))}static requestPoll($,w){let E={type:w};return typeof $==="string"?{text:$,request_poll:E}:{...$,request_poll:E}}webApp($,w){return this.add(s$.webApp($,w))}static webApp($,w){let E={url:w};return typeof $==="string"?{text:$,web_app:E}:{...$,web_app:E}}style($){let w=this.keyboard.length;if(w===0)throw Error("Need to add a button before applying a style!");let E=this.keyboard[w-1],X=E.length;if(X===0)throw Error("Need to add a button before applying a style!");let G=E[X-1];if(typeof G==="string")G={text:G},E[X-1]=G;return G.style=$,this}danger(){return this.style("danger")}success(){return this.style("success")}primary(){return this.style("primary")}icon($){let w=this.keyboard.length;if(w===0)throw Error("Need to add a button before adding an icon!");let E=this.keyboard[w-1],X=E.length;if(X===0)throw Error("Need to add a button before adding an icon!");let G=E[X-1];if(typeof G==="string")G={text:G},E[X-1]=G;return G.icon_custom_emoji_id=$,this}persistent($=!0){return this.is_persistent=$,this}selected($=!0){return this.selective=$,this}oneTime($=!0){return this.one_time_keyboard=$,this}resized($=!0){return this.resize_keyboard=$,this}placeholder($){return this.input_field_placeholder=$,this}toTransposed(){let $=this.keyboard,w=UL($);return this.clone(w)}toFlowed($,w={}){let E=this.keyboard,X=YL(E,$,w);return this.clone(X)}clone($=this.keyboard){let w=new s$($.map((E)=>E.slice()));return w.is_persistent=this.is_persistent,w.selective=this.selective,w.one_time_keyboard=this.one_time_keyboard,w.resize_keyboard=this.resize_keyboard,w.input_field_placeholder=this.input_field_placeholder,w}append(...$){for(let w of $){let E=s$.from(w);this.keyboard.push(...E.keyboard.map((X)=>X.slice()))}return this}build(){return this.keyboard}static from($){if($ instanceof s$)return $.clone();function w(E){return typeof E==="string"?s$.text(E):E}return new s$($.map((E)=>E.map(w)))}}HL.Keyboard=s$;class L${constructor($=[[]]){this.inline_keyboard=$}add(...$){var w;return(w=this.inline_keyboard[this.inline_keyboard.length-1])===null||w===void 0||w.push(...$),this}row(...$){return this.inline_keyboard.push($),this}url($,w){return this.add(L$.url($,w))}static url($,w){return typeof $==="string"?{text:$,url:w}:{...$,url:w}}text($,w=typeof $==="string"?$:$.text){return this.add(L$.text($,w))}static text($,w=typeof $==="string"?$:$.text){return typeof $==="string"?{text:$,callback_data:w}:{...$,callback_data:w}}webApp($,w){return this.add(L$.webApp($,w))}static webApp($,w){let E=typeof w==="string"?{url:w}:w;return typeof $==="string"?{text:$,web_app:E}:{...$,web_app:E}}login($,w){return this.add(L$.login($,w))}static login($,w){let E=typeof w==="string"?{url:w}:w;return typeof $==="string"?{text:$,login_url:E}:{...$,login_url:E}}switchInline($,w=""){return this.add(L$.switchInline($,w))}static switchInline($,w=""){return typeof $==="string"?{text:$,switch_inline_query:w}:{...$,switch_inline_query:w}}switchInlineCurrent($,w=""){return this.add(L$.switchInlineCurrent($,w))}static switchInlineCurrent($,w=""){return typeof $==="string"?{text:$,switch_inline_query_current_chat:w}:{...$,switch_inline_query_current_chat:w}}switchInlineChosen($,w={}){return this.add(L$.switchInlineChosen($,w))}static switchInlineChosen($,w={}){return typeof $==="string"?{text:$,switch_inline_query_chosen_chat:w}:{...$,switch_inline_query_chosen_chat:w}}copyText($,w){return this.add(L$.copyText($,w))}static copyText($,w){let E=typeof w==="string"?{text:w}:w;return typeof $==="string"?{text:$,copy_text:E}:{...$,copy_text:E}}game($){return this.add(L$.game($))}static game($){let w={};return typeof $==="string"?{text:$,callback_game:w}:{...$,callback_game:w}}pay($){return this.add(L$.pay($))}static pay($){return typeof $==="string"?{text:$,pay:!0}:{...$,pay:!0}}style($){let w=this.inline_keyboard.length;if(w===0)throw Error("Need to add a button before applying a style!");let E=this.inline_keyboard[w-1],X=E.length;if(X===0)throw Error("Need to add a button before applying a style!");return E[X-1].style=$,this}danger(){return this.style("danger")}success(){return this.style("success")}primary(){return this.style("primary")}icon($){let w=this.inline_keyboard.length;if(w===0)throw Error("Need to add a button before adding an icon!");let E=this.inline_keyboard[w-1],X=E.length;if(X===0)throw Error("Need to add a button before adding an icon!");return E[X-1].icon_custom_emoji_id=$,this}toTransposed(){let $=this.inline_keyboard,w=UL($);return new L$(w)}toFlowed($,w={}){let E=this.inline_keyboard,X=YL(E,$,w);return new L$(X)}clone(){return new L$(this.inline_keyboard.map(($)=>$.slice()))}append(...$){for(let w of $){let E=L$.from(w);this.inline_keyboard.push(...E.inline_keyboard.map((X)=>X.slice()))}return this}static from($){if($ instanceof L$)return $.clone();return new L$($.map((w)=>w.slice()))}}HL.InlineKeyboard=L$;function UL($){var w;let E=[];for(let X=0;X<$.length;X++){let G=$[X];for(let J=0;J<G.length;J++){let A=G[J];((w=E[J])!==null&&w!==void 0?w:E[J]=[]).push(A)}}return E}function YL($,w,{fillLastRow:E=!1}){var X;let G=w;if(E)G=$.map((D)=>D.length).reduce((D,N)=>D+N,0)%w;let J=[];for(let A of $)for(let D of A){let N=Math.max(0,J.length-1),W=N===0?G:w,O=(X=J[N])!==null&&X!==void 0?X:J[N]=[];if(O.length===W)O=[],J.push(O);O.push(D)}return J}});var BL=Z((zL)=>{Object.defineProperty(zL,"__esModule",{value:!0});zL.MemorySessionStorage=void 0;zL.session=sk;zL.lazySession=$b;zL.enhanceStorage=Eb;var dk=mw(),lk=(0,dk.debug)("grammy:session");function sk($={}){return $.type==="multi"?ek($):ak($)}function ak($){let{initial:w,storage:E,getSessionKey:X,custom:G}=zN($);return async(J,A)=>{let D=new FA(E,J,"session",w),N=await X(J);await D.init(N,{custom:G,lazy:!1}),await A(),await D.finish()}}function ek($){let w=Object.keys($).filter((X)=>X!=="type"),E=Object.fromEntries(w.map((X)=>[X,zN($[X])]));return async(X,G)=>{X.session={};let J=await Promise.all(w.map(async(A)=>{let{initial:D,storage:N,getSessionKey:W,custom:O}=E[A],Y=new FA(N,X.session,A,D),H=await W(X);return await Y.init(H,{custom:O,lazy:!1}),Y}));if(await G(),X.session==null)J.forEach((A)=>A.delete());await Promise.all(J.map((A)=>A.finish()))}}function $b($={}){if($.type!==void 0&&$.type!=="single")throw Error("Cannot use lazy multi sessions!");let{initial:w,storage:E,getSessionKey:X,custom:G}=zN($);return async(J,A)=>{let D=new FA(E,J,"session",w),N=await X(J);await D.init(N,{custom:G,lazy:!0}),await A(),await D.finish()}}class FA{constructor($,w,E,X){this.storage=$,this.obj=w,this.prop=E,this.initial=X,this.fetching=!1,this.read=!1,this.wrote=!1}load(){if(this.key===void 0)return;if(this.wrote)return;if(this.promise===void 0)this.fetching=!0,this.promise=Promise.resolve(this.storage.read(this.key)).then(($)=>{var w;if(this.fetching=!1,this.wrote)return this.value;if($!==void 0)return this.value=$,$;if($=(w=this.initial)===null||w===void 0?void 0:w.call(this),$!==void 0)this.wrote=!0,this.value=$;return $});return this.promise}async init($,w){if(this.key=$,!w.lazy)await this.load();Object.defineProperty(this.obj,this.prop,{enumerable:!0,get:()=>{if($===void 0){let E=ML("access",w);throw Error(E)}if(this.read=!0,!w.lazy||this.wrote)return this.value;return this.load(),this.fetching?this.promise:this.value},set:(E)=>{if($===void 0){let X=ML("assign",w);throw Error(X)}this.wrote=!0,this.fetching=!1,this.value=E}})}delete(){Object.assign(this.obj,{[this.prop]:void 0})}async finish(){if(this.key!==void 0){if(this.read)await this.load();if(this.read||this.wrote){let $=await this.value;if($==null)await this.storage.delete(this.key);else await this.storage.write(this.key,$)}}}}function zN($={}){let{prefix:w="",getSessionKey:E=jL,initial:X,storage:G}=$;if(G==null)lk("Storing session data in memory, all data will be lost when the bot restarts."),G=new TN;return{initial:X,storage:G,getSessionKey:async(A)=>{let D=await E(A);return D===void 0?void 0:w+D},custom:E!==jL}}function jL($){var w;return(w=$.chatId)===null||w===void 0?void 0:w.toString()}function ML($,w){let{lazy:E=!1,custom:X}=w;return`Cannot ${$} ${E?"lazy ":""}session data because ${X?"the custom `getSessionKey` function returned undefined for this update":"this update does not belong to a chat, so the session key is undefined"}!`}function wb($){return $===void 0||typeof $==="object"&&$!==null&&"__d"in $}function Eb($){let{storage:w,millisecondsToLive:E,migrations:X}=$;if(w=Xb(w),E!==void 0)w=Gb(w,E);if(X!==void 0)w=Jb(w,X);return Ab(w)}function Xb($){return{read:async(w)=>{let E=await $.read(w);return wb(E)?E:{__d:E}},write:(w,E)=>$.write(w,E),delete:(w)=>$.delete(w)}}function Gb($,w){let E={read:async(X)=>{let G=await $.read(X);if(G===void 0)return;if(G.e===void 0)return await E.write(X,G),G;if(G.e<Date.now()){await E.delete(X);return}return G},write:async(X,G)=>{G.e=RL(G,w).expires,await $.write(X,G)},delete:(X)=>$.delete(X)};return E}function Jb($,w){let E=Object.keys(w).map((W)=>parseInt(W)).sort((W,O)=>W-O),X=E.length;if(X===0)throw Error("No migrations given!");let G=E[0],J=X-1,A=E[J],D=new Map;E.forEach((W,O)=>D.set(W,O));function N(W){let O=J;while(W<=E[O])O--;return O}return{read:async(W)=>{var O;let Y=await $.read(W);if(Y===void 0)return Y;let{__d:H,v:L=G-1}=Y,F=1+((O=D.get(L))!==null&&O!==void 0?O:N(L));for(;F<X;F++)H=w[E[F]](H);return{...Y,v:A,__d:H}},write:(W,O)=>$.write(W,{v:A,...O}),delete:(W)=>$.delete(W)}}function Ab($){return{read:(w)=>Promise.resolve($.read(w)).then((E)=>E===null||E===void 0?void 0:E.__d),write:(w,E)=>$.write(w,{__d:E}),delete:(w)=>$.delete(w)}}class TN{constructor($){this.timeToLive=$,this.storage=new Map}read($){let w=this.storage.get($);if(w===void 0)return;if(w.expires!==void 0&&w.expires<Date.now()){this.delete($);return}return w.session}readAll(){return this.readAllValues()}readAllKeys(){return Array.from(this.storage.keys())}readAllValues(){return Array.from(this.storage.keys()).map(($)=>this.read($)).filter(($)=>$!==void 0)}readAllEntries(){return Array.from(this.storage.keys()).map(($)=>[$,this.read($)]).filter(($)=>$[1]!==void 0)}has($){return this.storage.has($)}write($,w){this.storage.set($,RL(w,this.timeToLive))}delete($){this.storage.delete($)}}zL.MemorySessionStorage=TN;function RL($,w){if(w!==void 0&&w<1/0){let E=Date.now();return{session:$,expires:E+w}}else return{session:$}}});var VL=Z((IL)=>{Object.defineProperty(IL,"__esModule",{value:!0});IL.adapters=void 0;var R$="X-Telegram-Bot-Api-Secret-Token",jA=R$.toLowerCase(),Rw="secret token is wrong",YX=()=>new Response(null,{status:200}),HX=($)=>new Response($,{status:200,headers:{"Content-Type":"application/json"}}),LX=()=>new Response('"unauthorized"',{status:401,statusText:Rw}),Ob=($,w,E)=>({get update(){var X;return JSON.parse((X=$.body)!==null&&X!==void 0?X:"{}")},header:$.headers[R$],end:()=>E(null,{statusCode:200}),respond:(X)=>E(null,{statusCode:200,headers:{"Content-Type":"application/json"},body:X}),unauthorized:()=>E(null,{statusCode:401})}),Ub=($,w)=>{let E;return{get update(){var X;return JSON.parse((X=$.body)!==null&&X!==void 0?X:"{}")},header:$.headers[R$],end:()=>E({statusCode:200}),respond:(X)=>E({statusCode:200,headers:{"Content-Type":"application/json"},body:X}),unauthorized:()=>E({statusCode:401}),handlerReturn:new Promise((X)=>E=X)}},Yb=($,w)=>{var E,X;return{get update(){return w.body},header:(X=(E=$.res)===null||E===void 0?void 0:E.headers)===null||X===void 0?void 0:X[R$],end:()=>$.res={status:200,body:""},respond:(G)=>{var J,A,D,N;(A=(J=$.res)===null||J===void 0?void 0:J.set)===null||A===void 0||A.call(J,"Content-Type","application/json"),(N=(D=$.res)===null||D===void 0?void 0:D.send)===null||N===void 0||N.call(D,G)},unauthorized:()=>{var G,J;(J=(G=$.res)===null||G===void 0?void 0:G.send)===null||J===void 0||J.call(G,401,Rw)}}},Hb=($)=>{let w;return{get update(){return $.json()},header:$.headers.get(R$)||void 0,end:()=>w({status:204}),respond:(E)=>w({jsonBody:E}),unauthorized:()=>w({status:401,body:Rw}),handlerReturn:new Promise((E)=>w=E)}},Lb=($)=>{let w;return{get update(){return $.json()},header:$.headers.get(R$)||void 0,end:()=>{w(YX())},respond:(E)=>{w(HX(E))},unauthorized:()=>{w(LX())},handlerReturn:new Promise((E)=>w=E)}},Fb=($)=>{let w;return $.respondWith(new Promise((E)=>{w=E})),{get update(){return $.request.json()},header:$.request.headers.get(R$)||void 0,end:()=>{w(YX())},respond:(E)=>{w(HX(E))},unauthorized:()=>{w(LX())}}},jb=($)=>{let w;return{get update(){return $.json()},header:$.headers.get(R$)||void 0,end:()=>{w(YX())},respond:(E)=>{w(HX(E))},unauthorized:()=>{w(LX())},handlerReturn:new Promise((E)=>w=E)}},Mb=($,w)=>({get update(){return $.body},header:$.header(R$),end:()=>w.end(),respond:(E)=>{w.set("Content-Type","application/json"),w.send(E)},unauthorized:()=>{w.status(401).send(Rw)}}),Rb=($,w)=>({get update(){return $.body},header:$.headers[jA],end:()=>w.send(""),respond:(E)=>w.headers({"Content-Type":"application/json"}).send(E),unauthorized:()=>w.code(401).send(Rw)}),zb=($)=>{let w;return{get update(){return $.req.json()},header:$.req.header(R$),end:()=>{w($.body(""))},respond:(E)=>{w($.json(E))},unauthorized:()=>{$.status(401),w($.body(""))},handlerReturn:new Promise((E)=>w=E)}},QL=($,w)=>{let E=$.headers[jA];return{get update(){return new Promise((X,G)=>{let J=[];$.on("data",(A)=>J.push(A)).once("end",()=>{let A=Buffer.concat(J).toString("utf-8");try{X(JSON.parse(A))}catch(D){G(D)}}).once("error",G)})},header:Array.isArray(E)?E[0]:E,end:()=>w.end(),respond:(X)=>w.writeHead(200,{"Content-Type":"application/json"}).end(X),unauthorized:()=>w.writeHead(401).end(Rw)}},Tb=($)=>({get update(){return $.request.body},header:$.get(R$)||void 0,end:()=>{$.body=""},respond:(w)=>{$.set("Content-Type","application/json"),$.response.body=w},unauthorized:()=>{$.status=401}}),Bb=($,w)=>({get update(){return $.body},header:$.headers[jA],end:()=>w.end(),respond:(E)=>w.status(200).json(E),unauthorized:()=>w.status(401).send(Rw)}),Qb=($)=>({get update(){return $.body},header:$.headers.get(R$)||void 0,end:()=>$.response.sendStatus(200),respond:(w)=>$.response.status(200).send(w),unauthorized:()=>$.response.status(401).send(Rw)}),Ib=($)=>({get update(){return $.request.body.json()},header:$.request.headers.get(R$)||void 0,end:()=>{$.response.status=200},respond:(w)=>{$.response.type="json",$.response.body=w},unauthorized:()=>{$.response.status=401}}),Kb=($)=>({get update(){return $.request.json()},header:$.request.headers.get(R$)||void 0,end:()=>$.respondWith(YX()),respond:(w)=>$.respondWith(HX(w)),unauthorized:()=>$.respondWith(LX())}),Vb=($)=>{let w;return{get update(){return $.json()},header:$.headers.get(R$)||void 0,end:()=>{if(w)w(YX())},respond:(E)=>{if(w)w(HX(E))},unauthorized:()=>{if(w)w(LX())},handlerReturn:new Promise((E)=>w=E)}},Pb=({request:$})=>{let w;return{get update(){return $.json()},header:$.headers.get(R$)||void 0,end:()=>{if(w)w(YX())},respond:(E)=>{if(w)w(HX(E))},unauthorized:()=>{if(w)w(LX())},handlerReturn:new Promise((E)=>w=E)}},qb=($,w)=>{var E;return{get update(){return $.json()},header:(E=$.headers.get(R$))!==null&&E!==void 0?E:void 0,end:()=>w.end(null),respond:(X)=>w.send(200,X),unauthorized:()=>w.send(401,Rw)}},Sb=($)=>{let w;return{get update(){return $.body},header:$.headers[jA],end(){w("")},respond(E){$.set.headers["content-type"]="application/json",w(E)},unauthorized(){$.set.status=401,w("")},handlerReturn:new Promise((E)=>w=E)}};IL.adapters={"aws-lambda":Ob,"aws-lambda-async":Ub,azure:Yb,"azure-v4":Hb,bun:Lb,cloudflare:Fb,"cloudflare-mod":jb,elysia:Sb,express:Mb,fastify:Rb,hono:zb,http:QL,https:QL,koa:Tb,"next-js":Bb,nhttp:Qb,oak:Ib,serveHttp:Kb,"std/http":Vb,sveltekit:Pb,worktop:qb}});var kL=Z((SL)=>{Object.defineProperty(SL,"__esModule",{value:!0});SL.webhookCallback=_b;var qL=mw(),kb=VL(),PL=(0,qL.debug)("grammy:error"),bb=($,w,E,X=()=>w('"unauthorized"'))=>({update:Promise.resolve($),respond:w,header:E,unauthorized:X}),Zb={...kb.adapters,callback:bb};function Cb($,w){if(w===void 0)return!0;if($===void 0)return!1;let E=new TextEncoder,X=E.encode($),G=E.encode(w);if(X.length!==G.length)return!1;let J=0;for(let A=0;A<G.length;A++){let D=A<X.length?X[A]:0,N=G[A];J|=D^N}return J===0}function _b($,w=qL.defaultAdapter,E,X,G){if($.isRunning())throw Error("Bot is already running via long polling, the webhook setup won't receive any updates!");else $.start=()=>{throw Error("You already started the bot via webhooks, calling `bot.start()` starts the bot with long polling and this will prevent your webhook setup from receiving any updates!")};let{onTimeout:J="throw",timeoutMilliseconds:A=1e4,secretToken:D}=typeof E==="object"?E:{onTimeout:E,timeoutMilliseconds:X,secretToken:G},N=!1,W=typeof w==="string"?Zb[w]:w;return async(...O)=>{var Y;let H=W(...O);if(!N)await $.init(),N=!0;if(!Cb(H.header,D))return await H.unauthorized(),H.handlerReturn;let L=!1,F={async send(j){L=!0,await H.respond(j)}};if(await vb($.handleUpdate(await H.update,F),typeof J==="function"?()=>J(...O):J,A),!L)(Y=H.end)===null||Y===void 0||Y.call(H);return H.handlerReturn}}function vb($,w,E){if(E===1/0)return $;return new Promise((X,G)=>{let J=setTimeout(()=>{if(PL(`Request timed out after ${E} ms`),w==="throw")G(Error(`Request timed out after ${E} ms`));else{if(typeof w==="function")w();X()}let A=Date.now();$.finally(()=>{let D=Date.now()-A;PL(`Request completed ${D} ms after timeout!`)})},E);$.then(X).catch(G).finally(()=>clearTimeout(J))})}});var CL=Z((P0)=>{var xb=P0&&P0.__createBinding||(Object.create?function($,w,E,X){if(X===void 0)X=E;var G=Object.getOwnPropertyDescriptor(w,E);if(!G||("get"in G?!w.__esModule:G.writable||G.configurable))G={enumerable:!0,get:function(){return w[E]}};Object.defineProperty($,X,G)}:function($,w,E,X){if(X===void 0)X=E;$[X]=w[E]}),FX=P0&&P0.__exportStar||function($,w){for(var E in $)if(E!=="default"&&!Object.prototype.hasOwnProperty.call(w,E))xb(w,$,E)};Object.defineProperty(P0,"__esModule",{value:!0});P0.HttpError=P0.GrammyError=P0.Api=P0.matchFilter=P0.Composer=P0.Context=P0.InputFile=P0.BotError=P0.Bot=void 0;var bL=jN();Object.defineProperty(P0,"Bot",{enumerable:!0,get:function(){return bL.Bot}});Object.defineProperty(P0,"BotError",{enumerable:!0,get:function(){return bL.BotError}});var yb=DN();Object.defineProperty(P0,"InputFile",{enumerable:!0,get:function(){return yb.InputFile}});var gb=GA();Object.defineProperty(P0,"Context",{enumerable:!0,get:function(){return gb.Context}});FX(GL(),P0);FX(DL(),P0);FX(OL(),P0);FX(FL(),P0);FX(BL(),P0);FX(kL(),P0);var ub=a8();Object.defineProperty(P0,"Composer",{enumerable:!0,get:function(){return ub.Composer}});var hb=EA();Object.defineProperty(P0,"matchFilter",{enumerable:!0,get:function(){return hb.matchFilter}});var cb=UN();Object.defineProperty(P0,"Api",{enumerable:!0,get:function(){return cb.Api}});var ZL=OA();Object.defineProperty(P0,"GrammyError",{enumerable:!0,get:function(){return ZL.GrammyError}});Object.defineProperty(P0,"HttpError",{enumerable:!0,get:function(){return ZL.HttpError}})});function QN($){let w=new jX.InlineKeyboard;for(let E of $){for(let X of E)w.text(X.label,X.value);w.row()}return w}function mb($){let w=O0(),E=w.gateway.telegram.token;if(!E)throw Error("Telegram token is not configured.");let X=new jX.Bot(E),G=new Map,J=null;function A(H){let L=w.gateway.telegram.authorized_users.map(String);return L.length>0&&L.includes(String(H))}function D(H){let L=Date.now();if(G.has(H))return!0;G.set(H,L);for(let[F,j]of G)if(L-j>nb)G.delete(F);return!1}function N(H){if(!H)return!1;return H.getTime()<$}async function W(H){let L=await X.api.getFile(H),F=await fetch(`https://api.telegram.org/file/bot${E}/${L.file_path}`);return new Uint8Array(await F.arrayBuffer())}async function O(H){if(J)await J(H)}function Y(H,L,F){let j=H.from;return{platform:"telegram",chatId:String(H.chat?.id??H.callbackQuery?.message?.chat.id??""),userId:String(j.id),username:j.username,displayName:[j.first_name,j.last_name].filter(Boolean).join(" ").trim()||void 0,text:L,platformMessageId:String(H.msg?.message_id??H.message?.message_id??""),attachments:F}}return{platform:"telegram",async start(H){J=H;let L=["start","help","status","mode","cwd","agent","tasks","task","approve","reject","assign","jobs","run","mem","sessions","session"];X.command(L,async(F)=>{if(!F.from||!A(F.from.id))return;let j=String(F.message?.message_id??"");if(j&&D(`cmd:${j}`))return;if(N(F.message?.date?new Date(F.message.date*1000):void 0))return;let M=F.message?.text?.split(" ")[0]?.replace(/^\//,"").split("@")[0]??"help",z=F.message?.text?.split(" ").slice(1).join(" ")??"",B=z?`/${M} ${z}`:`/${M}`;await O(Y(F,B))}),X.on("message",async(F)=>{if(!F.from||!A(F.from.id))return;let j=String(F.message?.message_id??"");if(j&&D(`msg:${j}`))return;if(N(F.message?.date?new Date(F.message.date*1000):void 0))return;let M=[];if(F.message?.voice)try{M.push({kind:"audio",data:await W(F.message.voice.file_id),mimeType:F.message.voice.mime_type??"audio/ogg",format:"ogg",duration:F.message.voice.duration})}catch(B){BN.warn("Failed to download voice message",{err:B})}if(F.message?.audio)try{M.push({kind:"audio",data:await W(F.message.audio.file_id),mimeType:F.message.audio.mime_type??"audio/mpeg",format:(F.message.audio.mime_type??"audio/mpeg").split("/").at(1)??"mp3",duration:F.message.audio.duration})}catch(B){BN.warn("Failed to download audio message",{err:B})}let z=F.message?.text??F.message?.caption??"";if(!z&&M.length===0)return;await O(Y(F,z,M.length>0?M:void 0))}),X.on("callback_query:data",async(F)=>{if(!F.from||!A(F.from.id)||!F.callbackQuery)return;let j=F.callbackQuery.id;if(D(`cb:${j}`)){await F.answerCallbackQuery();return}let M=String(F.callbackQuery.message?.chat.id??F.chat?.id??""),z=`${M}:${F.callbackQuery.message?.message_id}`;await O({platform:"telegram",chatId:M,userId:String(F.from.id),username:F.from.username,displayName:[F.from.first_name,F.from.last_name].filter(Boolean).join(" ").trim()||void 0,text:F.callbackQuery.data??"",platformMessageId:z}),await F.answerCallbackQuery()}),BN.info("Starting Telegram gateway adapter"),X.start({allowed_updates:["message","callback_query"]})},async stop(){X.stop()},async send(H,L,F){let j={};if(F?.parseMode==="html")j.parse_mode="HTML";if(F?.buttons?.length)j.reply_markup=QN(F.buttons);let M=L.slice(0,4096),z=await X.api.sendMessage(H,M,j);return`${z.chat.id}:${z.message_id}`},async updateMessage(H,L,F,j){let[,M]=L.split(":");if(!M)return;let z={};if(j?.parseMode==="html")z.parse_mode="HTML";if(j?.buttons?.length)z.reply_markup=QN(j.buttons);try{await X.api.editMessageText(H,Number(M),F.slice(0,4096),z)}catch(B){if(!String(B instanceof Error?B.message:"").includes("message is not modified"))throw B}},async sendWithButtons(H,L,F,j){let M={reply_markup:QN(F)};if(j?.parseMode==="html")M.parse_mode="HTML";let z=await X.api.sendMessage(H,L.slice(0,4096),M);return`${z.chat.id}:${z.message_id}`},async downloadAudio(H){return W(H)},async sendAudio(H,L,F,j){let M=F==="ogg"||F==="oga"?"ogg":"mp3",z=new jX.InputFile(L,`audio.${M}`),B=j?{caption:j}:{};if(M==="ogg")await X.api.sendVoice(H,z,B);else await X.api.sendAudio(H,z,B)},async showTyping(H){try{await X.api.sendChatAction(H,"typing")}catch{}},async registerCommands(H){await X.api.setMyCommands(H.map((L)=>({command:L.command,description:L.description})))}}}var jX,BN,nb=60000;var _L=R(()=>{C$();p$();rJ();jX=AJ(CL(),1),BN=Z0("gateway:telegram");mJ("telegram",($)=>mb($))});import{existsSync as rb}from"fs";class vL{adapters=new Map;sessionLock=new r8;permissionManager=new m8;startTime=Date.now();adapterStatus=new Map;pendingSessionApprove=new Set;rateLimiter=new c8;async start(){let $=O0(),w=[];if($.gateway.telegram.enabled&&$.gateway.telegram.token)w.push("telegram");if($.gateway.slack.enabled&&$.gateway.slack.bot_token&&$.gateway.slack.app_token)w.push("slack");for(let G of w)try{let J=MY(G,this.startTime);this.adapters.set(J.platform,J),await this.safeStart(J)}catch(J){let A=n8(String(J));zE.error(`Failed to create ${G} adapter`,A),this.adapterStatus.set(G,{error:A})}for(let[,G]of this.adapters)if("registerCommands"in G)try{await G.registerCommands(pb)}catch(J){zE.warn("Failed to register bot commands",{platform:G.platform,err:J})}await _Y();let E=O0();for(let G of["telegram","slack"]){let J=E.gateway[G];if(J.enabled&&J.authorized_users.length===0)zE.warn(`${G}: authorized_users is empty \u2014 all users will be denied. Add user IDs to config.`)}let X=[...this.adapters.keys()].join(", ");zE.info(`Gateway started with adapters: ${X||"none"}`)}async stop(){this.permissionManager.denyAll(),await Promise.all([...this.adapters.values()].map(($)=>$.stop().catch(()=>{}))),this.adapters.clear()}resolvePermission($,w){return this.permissionManager.resolve($,w)}async safeStart($){try{await $.start(async(w)=>this.handleIncoming(w)),this.adapterStatus.set($.platform,{})}catch(w){this.adapterStatus.set($.platform,{error:String(w)}),zE.error(`Failed to start ${$.platform} adapter`,n8(String(w)))}}normalizeCallbackText($){if($.startsWith("task:approve:"))return`/approve ${$.slice(13)}`;if($.startsWith("task:reject:"))return`/reject ${$.slice(12)}`;if($.startsWith("perm:approve:")){let w=$.slice(13);if(this.permissionManager.resolve(w,!0))return`__perm_resolved:${w}:approved`;return`/approve ${w}`}if($.startsWith("perm:deny:")){let w=$.slice(10);if(this.permissionManager.resolve(w,!1))return`__perm_resolved:${w}:denied`;return`/reject ${w}`}if($.startsWith("perm:session:")){let w=$.slice(13);return this.permissionManager.resolve(w,!0),this.pendingSessionApprove.add(w),`__perm_resolved:${w}:session`}return $}async handleIncoming($){let w=O0(),E=w.gateway[$.platform],X=E.authorized_users.map(String),G=await IY({platform:$.platform,chatId:$.chatId,username:$.username,displayName:$.displayName,authorized:X.length>0&&X.includes($.userId),mode:E.mode,threadId:$.threadId});if(!G.authorized)return;if(!this.rateLimiter.allow(G.id)){await this.sendText($,"\u23F8 Slow down \u2014 too many messages. Try again in a minute.");return}let J=$.text.trim(),A=$.attachments?.find((W)=>W.kind==="audio");if(J){if(J=this.normalizeCallbackText(J),J.startsWith("__perm_resolved:")){let O=J.split(":")[2],Y=O==="approved"?"\u2705 Permission approved.":O==="session"?"\u2705 Permission approved for this session.":"\u274C Permission denied.";if(await this.sendText($,Y),O==="session"){let H=await jw(G.id);if(H)await a1(H.id,{auto_approve:!0})}return}}if(!J&&A&&w.speech.enabled)try{let W=await iY({audio:A.data,format:A.format});await this.handleIncoming({...$,text:W,fromVoice:!0,attachments:[]});return}catch(W){await this.sendText($,`Voice transcription failed: ${W instanceof Error?W.message:String(W)}`);return}if(!J){await this.sendText($,"Send text or a voice message.");return}await AX({chatKey:G.id,direction:"in",role:"user",text:J,platformMessageId:$.platformMessageId,threadId:$.threadId,metadata:$.fromVoice?{from_voice:!0}:void 0});let D=await hY({chatKey:G.id,rawText:J,currentMode:G.mode,currentWorkingDir:G.working_dir});if(D){if(D.mode)G.mode=D.mode;let W=D.html??D.text??"",O=D.text??W,Y=D.html?"html":void 0,H=this.adapters.get($.platform);if(H&&D.buttons?.length&&"sendWithButtons"in H)await H.sendWithButtons($.chatId,W,D.buttons,{threadId:$.threadId,parseMode:Y});else if(H)await H.send($.chatId,W,{threadId:$.threadId,parseMode:Y});if($.fromVoice&&O)await this.trySendVoiceReply($,O);await AX({chatKey:G.id,direction:"out",role:"system",text:O,threadId:$.threadId});return}if(G.mode.startsWith("job:")){let W=G.mode.slice(4),O=await sJ(W),Y=O?`Triggered ${O.name} \u2192 ${await A1({jobId:O.id,triggerBy:"bridge-msg",envOverrides:{MSG:J}})}`:`Job not found: ${W}`;if(await this.sendText($,Y),$.fromVoice)await this.trySendVoiceReply($,Y);await AX({chatKey:G.id,direction:"out",role:"system",text:Y,threadId:$.threadId});return}if(G.mode==="direct"){await this.sendText($,"Direct mode active. Use /help for commands, or /agent claude to start an agent session."),await AX({chatKey:G.id,direction:"out",role:"system",text:"Direct mode active. Use /help for commands, or /agent claude to start an agent session.",threadId:$.threadId});return}let N=await cY({chatKey:G.id,mode:G.mode,cwd:G.working_dir});if(!this.sessionLock.tryAcquire(N.id)){await this.sendText($,`\u23F3 ${N.backend} is still processing \u2014 please wait.`);return}try{await this.runAgentTurnWithPreview($,G,N,J)}finally{this.sessionLock.release(N.id)}}async runAgentTurnWithPreview($,w,E,X){if(!E.cwd||!rb(E.cwd)){await this.sendText($,"Set a working directory first: /cwd <absolute-path>");return}let G=this.adapters.get($.platform);if(!G)return;if("showTyping"in G)await G.showTyping($.chatId).catch(()=>{});let J=await G.send($.chatId,`${E.backend} is thinking\u2026`,{threadId:$.threadId}),A=null;if(J&&aJ.supports(G))A=new aJ(G),await A.init(E.id,$.chatId,J,`${E.backend} is thinking\u2026`);await a1(E.id,{status:"running",last_activity_at:new Date});try{let D=await ZY({chatKey:w.id,chatId:$.chatId,platform:$.platform,adapter:G,permissionManager:this.permissionManager,session:{id:E.id,backend:E.backend,cwd:E.cwd,model:E.model,runtime_session_id:E.runtime_session_id,auto_approve:E.auto_approve,task_id:E.task_id},threadId:$.threadId},X,J,A);if(await a1(E.id,{status:"idle",runtime_session_id:D.runtimeSessionId,last_activity_at:new Date,last_error:null}),A&&J)await A.finalize(E.id,D.output);else if(J&&"updateMessage"in G)await G.updateMessage($.chatId,J,D.output,{threadId:$.threadId}).catch(()=>G.send($.chatId,D.output,{threadId:$.threadId}));else await G.send($.chatId,D.output,{threadId:$.threadId});if(await AX({chatKey:w.id,direction:"out",role:"assistant",text:D.output,gatewaySessionId:E.id,threadId:$.threadId,platformMessageId:J}),$.fromVoice)await this.trySendVoiceReply($,D.output)}catch(D){A?.cleanup(E.id);let N=`Agent error: ${D instanceof Error?D.message:String(D)}`;await a1(E.id,{status:"error",last_error:N,last_activity_at:new Date});let W=N.slice(0,1000);if(J&&"updateMessage"in G)await G.updateMessage($.chatId,J,W,{threadId:$.threadId}).catch(()=>G.send($.chatId,W,{threadId:$.threadId}));else await G.send($.chatId,W,{threadId:$.threadId}).catch(()=>{});if(D instanceof Error&&/auth|api.key|401/i.test(D.message))await CY(E.id)}}async sendText($,w){let E=this.adapters.get($.platform);if(!E)return;await E.send($.chatId,w,{threadId:$.threadId})}async trySendVoiceReply($,w){if(!O0().tts.enabled)return;let X=this.adapters.get($.platform);if(!X||!("sendAudio"in X))return;try{let G=await dY(w);await X.sendAudio($.chatId,G.audio,G.format,"Voice reply")}catch(G){zE.warn("TTS failed",{err:G})}}async notifyTaskReview($){let w=await kY(),E=`\uD83D\uDC40 <b>Review requested</b>
|
|
409
|
+
On the other hand, if you actually know what you're doing and you do need to install further middleware while your bot is running, consider installing a composer instance on your bot, and in turn augment the composer after the fact. This way, you can circumvent this protection against memory leaks.`)}var ak=HN()});var DL=Z((AL)=>{Object.defineProperty(AL,"__esModule",{value:!0});AL.API_CONSTANTS=void 0;var JL=zN(),ek=[...JL.DEFAULT_UPDATE_TYPES,"chat_member","message_reaction","message_reaction_count"],$b={can_send_messages:!0,can_send_audios:!0,can_send_documents:!0,can_send_photos:!0,can_send_videos:!0,can_send_video_notes:!0,can_send_voice_notes:!0,can_send_polls:!0,can_send_other_messages:!0,can_add_web_page_previews:!0,can_change_info:!0,can_invite_users:!0,can_edit_tag:!0,can_pin_messages:!0,can_manage_topics:!0};AL.API_CONSTANTS={DEFAULT_UPDATE_TYPES:JL.DEFAULT_UPDATE_TYPES,ALL_UPDATE_TYPES:ek,ALL_CHAT_PERMISSIONS:$b};Object.freeze(AL.API_CONSTANTS)});var OL=Z((NL)=>{Object.defineProperty(NL,"__esModule",{value:!0});NL.InlineQueryResultBuilder=void 0;function O$($){return{...$,...BN($)}}function BN($){return{text(w,E={}){let X={message_text:w,...E};return{...$,input_message_content:X}},location(w,E,X={}){let G={latitude:w,longitude:E,...X};return{...$,input_message_content:G}},venue(w,E,X,G,J){let A={title:w,latitude:E,longitude:X,address:G,...J};return{...$,input_message_content:A}},contact(w,E,X={}){let G={first_name:w,phone_number:E,...X};return{...$,input_message_content:G}},invoice(w,E,X,G,J,A,D={}){let N={title:w,description:E,payload:X,provider_token:G,currency:J,prices:A,...D};return{...$,input_message_content:N}}}}NL.InlineQueryResultBuilder={article($,w,E={}){return BN({type:"article",id:$,title:w,...E})},audio($,w,E,X={}){return O$({type:"audio",id:$,title:w,audio_url:typeof E==="string"?E:E.href,...X})},audioCached($,w,E={}){return O$({type:"audio",id:$,audio_file_id:w,...E})},contact($,w,E,X={}){return O$({type:"contact",id:$,phone_number:w,first_name:E,...X})},documentPdf($,w,E,X={}){return O$({type:"document",mime_type:"application/pdf",id:$,title:w,document_url:typeof E==="string"?E:E.href,...X})},documentZip($,w,E,X={}){return O$({type:"document",mime_type:"application/zip",id:$,title:w,document_url:typeof E==="string"?E:E.href,...X})},documentCached($,w,E,X={}){return O$({type:"document",id:$,title:w,document_file_id:E,...X})},game($,w,E={}){return{type:"game",id:$,game_short_name:w,...E}},gif($,w,E,X={}){return O$({type:"gif",id:$,gif_url:typeof w==="string"?w:w.href,thumbnail_url:typeof E==="string"?E:E.href,...X})},gifCached($,w,E={}){return O$({type:"gif",id:$,gif_file_id:w,...E})},location($,w,E,X,G={}){return O$({type:"location",id:$,title:w,latitude:E,longitude:X,...G})},mpeg4gif($,w,E,X={}){return O$({type:"mpeg4_gif",id:$,mpeg4_url:typeof w==="string"?w:w.href,thumbnail_url:typeof E==="string"?E:E.href,...X})},mpeg4gifCached($,w,E={}){return O$({type:"mpeg4_gif",id:$,mpeg4_file_id:w,...E})},photo($,w,E={}){let X=typeof w==="string"?w:w.href;return O$({type:"photo",id:$,photo_url:X,thumbnail_url:X,...E})},photoCached($,w,E={}){return O$({type:"photo",id:$,photo_file_id:w,...E})},stickerCached($,w,E={}){return O$({type:"sticker",id:$,sticker_file_id:w,...E})},venue($,w,E,X,G,J={}){return O$({type:"venue",id:$,title:w,latitude:E,longitude:X,address:G,...J})},videoHtml($,w,E,X,G={}){return BN({type:"video",mime_type:"text/html",id:$,title:w,video_url:typeof E==="string"?E:E.href,thumbnail_url:typeof X==="string"?X:X.href,...G})},videoMp4($,w,E,X,G={}){return O$({type:"video",mime_type:"video/mp4",id:$,title:w,video_url:typeof E==="string"?E:E.href,thumbnail_url:typeof X==="string"?X:X.href,...G})},videoCached($,w,E,X={}){return O$({type:"video",id:$,title:w,video_file_id:E,...X})},voice($,w,E,X={}){return O$({type:"voice",id:$,title:w,voice_url:typeof E==="string"?E:E.href,...X})},voiceCached($,w,E,X={}){return O$({type:"voice",id:$,title:w,voice_file_id:E,...X})}}});var HL=Z((UL)=>{Object.defineProperty(UL,"__esModule",{value:!0});UL.InputMediaBuilder=void 0;UL.InputMediaBuilder={photo($,w={}){return{type:"photo",media:$,...w}},video($,w={}){return{type:"video",media:$,...w}},animation($,w={}){return{type:"animation",media:$,...w}},audio($,w={}){return{type:"audio",media:$,...w}},document($,w={}){return{type:"document",media:$,...w}}}});var RL=Z((jL)=>{Object.defineProperty(jL,"__esModule",{value:!0});jL.InlineKeyboard=jL.Keyboard=void 0;class s${constructor($=[[]]){this.keyboard=$}add(...$){var w;return(w=this.keyboard[this.keyboard.length-1])===null||w===void 0||w.push(...$),this}row(...$){return this.keyboard.push($),this}text($,w){return this.add(s$.text($,w))}static text($,w){return typeof w==="string"?{text:$,style:w}:{text:$,...w}}requestUsers($,w,E={}){return this.add(s$.requestUsers($,w,E))}static requestUsers($,w,E={}){return typeof $==="string"?{text:$,request_users:{request_id:w,...E}}:{...$,request_users:{request_id:w,...E}}}requestChat($,w,E={chat_is_channel:!1}){return this.add(s$.requestChat($,w,E))}static requestChat($,w,E={chat_is_channel:!1}){let X={request_id:w,...E};return typeof $==="string"?{text:$,request_chat:X}:{...$,request_chat:X}}requestContact($){return this.add(s$.requestContact($))}static requestContact($){return typeof $==="string"?{text:$,request_contact:!0}:{...$,request_contact:!0}}requestLocation($){return this.add(s$.requestLocation($))}static requestLocation($){return typeof $==="string"?{text:$,request_location:!0}:{...$,request_location:!0}}requestPoll($,w){return this.add(s$.requestPoll($,w))}static requestPoll($,w){let E={type:w};return typeof $==="string"?{text:$,request_poll:E}:{...$,request_poll:E}}webApp($,w){return this.add(s$.webApp($,w))}static webApp($,w){let E={url:w};return typeof $==="string"?{text:$,web_app:E}:{...$,web_app:E}}style($){let w=this.keyboard.length;if(w===0)throw Error("Need to add a button before applying a style!");let E=this.keyboard[w-1],X=E.length;if(X===0)throw Error("Need to add a button before applying a style!");let G=E[X-1];if(typeof G==="string")G={text:G},E[X-1]=G;return G.style=$,this}danger(){return this.style("danger")}success(){return this.style("success")}primary(){return this.style("primary")}icon($){let w=this.keyboard.length;if(w===0)throw Error("Need to add a button before adding an icon!");let E=this.keyboard[w-1],X=E.length;if(X===0)throw Error("Need to add a button before adding an icon!");let G=E[X-1];if(typeof G==="string")G={text:G},E[X-1]=G;return G.icon_custom_emoji_id=$,this}persistent($=!0){return this.is_persistent=$,this}selected($=!0){return this.selective=$,this}oneTime($=!0){return this.one_time_keyboard=$,this}resized($=!0){return this.resize_keyboard=$,this}placeholder($){return this.input_field_placeholder=$,this}toTransposed(){let $=this.keyboard,w=LL($);return this.clone(w)}toFlowed($,w={}){let E=this.keyboard,X=FL(E,$,w);return this.clone(X)}clone($=this.keyboard){let w=new s$($.map((E)=>E.slice()));return w.is_persistent=this.is_persistent,w.selective=this.selective,w.one_time_keyboard=this.one_time_keyboard,w.resize_keyboard=this.resize_keyboard,w.input_field_placeholder=this.input_field_placeholder,w}append(...$){for(let w of $){let E=s$.from(w);this.keyboard.push(...E.keyboard.map((X)=>X.slice()))}return this}build(){return this.keyboard}static from($){if($ instanceof s$)return $.clone();function w(E){return typeof E==="string"?s$.text(E):E}return new s$($.map((E)=>E.map(w)))}}jL.Keyboard=s$;class L${constructor($=[[]]){this.inline_keyboard=$}add(...$){var w;return(w=this.inline_keyboard[this.inline_keyboard.length-1])===null||w===void 0||w.push(...$),this}row(...$){return this.inline_keyboard.push($),this}url($,w){return this.add(L$.url($,w))}static url($,w){return typeof $==="string"?{text:$,url:w}:{...$,url:w}}text($,w=typeof $==="string"?$:$.text){return this.add(L$.text($,w))}static text($,w=typeof $==="string"?$:$.text){return typeof $==="string"?{text:$,callback_data:w}:{...$,callback_data:w}}webApp($,w){return this.add(L$.webApp($,w))}static webApp($,w){let E=typeof w==="string"?{url:w}:w;return typeof $==="string"?{text:$,web_app:E}:{...$,web_app:E}}login($,w){return this.add(L$.login($,w))}static login($,w){let E=typeof w==="string"?{url:w}:w;return typeof $==="string"?{text:$,login_url:E}:{...$,login_url:E}}switchInline($,w=""){return this.add(L$.switchInline($,w))}static switchInline($,w=""){return typeof $==="string"?{text:$,switch_inline_query:w}:{...$,switch_inline_query:w}}switchInlineCurrent($,w=""){return this.add(L$.switchInlineCurrent($,w))}static switchInlineCurrent($,w=""){return typeof $==="string"?{text:$,switch_inline_query_current_chat:w}:{...$,switch_inline_query_current_chat:w}}switchInlineChosen($,w={}){return this.add(L$.switchInlineChosen($,w))}static switchInlineChosen($,w={}){return typeof $==="string"?{text:$,switch_inline_query_chosen_chat:w}:{...$,switch_inline_query_chosen_chat:w}}copyText($,w){return this.add(L$.copyText($,w))}static copyText($,w){let E=typeof w==="string"?{text:w}:w;return typeof $==="string"?{text:$,copy_text:E}:{...$,copy_text:E}}game($){return this.add(L$.game($))}static game($){let w={};return typeof $==="string"?{text:$,callback_game:w}:{...$,callback_game:w}}pay($){return this.add(L$.pay($))}static pay($){return typeof $==="string"?{text:$,pay:!0}:{...$,pay:!0}}style($){let w=this.inline_keyboard.length;if(w===0)throw Error("Need to add a button before applying a style!");let E=this.inline_keyboard[w-1],X=E.length;if(X===0)throw Error("Need to add a button before applying a style!");return E[X-1].style=$,this}danger(){return this.style("danger")}success(){return this.style("success")}primary(){return this.style("primary")}icon($){let w=this.inline_keyboard.length;if(w===0)throw Error("Need to add a button before adding an icon!");let E=this.inline_keyboard[w-1],X=E.length;if(X===0)throw Error("Need to add a button before adding an icon!");return E[X-1].icon_custom_emoji_id=$,this}toTransposed(){let $=this.inline_keyboard,w=LL($);return new L$(w)}toFlowed($,w={}){let E=this.inline_keyboard,X=FL(E,$,w);return new L$(X)}clone(){return new L$(this.inline_keyboard.map(($)=>$.slice()))}append(...$){for(let w of $){let E=L$.from(w);this.inline_keyboard.push(...E.inline_keyboard.map((X)=>X.slice()))}return this}static from($){if($ instanceof L$)return $.clone();return new L$($.map((w)=>w.slice()))}}jL.InlineKeyboard=L$;function LL($){var w;let E=[];for(let X=0;X<$.length;X++){let G=$[X];for(let J=0;J<G.length;J++){let A=G[J];((w=E[J])!==null&&w!==void 0?w:E[J]=[]).push(A)}}return E}function FL($,w,{fillLastRow:E=!1}){var X;let G=w;if(E)G=$.map((D)=>D.length).reduce((D,N)=>D+N,0)%w;let J=[];for(let A of $)for(let D of A){let N=Math.max(0,J.length-1),W=N===0?G:w,O=(X=J[N])!==null&&X!==void 0?X:J[N]=[];if(O.length===W)O=[],J.push(O);O.push(D)}return J}});var KL=Z((QL)=>{Object.defineProperty(QL,"__esModule",{value:!0});QL.MemorySessionStorage=void 0;QL.session=Gb;QL.lazySession=Db;QL.enhanceStorage=Wb;var Eb=mw(),Xb=(0,Eb.debug)("grammy:session");function Gb($={}){return $.type==="multi"?Ab($):Jb($)}function Jb($){let{initial:w,storage:E,getSessionKey:X,custom:G}=QN($);return async(J,A)=>{let D=new MA(E,J,"session",w),N=await X(J);await D.init(N,{custom:G,lazy:!1}),await A(),await D.finish()}}function Ab($){let w=Object.keys($).filter((X)=>X!=="type"),E=Object.fromEntries(w.map((X)=>[X,QN($[X])]));return async(X,G)=>{X.session={};let J=await Promise.all(w.map(async(A)=>{let{initial:D,storage:N,getSessionKey:W,custom:O}=E[A],Y=new MA(N,X.session,A,D),H=await W(X);return await Y.init(H,{custom:O,lazy:!1}),Y}));if(await G(),X.session==null)J.forEach((A)=>A.delete());await Promise.all(J.map((A)=>A.finish()))}}function Db($={}){if($.type!==void 0&&$.type!=="single")throw Error("Cannot use lazy multi sessions!");let{initial:w,storage:E,getSessionKey:X,custom:G}=QN($);return async(J,A)=>{let D=new MA(E,J,"session",w),N=await X(J);await D.init(N,{custom:G,lazy:!0}),await A(),await D.finish()}}class MA{constructor($,w,E,X){this.storage=$,this.obj=w,this.prop=E,this.initial=X,this.fetching=!1,this.read=!1,this.wrote=!1}load(){if(this.key===void 0)return;if(this.wrote)return;if(this.promise===void 0)this.fetching=!0,this.promise=Promise.resolve(this.storage.read(this.key)).then(($)=>{var w;if(this.fetching=!1,this.wrote)return this.value;if($!==void 0)return this.value=$,$;if($=(w=this.initial)===null||w===void 0?void 0:w.call(this),$!==void 0)this.wrote=!0,this.value=$;return $});return this.promise}async init($,w){if(this.key=$,!w.lazy)await this.load();Object.defineProperty(this.obj,this.prop,{enumerable:!0,get:()=>{if($===void 0){let E=TL("access",w);throw Error(E)}if(this.read=!0,!w.lazy||this.wrote)return this.value;return this.load(),this.fetching?this.promise:this.value},set:(E)=>{if($===void 0){let X=TL("assign",w);throw Error(X)}this.wrote=!0,this.fetching=!1,this.value=E}})}delete(){Object.assign(this.obj,{[this.prop]:void 0})}async finish(){if(this.key!==void 0){if(this.read)await this.load();if(this.read||this.wrote){let $=await this.value;if($==null)await this.storage.delete(this.key);else await this.storage.write(this.key,$)}}}}function QN($={}){let{prefix:w="",getSessionKey:E=zL,initial:X,storage:G}=$;if(G==null)Xb("Storing session data in memory, all data will be lost when the bot restarts."),G=new IN;return{initial:X,storage:G,getSessionKey:async(A)=>{let D=await E(A);return D===void 0?void 0:w+D},custom:E!==zL}}function zL($){var w;return(w=$.chatId)===null||w===void 0?void 0:w.toString()}function TL($,w){let{lazy:E=!1,custom:X}=w;return`Cannot ${$} ${E?"lazy ":""}session data because ${X?"the custom `getSessionKey` function returned undefined for this update":"this update does not belong to a chat, so the session key is undefined"}!`}function Nb($){return $===void 0||typeof $==="object"&&$!==null&&"__d"in $}function Wb($){let{storage:w,millisecondsToLive:E,migrations:X}=$;if(w=Ob(w),E!==void 0)w=Ub(w,E);if(X!==void 0)w=Yb(w,X);return Hb(w)}function Ob($){return{read:async(w)=>{let E=await $.read(w);return Nb(E)?E:{__d:E}},write:(w,E)=>$.write(w,E),delete:(w)=>$.delete(w)}}function Ub($,w){let E={read:async(X)=>{let G=await $.read(X);if(G===void 0)return;if(G.e===void 0)return await E.write(X,G),G;if(G.e<Date.now()){await E.delete(X);return}return G},write:async(X,G)=>{G.e=BL(G,w).expires,await $.write(X,G)},delete:(X)=>$.delete(X)};return E}function Yb($,w){let E=Object.keys(w).map((W)=>parseInt(W)).sort((W,O)=>W-O),X=E.length;if(X===0)throw Error("No migrations given!");let G=E[0],J=X-1,A=E[J],D=new Map;E.forEach((W,O)=>D.set(W,O));function N(W){let O=J;while(W<=E[O])O--;return O}return{read:async(W)=>{var O;let Y=await $.read(W);if(Y===void 0)return Y;let{__d:H,v:L=G-1}=Y,F=1+((O=D.get(L))!==null&&O!==void 0?O:N(L));for(;F<X;F++)H=w[E[F]](H);return{...Y,v:A,__d:H}},write:(W,O)=>$.write(W,{v:A,...O}),delete:(W)=>$.delete(W)}}function Hb($){return{read:(w)=>Promise.resolve($.read(w)).then((E)=>E===null||E===void 0?void 0:E.__d),write:(w,E)=>$.write(w,{__d:E}),delete:(w)=>$.delete(w)}}class IN{constructor($){this.timeToLive=$,this.storage=new Map}read($){let w=this.storage.get($);if(w===void 0)return;if(w.expires!==void 0&&w.expires<Date.now()){this.delete($);return}return w.session}readAll(){return this.readAllValues()}readAllKeys(){return Array.from(this.storage.keys())}readAllValues(){return Array.from(this.storage.keys()).map(($)=>this.read($)).filter(($)=>$!==void 0)}readAllEntries(){return Array.from(this.storage.keys()).map(($)=>[$,this.read($)]).filter(($)=>$[1]!==void 0)}has($){return this.storage.has($)}write($,w){this.storage.set($,BL(w,this.timeToLive))}delete($){this.storage.delete($)}}QL.MemorySessionStorage=IN;function BL($,w){if(w!==void 0&&w<1/0){let E=Date.now();return{session:$,expires:E+w}}else return{session:$}}});var SL=Z((PL)=>{Object.defineProperty(PL,"__esModule",{value:!0});PL.adapters=void 0;var R$="X-Telegram-Bot-Api-Secret-Token",RA=R$.toLowerCase(),Rw="secret token is wrong",HX=()=>new Response(null,{status:200}),LX=($)=>new Response($,{status:200,headers:{"Content-Type":"application/json"}}),FX=()=>new Response('"unauthorized"',{status:401,statusText:Rw}),Mb=($,w,E)=>({get update(){var X;return JSON.parse((X=$.body)!==null&&X!==void 0?X:"{}")},header:$.headers[R$],end:()=>E(null,{statusCode:200}),respond:(X)=>E(null,{statusCode:200,headers:{"Content-Type":"application/json"},body:X}),unauthorized:()=>E(null,{statusCode:401})}),Rb=($,w)=>{let E;return{get update(){var X;return JSON.parse((X=$.body)!==null&&X!==void 0?X:"{}")},header:$.headers[R$],end:()=>E({statusCode:200}),respond:(X)=>E({statusCode:200,headers:{"Content-Type":"application/json"},body:X}),unauthorized:()=>E({statusCode:401}),handlerReturn:new Promise((X)=>E=X)}},zb=($,w)=>{var E,X;return{get update(){return w.body},header:(X=(E=$.res)===null||E===void 0?void 0:E.headers)===null||X===void 0?void 0:X[R$],end:()=>$.res={status:200,body:""},respond:(G)=>{var J,A,D,N;(A=(J=$.res)===null||J===void 0?void 0:J.set)===null||A===void 0||A.call(J,"Content-Type","application/json"),(N=(D=$.res)===null||D===void 0?void 0:D.send)===null||N===void 0||N.call(D,G)},unauthorized:()=>{var G,J;(J=(G=$.res)===null||G===void 0?void 0:G.send)===null||J===void 0||J.call(G,401,Rw)}}},Tb=($)=>{let w;return{get update(){return $.json()},header:$.headers.get(R$)||void 0,end:()=>w({status:204}),respond:(E)=>w({jsonBody:E}),unauthorized:()=>w({status:401,body:Rw}),handlerReturn:new Promise((E)=>w=E)}},Bb=($)=>{let w;return{get update(){return $.json()},header:$.headers.get(R$)||void 0,end:()=>{w(HX())},respond:(E)=>{w(LX(E))},unauthorized:()=>{w(FX())},handlerReturn:new Promise((E)=>w=E)}},Qb=($)=>{let w;return $.respondWith(new Promise((E)=>{w=E})),{get update(){return $.request.json()},header:$.request.headers.get(R$)||void 0,end:()=>{w(HX())},respond:(E)=>{w(LX(E))},unauthorized:()=>{w(FX())}}},Ib=($)=>{let w;return{get update(){return $.json()},header:$.headers.get(R$)||void 0,end:()=>{w(HX())},respond:(E)=>{w(LX(E))},unauthorized:()=>{w(FX())},handlerReturn:new Promise((E)=>w=E)}},Kb=($,w)=>({get update(){return $.body},header:$.header(R$),end:()=>w.end(),respond:(E)=>{w.set("Content-Type","application/json"),w.send(E)},unauthorized:()=>{w.status(401).send(Rw)}}),Vb=($,w)=>({get update(){return $.body},header:$.headers[RA],end:()=>w.send(""),respond:(E)=>w.headers({"Content-Type":"application/json"}).send(E),unauthorized:()=>w.code(401).send(Rw)}),Pb=($)=>{let w;return{get update(){return $.req.json()},header:$.req.header(R$),end:()=>{w($.body(""))},respond:(E)=>{w($.json(E))},unauthorized:()=>{$.status(401),w($.body(""))},handlerReturn:new Promise((E)=>w=E)}},VL=($,w)=>{let E=$.headers[RA];return{get update(){return new Promise((X,G)=>{let J=[];$.on("data",(A)=>J.push(A)).once("end",()=>{let A=Buffer.concat(J).toString("utf-8");try{X(JSON.parse(A))}catch(D){G(D)}}).once("error",G)})},header:Array.isArray(E)?E[0]:E,end:()=>w.end(),respond:(X)=>w.writeHead(200,{"Content-Type":"application/json"}).end(X),unauthorized:()=>w.writeHead(401).end(Rw)}},qb=($)=>({get update(){return $.request.body},header:$.get(R$)||void 0,end:()=>{$.body=""},respond:(w)=>{$.set("Content-Type","application/json"),$.response.body=w},unauthorized:()=>{$.status=401}}),Sb=($,w)=>({get update(){return $.body},header:$.headers[RA],end:()=>w.end(),respond:(E)=>w.status(200).json(E),unauthorized:()=>w.status(401).send(Rw)}),kb=($)=>({get update(){return $.body},header:$.headers.get(R$)||void 0,end:()=>$.response.sendStatus(200),respond:(w)=>$.response.status(200).send(w),unauthorized:()=>$.response.status(401).send(Rw)}),bb=($)=>({get update(){return $.request.body.json()},header:$.request.headers.get(R$)||void 0,end:()=>{$.response.status=200},respond:(w)=>{$.response.type="json",$.response.body=w},unauthorized:()=>{$.response.status=401}}),Zb=($)=>({get update(){return $.request.json()},header:$.request.headers.get(R$)||void 0,end:()=>$.respondWith(HX()),respond:(w)=>$.respondWith(LX(w)),unauthorized:()=>$.respondWith(FX())}),Cb=($)=>{let w;return{get update(){return $.json()},header:$.headers.get(R$)||void 0,end:()=>{if(w)w(HX())},respond:(E)=>{if(w)w(LX(E))},unauthorized:()=>{if(w)w(FX())},handlerReturn:new Promise((E)=>w=E)}},_b=({request:$})=>{let w;return{get update(){return $.json()},header:$.headers.get(R$)||void 0,end:()=>{if(w)w(HX())},respond:(E)=>{if(w)w(LX(E))},unauthorized:()=>{if(w)w(FX())},handlerReturn:new Promise((E)=>w=E)}},vb=($,w)=>{var E;return{get update(){return $.json()},header:(E=$.headers.get(R$))!==null&&E!==void 0?E:void 0,end:()=>w.end(null),respond:(X)=>w.send(200,X),unauthorized:()=>w.send(401,Rw)}},fb=($)=>{let w;return{get update(){return $.body},header:$.headers[RA],end(){w("")},respond(E){$.set.headers["content-type"]="application/json",w(E)},unauthorized(){$.set.status=401,w("")},handlerReturn:new Promise((E)=>w=E)}};PL.adapters={"aws-lambda":Mb,"aws-lambda-async":Rb,azure:zb,"azure-v4":Tb,bun:Bb,cloudflare:Qb,"cloudflare-mod":Ib,elysia:fb,express:Kb,fastify:Vb,hono:Pb,http:VL,https:VL,koa:qb,"next-js":Sb,nhttp:kb,oak:bb,serveHttp:Zb,"std/http":Cb,sveltekit:_b,worktop:vb}});var CL=Z((ZL)=>{Object.defineProperty(ZL,"__esModule",{value:!0});ZL.webhookCallback=hb;var bL=mw(),xb=SL(),kL=(0,bL.debug)("grammy:error"),yb=($,w,E,X=()=>w('"unauthorized"'))=>({update:Promise.resolve($),respond:w,header:E,unauthorized:X}),gb={...xb.adapters,callback:yb};function ub($,w){if(w===void 0)return!0;if($===void 0)return!1;let E=new TextEncoder,X=E.encode($),G=E.encode(w);if(X.length!==G.length)return!1;let J=0;for(let A=0;A<G.length;A++){let D=A<X.length?X[A]:0,N=G[A];J|=D^N}return J===0}function hb($,w=bL.defaultAdapter,E,X,G){if($.isRunning())throw Error("Bot is already running via long polling, the webhook setup won't receive any updates!");else $.start=()=>{throw Error("You already started the bot via webhooks, calling `bot.start()` starts the bot with long polling and this will prevent your webhook setup from receiving any updates!")};let{onTimeout:J="throw",timeoutMilliseconds:A=1e4,secretToken:D}=typeof E==="object"?E:{onTimeout:E,timeoutMilliseconds:X,secretToken:G},N=!1,W=typeof w==="string"?gb[w]:w;return async(...O)=>{var Y;let H=W(...O);if(!N)await $.init(),N=!0;if(!ub(H.header,D))return await H.unauthorized(),H.handlerReturn;let L=!1,F={async send(j){L=!0,await H.respond(j)}};if(await cb($.handleUpdate(await H.update,F),typeof J==="function"?()=>J(...O):J,A),!L)(Y=H.end)===null||Y===void 0||Y.call(H);return H.handlerReturn}}function cb($,w,E){if(E===1/0)return $;return new Promise((X,G)=>{let J=setTimeout(()=>{if(kL(`Request timed out after ${E} ms`),w==="throw")G(Error(`Request timed out after ${E} ms`));else{if(typeof w==="function")w();X()}let A=Date.now();$.finally(()=>{let D=Date.now()-A;kL(`Request completed ${D} ms after timeout!`)})},E);$.then(X).catch(G).finally(()=>clearTimeout(J))})}});var fL=Z((P0)=>{var mb=P0&&P0.__createBinding||(Object.create?function($,w,E,X){if(X===void 0)X=E;var G=Object.getOwnPropertyDescriptor(w,E);if(!G||("get"in G?!w.__esModule:G.writable||G.configurable))G={enumerable:!0,get:function(){return w[E]}};Object.defineProperty($,X,G)}:function($,w,E,X){if(X===void 0)X=E;$[X]=w[E]}),jX=P0&&P0.__exportStar||function($,w){for(var E in $)if(E!=="default"&&!Object.prototype.hasOwnProperty.call(w,E))mb(w,$,E)};Object.defineProperty(P0,"__esModule",{value:!0});P0.HttpError=P0.GrammyError=P0.Api=P0.matchFilter=P0.Composer=P0.Context=P0.InputFile=P0.BotError=P0.Bot=void 0;var _L=zN();Object.defineProperty(P0,"Bot",{enumerable:!0,get:function(){return _L.Bot}});Object.defineProperty(P0,"BotError",{enumerable:!0,get:function(){return _L.BotError}});var rb=ON();Object.defineProperty(P0,"InputFile",{enumerable:!0,get:function(){return rb.InputFile}});var pb=AA();Object.defineProperty(P0,"Context",{enumerable:!0,get:function(){return pb.Context}});jX(DL(),P0);jX(OL(),P0);jX(HL(),P0);jX(RL(),P0);jX(KL(),P0);jX(CL(),P0);var ob=wN();Object.defineProperty(P0,"Composer",{enumerable:!0,get:function(){return ob.Composer}});var tb=GA();Object.defineProperty(P0,"matchFilter",{enumerable:!0,get:function(){return tb.matchFilter}});var ib=LN();Object.defineProperty(P0,"Api",{enumerable:!0,get:function(){return ib.Api}});var vL=YA();Object.defineProperty(P0,"GrammyError",{enumerable:!0,get:function(){return vL.GrammyError}});Object.defineProperty(P0,"HttpError",{enumerable:!0,get:function(){return vL.HttpError}})});function VN($){let w=new MX.InlineKeyboard;for(let E of $){for(let X of E)w.text(X.label,X.value);w.row()}return w}function lb($){let w=O0(),E=w.gateway.telegram.token;if(!E)throw Error("Telegram token is not configured.");let X=new MX.Bot(E),G=new Map,J=null;function A(H){let L=w.gateway.telegram.authorized_users.map(String);return L.length>0&&L.includes(String(H))}function D(H){let L=Date.now();if(G.has(H))return!0;G.set(H,L);for(let[F,j]of G)if(L-j>db)G.delete(F);return!1}function N(H){if(!H)return!1;return H.getTime()<$}async function W(H){let L=await X.api.getFile(H),F=await fetch(`https://api.telegram.org/file/bot${E}/${L.file_path}`);return new Uint8Array(await F.arrayBuffer())}async function O(H){if(J)await J(H)}function Y(H,L,F){let j=H.from;return{platform:"telegram",chatId:String(H.chat?.id??H.callbackQuery?.message?.chat.id??""),userId:String(j.id),username:j.username,displayName:[j.first_name,j.last_name].filter(Boolean).join(" ").trim()||void 0,text:L,platformMessageId:String(H.msg?.message_id??H.message?.message_id??""),attachments:F}}return{platform:"telegram",async start(H){J=H;let L=["start","help","status","mode","cwd","agent","tasks","task","approve","reject","assign","jobs","run","mem","sessions","session"];X.command(L,async(F)=>{if(!F.from||!A(F.from.id))return;let j=String(F.message?.message_id??"");if(j&&D(`cmd:${j}`))return;if(N(F.message?.date?new Date(F.message.date*1000):void 0))return;let M=F.message?.text?.split(" ")[0]?.replace(/^\//,"").split("@")[0]??"help",z=F.message?.text?.split(" ").slice(1).join(" ")??"",B=z?`/${M} ${z}`:`/${M}`;await O(Y(F,B))}),X.on("message",async(F)=>{if(!F.from||!A(F.from.id))return;let j=String(F.message?.message_id??"");if(j&&D(`msg:${j}`))return;if(N(F.message?.date?new Date(F.message.date*1000):void 0))return;let M=[];if(F.message?.voice)try{M.push({kind:"audio",data:await W(F.message.voice.file_id),mimeType:F.message.voice.mime_type??"audio/ogg",format:"ogg",duration:F.message.voice.duration})}catch(B){KN.warn("Failed to download voice message",{err:B})}if(F.message?.audio)try{M.push({kind:"audio",data:await W(F.message.audio.file_id),mimeType:F.message.audio.mime_type??"audio/mpeg",format:(F.message.audio.mime_type??"audio/mpeg").split("/").at(1)??"mp3",duration:F.message.audio.duration})}catch(B){KN.warn("Failed to download audio message",{err:B})}let z=F.message?.text??F.message?.caption??"";if(!z&&M.length===0)return;await O(Y(F,z,M.length>0?M:void 0))}),X.on("callback_query:data",async(F)=>{if(!F.from||!A(F.from.id)||!F.callbackQuery)return;let j=F.callbackQuery.id;if(D(`cb:${j}`)){await F.answerCallbackQuery();return}let M=String(F.callbackQuery.message?.chat.id??F.chat?.id??""),z=`${M}:${F.callbackQuery.message?.message_id}`;await O({platform:"telegram",chatId:M,userId:String(F.from.id),username:F.from.username,displayName:[F.from.first_name,F.from.last_name].filter(Boolean).join(" ").trim()||void 0,text:F.callbackQuery.data??"",platformMessageId:z}),await F.answerCallbackQuery()}),KN.info("Starting Telegram gateway adapter"),X.start({allowed_updates:["message","callback_query"]})},async stop(){X.stop()},async send(H,L,F){let j={};if(F?.parseMode==="html")j.parse_mode="HTML";if(F?.buttons?.length)j.reply_markup=VN(F.buttons);let M=L.slice(0,4096),z=await X.api.sendMessage(H,M,j);return`${z.chat.id}:${z.message_id}`},async updateMessage(H,L,F,j){let[,M]=L.split(":");if(!M)return;let z={};if(j?.parseMode==="html")z.parse_mode="HTML";if(j?.buttons?.length)z.reply_markup=VN(j.buttons);try{await X.api.editMessageText(H,Number(M),F.slice(0,4096),z)}catch(B){if(!String(B instanceof Error?B.message:"").includes("message is not modified"))throw B}},async sendWithButtons(H,L,F,j){let M={reply_markup:VN(F)};if(j?.parseMode==="html")M.parse_mode="HTML";let z=await X.api.sendMessage(H,L.slice(0,4096),M);return`${z.chat.id}:${z.message_id}`},async downloadAudio(H){return W(H)},async sendAudio(H,L,F,j){let M=F==="ogg"||F==="oga"?"ogg":"mp3",z=new MX.InputFile(L,`audio.${M}`),B=j?{caption:j}:{};if(M==="ogg")await X.api.sendVoice(H,z,B);else await X.api.sendAudio(H,z,B)},async showTyping(H){try{await X.api.sendChatAction(H,"typing")}catch{}},async registerCommands(H){await X.api.setMyCommands(H.map((L)=>({command:L.command,description:L.description})))}}}var MX,KN,db=60000;var xL=R(()=>{C$();p$();oJ();MX=DJ(fL(),1),KN=Z0("gateway:telegram");pJ("telegram",($)=>lb($))});import{existsSync as sb}from"fs";class yL{adapters=new Map;sessionLock=new t8;permissionManager=new o8;startTime=Date.now();adapterStatus=new Map;pendingSessionApprove=new Set;rateLimiter=new r8;async start(){let $=O0(),w=[];if($.gateway.telegram.enabled&&$.gateway.telegram.token)w.push("telegram");if($.gateway.slack.enabled&&$.gateway.slack.bot_token&&$.gateway.slack.app_token)w.push("slack");for(let G of w)try{let J=TY(G,this.startTime);this.adapters.set(J.platform,J),await this.safeStart(J)}catch(J){let A=p8(String(J));zE.error(`Failed to create ${G} adapter`,A),this.adapterStatus.set(G,{error:A})}for(let[,G]of this.adapters)if("registerCommands"in G)try{await G.registerCommands(ab)}catch(J){zE.warn("Failed to register bot commands",{platform:G.platform,err:J})}await xY();let E=O0();for(let G of["telegram","slack"]){let J=E.gateway[G];if(J.enabled&&J.authorized_users.length===0)zE.warn(`${G}: authorized_users is empty \u2014 all users will be denied. Add user IDs to config.`)}let X=[...this.adapters.keys()].join(", ");zE.info(`Gateway started with adapters: ${X||"none"}`)}async stop(){this.permissionManager.denyAll(),await Promise.all([...this.adapters.values()].map(($)=>$.stop().catch(()=>{}))),this.adapters.clear()}resolvePermission($,w){return this.permissionManager.resolve($,w)}async safeStart($){try{await $.start(async(w)=>this.handleIncoming(w)),this.adapterStatus.set($.platform,{})}catch(w){this.adapterStatus.set($.platform,{error:String(w)}),zE.error(`Failed to start ${$.platform} adapter`,p8(String(w)))}}normalizeCallbackText($){if($.startsWith("task:approve:"))return`/approve ${$.slice(13)}`;if($.startsWith("task:reject:"))return`/reject ${$.slice(12)}`;if($.startsWith("perm:approve:")){let w=$.slice(13);if(this.permissionManager.resolve(w,!0))return`__perm_resolved:${w}:approved`;return`/approve ${w}`}if($.startsWith("perm:deny:")){let w=$.slice(10);if(this.permissionManager.resolve(w,!1))return`__perm_resolved:${w}:denied`;return`/reject ${w}`}if($.startsWith("perm:session:")){let w=$.slice(13);return this.permissionManager.resolve(w,!0),this.pendingSessionApprove.add(w),`__perm_resolved:${w}:session`}return $}async handleIncoming($){let w=O0(),E=w.gateway[$.platform],X=E.authorized_users.map(String),G=await PY({platform:$.platform,chatId:$.chatId,username:$.username,displayName:$.displayName,authorized:X.length>0&&X.includes($.userId),mode:E.mode,threadId:$.threadId});if(!G.authorized)return;if(!this.rateLimiter.allow(G.id)){await this.sendText($,"\u23F8 Slow down \u2014 too many messages. Try again in a minute.");return}let J=$.text.trim(),A=$.attachments?.find((W)=>W.kind==="audio");if(J){if(J=this.normalizeCallbackText(J),J.startsWith("__perm_resolved:")){let O=J.split(":")[2],Y=O==="approved"?"\u2705 Permission approved.":O==="session"?"\u2705 Permission approved for this session.":"\u274C Permission denied.";if(await this.sendText($,Y),O==="session"){let H=await jw(G.id);if(H)await a1(H.id,{auto_approve:!0})}return}}if(!J&&A&&w.speech.enabled)try{let W=await sY({audio:A.data,format:A.format});await this.handleIncoming({...$,text:W,fromVoice:!0,attachments:[]});return}catch(W){await this.sendText($,`Voice transcription failed: ${W instanceof Error?W.message:String(W)}`);return}if(!J){await this.sendText($,"Send text or a voice message.");return}await DX({chatKey:G.id,direction:"in",role:"user",text:J,platformMessageId:$.platformMessageId,threadId:$.threadId,metadata:$.fromVoice?{from_voice:!0}:void 0});let D=await mY({chatKey:G.id,rawText:J,currentMode:G.mode,currentWorkingDir:G.working_dir});if(D){if(D.mode)G.mode=D.mode;let W=D.html??D.text??"",O=D.text??W,Y=D.html?"html":void 0,H=this.adapters.get($.platform);if(H&&D.buttons?.length&&"sendWithButtons"in H)await H.sendWithButtons($.chatId,W,D.buttons,{threadId:$.threadId,parseMode:Y});else if(H)await H.send($.chatId,W,{threadId:$.threadId,parseMode:Y});if($.fromVoice&&O)await this.trySendVoiceReply($,O);await DX({chatKey:G.id,direction:"out",role:"system",text:O,threadId:$.threadId});return}if(G.mode.startsWith("job:")){let W=G.mode.slice(4),O=await eJ(W),Y=O?`Triggered ${O.name} \u2192 ${await A1({jobId:O.id,triggerBy:"bridge-msg",envOverrides:{MSG:J}})}`:`Job not found: ${W}`;if(await this.sendText($,Y),$.fromVoice)await this.trySendVoiceReply($,Y);await DX({chatKey:G.id,direction:"out",role:"system",text:Y,threadId:$.threadId});return}if(G.mode==="direct"){await this.sendText($,"Direct mode active. Use /help for commands, or /agent claude to start an agent session."),await DX({chatKey:G.id,direction:"out",role:"system",text:"Direct mode active. Use /help for commands, or /agent claude to start an agent session.",threadId:$.threadId});return}let N=await rY({chatKey:G.id,mode:G.mode,cwd:G.working_dir});if(!this.sessionLock.tryAcquire(N.id)){await this.sendText($,`\u23F3 ${N.backend} is still processing \u2014 please wait.`);return}try{await this.runAgentTurnWithPreview($,G,N,J)}finally{this.sessionLock.release(N.id)}}async runAgentTurnWithPreview($,w,E,X){if(!E.cwd||!sb(E.cwd)){await this.sendText($,"Set a working directory first: /cwd <absolute-path>");return}let G=this.adapters.get($.platform);if(!G)return;if("showTyping"in G)await G.showTyping($.chatId).catch(()=>{});let J=await G.send($.chatId,`${E.backend} is thinking\u2026`,{threadId:$.threadId}),A=null;if(J&&$A.supports(G))A=new $A(G),await A.init(E.id,$.chatId,J,`${E.backend} is thinking\u2026`);await a1(E.id,{status:"running",last_activity_at:new Date});try{let D=await vY({chatKey:w.id,chatId:$.chatId,platform:$.platform,adapter:G,permissionManager:this.permissionManager,session:{id:E.id,backend:E.backend,cwd:E.cwd,model:E.model,runtime_session_id:E.runtime_session_id,auto_approve:E.auto_approve,task_id:E.task_id},threadId:$.threadId},X,J,A);if(await a1(E.id,{status:"idle",runtime_session_id:D.runtimeSessionId,last_activity_at:new Date,last_error:null}),A&&J)await A.finalize(E.id,D.output);else if(J&&"updateMessage"in G)await G.updateMessage($.chatId,J,D.output,{threadId:$.threadId}).catch(()=>G.send($.chatId,D.output,{threadId:$.threadId}));else await G.send($.chatId,D.output,{threadId:$.threadId});if(await DX({chatKey:w.id,direction:"out",role:"assistant",text:D.output,gatewaySessionId:E.id,threadId:$.threadId,platformMessageId:J}),$.fromVoice)await this.trySendVoiceReply($,D.output)}catch(D){A?.cleanup(E.id);let N=`Agent error: ${D instanceof Error?D.message:String(D)}`;await a1(E.id,{status:"error",last_error:N,last_activity_at:new Date});let W=N.slice(0,1000);if(J&&"updateMessage"in G)await G.updateMessage($.chatId,J,W,{threadId:$.threadId}).catch(()=>G.send($.chatId,W,{threadId:$.threadId}));else await G.send($.chatId,W,{threadId:$.threadId}).catch(()=>{});if(D instanceof Error&&/auth|api.key|401/i.test(D.message))await fY(E.id)}}async sendText($,w){let E=this.adapters.get($.platform);if(!E)return;await E.send($.chatId,w,{threadId:$.threadId})}async trySendVoiceReply($,w){if(!O0().tts.enabled)return;let X=this.adapters.get($.platform);if(!X||!("sendAudio"in X))return;try{let G=await aY(w);await X.sendAudio($.chatId,G.audio,G.format,"Voice reply")}catch(G){zE.warn("TTS failed",{err:G})}}async notifyTaskReview($){let w=await CY(),E=`\uD83D\uDC40 <b>Review requested</b>
|
|
410
410
|
|
|
411
411
|
<b>${$.title}</b>
|
|
412
|
-
${$.summary.slice(0,400)}`,X=[[{label:"\u2705 Approve",value:`task:approve:${$.taskId}`},{label:"\uD83D\uDD01 Changes",value:`task:reject:${$.taskId}`}]];await Promise.all(w.map(async(G)=>{let J=this.adapters.get(G.platform);if(!J)return;try{if("sendWithButtons"in J)await J.sendWithButtons(G.chat_id,E,X,{parseMode:"html"});else await J.send(G.chat_id,E,{parseMode:"html"})}catch(A){zE.warn("Failed to send review notification",{err:A,chat:G.id})}}))}async sendToChat($,w,E,X){let G=this.adapters.get($);if(!G)throw Error(`Adapter not available: ${$}`);await G.send(w,E,X)}getStatus(){return{adapters:[...this.adapters.keys()].map(($)=>{let w=this.adapterStatus.get($)?.error;return w?{name:$,error:w}:{name:$}}),startTime:this.startTime}}}async function
|
|
413
|
-
`)}var zE,
|
|
412
|
+
${$.summary.slice(0,400)}`,X=[[{label:"\u2705 Approve",value:`task:approve:${$.taskId}`},{label:"\uD83D\uDD01 Changes",value:`task:reject:${$.taskId}`}]];await Promise.all(w.map(async(G)=>{let J=this.adapters.get(G.platform);if(!J)return;try{if("sendWithButtons"in J)await J.sendWithButtons(G.chat_id,E,X,{parseMode:"html"});else await J.send(G.chat_id,E,{parseMode:"html"})}catch(A){zE.warn("Failed to send review notification",{err:A,chat:G.id})}}))}async sendToChat($,w,E,X){let G=this.adapters.get($);if(!G)throw Error(`Adapter not available: ${$}`);await G.send(w,E,X)}getStatus(){return{adapters:[...this.adapters.keys()].map(($)=>{let w=this.adapterStatus.get($)?.error;return w?{name:$,error:w}:{name:$}}),startTime:this.startTime}}}async function PN(){if(ww)return;ww=new yL,await ww.start()}async function qN(){if(!ww)return;await ww.stop(),ww=null}function zA(){return ww}async function SN($,w,E,X){await ww?.sendToChat($,w,E,X)}function kN(){if(!ww)return"Gateway not running.";let{adapters:$,startTime:w}=ww.getStatus();return[`Started: ${new Date(w).toISOString()}`,`Adapters: ${$.length>0?$.map((X)=>`${X.name}${X.error?` (ERROR: ${X.error})`:" \u2713"}`).join(", "):"none"}`].join(`
|
|
413
|
+
`)}var zE,ab,ww=null;var gL=R(()=>{C$();p$();nw();oJ();yY();gY();aJ();pY();oY();eY();xL();vG();zE=Z0("gateway"),ab=[{command:"help",description:"Show available commands"},{command:"status",description:"System status and sessions"},{command:"tasks",description:"List active tasks"},{command:"task",description:"Task details: /task <id>"},{command:"approve",description:"Approve task or permission"},{command:"reject",description:"Reject task or deny permission"},{command:"assign",description:"Assign task to agent: /assign <id> <agent>"},{command:"jobs",description:"List jobs"},{command:"run",description:"Run a job: /run <name>"},{command:"mem",description:"Search memories: /mem <query>"},{command:"agent",description:"Switch agent: /agent claude|codex|cursor"},{command:"sessions",description:"List agent sessions"},{command:"session",description:"Session lifecycle: new|list|switch|stop"},{command:"mode",description:"Switch routing mode"},{command:"cwd",description:"Set working directory"}]});var bN=R(()=>{gL();vG()});var mN,BX=($,w)=>{let E=new String($);return E.isEscaped=!0,E.callbacks=w,E},$C,z3=async($,w)=>{let E="";w||=[];let X=await Promise.all($);for(let G=X.length-1;;G--){if(E+=X[G],G--,G<0)break;let J=X[G];if(typeof J==="object")w.push(...J.callbacks||[]);let A=J.isEscaped;if(J=await(typeof J==="object"?J.toString():J),typeof J==="object")w.push(...J.callbacks||[]);if(J.isEscaped??A)E+=J;else{let D=[E];qA(J,D),E=D[0]}}return BX(E,w)},qA=($,w)=>{let E=$.search($C);if(E===-1){w[0]+=$;return}let X,G,J=0;for(G=E;G<$.length;G++){switch($.charCodeAt(G)){case 34:X=""";break;case 39:X="'";break;case 38:X="&";break;case 60:X="<";break;case 62:X=">";break;default:continue}w[0]+=$.substring(J,G)+X,J=G+1}w[0]+=$.substring(J,G)},T3=($)=>{let w=$.callbacks;if(!w?.length)return $;let E=[$],X={};return w.forEach((G)=>G({phase:mN.Stringify,buffer:E,context:X})),E[0]},rN=async($,w,E,X,G)=>{if(typeof $==="object"&&!($ instanceof String)){if(!($ instanceof Promise))$=$.toString();if($ instanceof Promise)$=await $}let J=$.callbacks;if(!J?.length)return Promise.resolve($);if(G)G[0]+=$;else G=[$];let A=Promise.all(J.map((D)=>D({phase:w,buffer:G,context:X}))).then((D)=>Promise.all(D.filter(Boolean).map((N)=>rN(N,w,!1,X,G))).then(()=>G[0]));if(E)return BX(await A,J);else return A};var pN=R(()=>{mN={Stringify:1,BeforeStream:2,Stream:3},$C=/[&<>'"]/});var oN=($,...w)=>{let E=[""];for(let X=0,G=$.length-1;X<G;X++){E[0]+=$[X];let J=Array.isArray(w[X])?w[X].flat(1/0):[w[X]];for(let A=0,D=J.length;A<D;A++){let N=J[A];if(typeof N==="string")qA(N,E);else if(typeof N==="number")E[0]+=N;else if(typeof N==="boolean"||N===null||N===void 0)continue;else if(typeof N==="object"&&N.isEscaped)if(N.callbacks)E.unshift("",N);else{let W=N.toString();if(W instanceof Promise)E.unshift("",W);else E[0]+=W}else if(N instanceof Promise)E.unshift("",N);else qA(N.toString(),E)}}return E[0]+=$.at(-1),E.length===1?"callbacks"in E?BX(T3(BX(E[0],E.callbacks))):BX(E[0]):z3(E,E.callbacks)};var B3=R(()=>{pN()});var J0,Q3,wC=($)=>{return Object.entries($).map(([w,E])=>{let X=w;if(!Q3[X]||E===void 0)return"";switch(Q3[X]){case J0.STRING:return`${X}: '${E}'`;case J0.STRING_ARRAY:if(!Array.isArray(E))return"";return`${X}: [${E.map((G)=>`${G}`).join(",")}]`;case J0.JSON_STRING:return`${X}: ${JSON.stringify(E)}`;case J0.RAW:return`${X}: ${E}`;default:return""}}).filter((w)=>w!=="").join(",")},EC=({version:$})=>{let w=`https://cdn.jsdelivr.net/npm/swagger-ui-dist${$!==void 0?`@${$}`:""}`;return{css:[`${w}/swagger-ui.css`],js:[`${w}/swagger-ui-bundle.js`]}},XC=($)=>{let w=EC({version:$?.version});if(delete $.version,$.manuallySwaggerUIHtml)return $.manuallySwaggerUIHtml(w);let E=wC($);return`
|
|
414
414
|
<div>
|
|
415
415
|
<div id="swagger-ui"></div>
|
|
416
|
-
${w.css.map((X)=>
|
|
417
|
-
${w.js.map((X)=>
|
|
416
|
+
${w.css.map((X)=>oN`<link rel="stylesheet" href="${X}" />`)}
|
|
417
|
+
${w.js.map((X)=>oN`<script src="${X}" crossorigin="anonymous"><\/script>`)}
|
|
418
418
|
<script>
|
|
419
419
|
window.onload = () => {
|
|
420
420
|
window.ui = SwaggerUIBundle({
|
|
@@ -423,7 +423,7 @@ ${$.summary.slice(0,400)}`,X=[[{label:"\u2705 Approve",value:`task:approve:${$.t
|
|
|
423
423
|
}
|
|
424
424
|
</script>
|
|
425
425
|
</div>
|
|
426
|
-
`},
|
|
426
|
+
`},I3=($)=>async(w)=>{let E=$?.title??"SwaggerUI";return w.html(`
|
|
427
427
|
<!doctype html>
|
|
428
428
|
<html lang="en">
|
|
429
429
|
<head>
|
|
@@ -433,18 +433,18 @@ ${$.summary.slice(0,400)}`,X=[[{label:"\u2705 Approve",value:`task:approve:${$.t
|
|
|
433
433
|
<title>${E}</title>
|
|
434
434
|
</head>
|
|
435
435
|
<body>
|
|
436
|
-
${
|
|
436
|
+
${XC($)}
|
|
437
437
|
</body>
|
|
438
438
|
</html>
|
|
439
|
-
`)};var B3=R(()=>{R3();J0={STRING_ARRAY:"string_array",STRING:"string",JSON_STRING:"json_string",RAW:"raw"},z3={configUrl:J0.STRING,deepLinking:J0.RAW,presets:J0.STRING_ARRAY,plugins:J0.STRING_ARRAY,spec:J0.JSON_STRING,url:J0.STRING,urls:J0.JSON_STRING,layout:J0.STRING,docExpansion:J0.STRING,maxDisplayedTags:J0.RAW,operationsSorter:J0.RAW,requestInterceptor:J0.RAW,responseInterceptor:J0.RAW,persistAuthorization:J0.RAW,defaultModelsExpandDepth:J0.RAW,defaultModelExpandDepth:J0.RAW,defaultModelRendering:J0.STRING,displayRequestDuration:J0.RAW,filter:J0.RAW,showExtensions:J0.RAW,showCommonExtensions:J0.RAW,queryConfigEnabled:J0.RAW,displayOperationId:J0.RAW,tagsSorter:J0.RAW,onComplete:J0.RAW,syntaxHighlight:J0.JSON_STRING,tryItOutEnabled:J0.RAW,requestSnippetsEnabled:J0.RAW,requestSnippets:J0.JSON_STRING,oauth2RedirectUrl:J0.STRING,showMutabledRequest:J0.RAW,request:J0.JSON_STRING,supportedSubmitMethods:J0.JSON_STRING,validatorUrl:J0.STRING,withCredentials:J0.RAW,modelPropertyMacro:J0.RAW,parameterMacro:J0.RAW}});function tG($,w){var E={};for(var X in $)if(Object.prototype.hasOwnProperty.call($,X)&&w.indexOf(X)<0)E[X]=$[X];if($!=null&&typeof Object.getOwnPropertySymbols==="function"){for(var G=0,X=Object.getOwnPropertySymbols($);G<X.length;G++)if(w.indexOf(X[G])<0&&Object.prototype.propertyIsEnumerable.call($,X[G]))E[X[G]]=$[X[G]]}return E}function N0($,w){var E;return((E=$===null||$===void 0?void 0:$._def)===null||E===void 0?void 0:E.typeName)===w}function sZ($){return"_def"in $}function pG($,w){let E=$.ZodType.prototype[w];$.ZodType.prototype[w]=function(...X){let G=E.apply(this,X);return G._def.openapi=this._def.openapi,G}}function I3($){if(typeof $.ZodType.prototype.openapi<"u")return;$.ZodType.prototype.openapi=function(G,J){var A,D,N,W,O,Y;let H=typeof G==="string"?J:G,L=H!==null&&H!==void 0?H:{},{param:F}=L,j=tG(L,["param"]),M=Object.assign(Object.assign({},(A=this._def.openapi)===null||A===void 0?void 0:A._internal),typeof G==="string"?{refId:G}:void 0),z=Object.assign(Object.assign(Object.assign({},(D=this._def.openapi)===null||D===void 0?void 0:D.metadata),j),((W=(N=this._def.openapi)===null||N===void 0?void 0:N.metadata)===null||W===void 0?void 0:W.param)||F?{param:Object.assign(Object.assign({},(Y=(O=this._def.openapi)===null||O===void 0?void 0:O.metadata)===null||Y===void 0?void 0:Y.param),F)}:void 0),B=new this.constructor(Object.assign(Object.assign({},this._def),{openapi:Object.assign(Object.assign({},Object.keys(M).length>0?{_internal:M}:void 0),Object.keys(z).length>0?{metadata:z}:void 0)}));if(N0(this,"ZodObject")){let Q=this.extend;B.extend=function(...k){var v,C,n,T0,f0,c0,d0;let K0=Q.apply(this,k);return K0._def.openapi={_internal:{extendedFrom:((C=(v=this._def.openapi)===null||v===void 0?void 0:v._internal)===null||C===void 0?void 0:C.refId)?{refId:(T0=(n=this._def.openapi)===null||n===void 0?void 0:n._internal)===null||T0===void 0?void 0:T0.refId,schema:this}:(c0=(f0=this._def.openapi)===null||f0===void 0?void 0:f0._internal)===null||c0===void 0?void 0:c0.extendedFrom},metadata:(d0=K0._def.openapi)===null||d0===void 0?void 0:d0.metadata},K0}}return B},pG($,"optional"),pG($,"nullable"),pG($,"default"),pG($,"transform"),pG($,"refine");let w=$.ZodObject.prototype.deepPartial;$.ZodObject.prototype.deepPartial=function(){let G=this._def.shape(),J=w.apply(this),A=J._def.shape();return Object.entries(A).forEach(([D,N])=>{var W,O;N._def.openapi=(O=(W=G[D])===null||W===void 0?void 0:W._def)===null||O===void 0?void 0:O.openapi}),J._def.openapi=void 0,J};let E=$.ZodObject.prototype.pick;$.ZodObject.prototype.pick=function(...G){let J=E.apply(this,G);return J._def.openapi=void 0,J};let X=$.ZodObject.prototype.omit;$.ZodObject.prototype.omit=function(...G){let J=X.apply(this,G);return J._def.openapi=void 0,J}}function PA($,w){if($===null||$===void 0||w===null||w===void 0)return $===w;if($===w||$.valueOf()===w.valueOf())return!0;if(Array.isArray($)){if(!Array.isArray(w))return!1;if($.length!==w.length)return!1}if(!($ instanceof Object)||!(w instanceof Object))return!1;let E=Object.keys($);return Object.keys(w).every((X)=>E.indexOf(X)!==-1)&&E.every((X)=>PA($[X],w[X]))}class K3{constructor(){this.buckets=new Map}put($){let w=this.hashCodeOf($),E=this.buckets.get(w);if(!E){this.buckets.set(w,[$]);return}if(!E.some((G)=>PA(G,$)))E.push($)}contains($){let w=this.hashCodeOf($),E=this.buckets.get(w);if(!E)return!1;return E.some((X)=>PA(X,$))}values(){return[...this.buckets.values()].flat()}stats(){let $=0,w=0,E=0;for(let G of this.buckets.values())if($+=1,w+=G.length,G.length>1)E+=1;let X=$/w;return{totalBuckets:$,collisions:E,totalValues:w,hashEffectiveness:X}}hashCodeOf($){let w=0;if(Array.isArray($)){for(let E=0;E<$.length;E++)w^=this.hashCodeOf($[E])*E;return w}if(typeof $==="string"){for(let E=0;E<$.length;E++)w^=$.charCodeAt(E)*E;return w}if(typeof $==="number")return $;if(typeof $==="object")for(let[E,X]of Object.entries($))w^=this.hashCodeOf(E)+this.hashCodeOf(X!==null&&X!==void 0?X:"");return w}}function iG($){return $===void 0}function dG($,w){let E={};return Object.entries($).forEach(([X,G])=>{E[X]=w(G)}),E}function aZ($,w){let E={};return Object.entries($).forEach(([X,G])=>{if(!w.some((J)=>J===X))E[X]=G}),E}function QX($,w){let E={};return Object.entries($).forEach(([X,G])=>{if(!w(G,X))E[X]=G}),E}function Q3($){return $.filter((w)=>!iG(w))}function eZ($){let w=new K3;return $.forEach((E)=>w.put(E)),[...w.values()]}function V3($){return typeof $==="string"}class pN{constructor($){this.parents=$,this._definitions=[]}get definitions(){var $,w;return[...(w=($=this.parents)===null||$===void 0?void 0:$.flatMap((X)=>X.definitions))!==null&&w!==void 0?w:[],...this._definitions]}register($,w){let E=this.schemaWithRefId($,w);return this._definitions.push({type:"schema",schema:E}),E}registerParameter($,w){var E,X,G;let J=this.schemaWithRefId($,w),A=(E=J._def.openapi)===null||E===void 0?void 0:E.metadata,D=J.openapi(Object.assign(Object.assign({},A),{param:Object.assign(Object.assign({},A===null||A===void 0?void 0:A.param),{name:(G=(X=A===null||A===void 0?void 0:A.param)===null||X===void 0?void 0:X.name)!==null&&G!==void 0?G:$})}));return this._definitions.push({type:"parameter",schema:D}),D}registerPath($){this._definitions.push({type:"route",route:$})}registerWebhook($){this._definitions.push({type:"webhook",webhook:$})}registerComponent($,w,E){return this._definitions.push({type:"component",componentType:$,name:w,component:E}),{name:w,ref:{$ref:`#/components/${$}/${w}`}}}schemaWithRefId($,w){return w.openapi($)}}class sG{constructor($){this.message=$}}function oG($,w){try{return $()}catch(E){if(E instanceof lG)throw new lG(Object.assign(Object.assign({},E.data),w));throw E}}class g0{static getMetadata($){var w;let E=this.unwrapChained($),X=$._def.openapi?$._def.openapi:E._def.openapi,G=(w=$.description)!==null&&w!==void 0?w:E.description;return{_internal:X===null||X===void 0?void 0:X._internal,metadata:Object.assign({description:G},X===null||X===void 0?void 0:X.metadata)}}static getInternalMetadata($){let w=this.unwrapChained($),E=$._def.openapi?$._def.openapi:w._def.openapi;return E===null||E===void 0?void 0:E._internal}static getParamMetadata($){var w,E;let X=this.unwrapChained($),G=$._def.openapi?$._def.openapi:X._def.openapi,J=(w=$.description)!==null&&w!==void 0?w:X.description;return{_internal:G===null||G===void 0?void 0:G._internal,metadata:Object.assign(Object.assign({},G===null||G===void 0?void 0:G.metadata),{param:Object.assign({description:J},(E=G===null||G===void 0?void 0:G.metadata)===null||E===void 0?void 0:E.param)})}}static buildSchemaMetadata($){return QX(aZ($,["param"]),iG)}static buildParameterMetadata($){return QX($,iG)}static applySchemaMetadata($,w){return QX(Object.assign(Object.assign({},$),this.buildSchemaMetadata(w)),iG)}static getRefId($){var w;return(w=this.getInternalMetadata($))===null||w===void 0?void 0:w.refId}static unwrapChained($){return this.unwrapUntil($)}static getDefaultValue($){let w=this.unwrapUntil($,"ZodDefault");return w===null||w===void 0?void 0:w._def.defaultValue()}static unwrapUntil($,w){if(w&&N0($,w))return $;if(N0($,"ZodOptional")||N0($,"ZodNullable")||N0($,"ZodBranded"))return this.unwrapUntil($.unwrap(),w);if(N0($,"ZodDefault")||N0($,"ZodReadonly"))return this.unwrapUntil($._def.innerType,w);if(N0($,"ZodEffects"))return this.unwrapUntil($._def.schema,w);if(N0($,"ZodPipeline"))return this.unwrapUntil($._def.in,w);return w?void 0:$}static isOptionalSchema($){return $.isOptional()}}class q3{transform($,w,E){var X,G;let J=$._def.type;return Object.assign(Object.assign({},w("array")),{items:E(J),minItems:(X=$._def.minLength)===null||X===void 0?void 0:X.value,maxItems:(G=$._def.maxLength)===null||G===void 0?void 0:G.value})}}class S3{transform($){return Object.assign(Object.assign({},$("string")),{pattern:"^d+$"})}}class k3{transform($,w,E,X,G){let J=[...$.options.values()],A=J.map(X);if(w)return{oneOf:E(A,w)};return{oneOf:A,discriminator:this.mapDiscriminator(J,$.discriminator,G)}}mapDiscriminator($,w,E){if($.some((G)=>g0.getRefId(G)===void 0))return;let X={};return $.forEach((G)=>{var J;let A=g0.getRefId(G),D=(J=G.shape)===null||J===void 0?void 0:J[w];if(N0(D,"ZodEnum")||N0(D,"ZodNativeEnum")){Object.values(D.enum).filter(V3).forEach((O)=>{X[O]=E(A)});return}let N=D===null||D===void 0?void 0:D._def.value;if(typeof N!=="string")throw Error(`Discriminator ${w} could not be found in one of the values of a discriminated union`);X[N]=E(A)}),{propertyName:w,mapping:X}}}class b3{transform($,w){return Object.assign(Object.assign({},w("string")),{enum:$._def.values})}}class Z3{transform($,w,E,X){let J={allOf:this.flattenIntersectionTypes($).map(X)};if(w)return{anyOf:E([J],w)};return J}flattenIntersectionTypes($){if(!N0($,"ZodIntersection"))return[$];let w=this.flattenIntersectionTypes($._def.left),E=this.flattenIntersectionTypes($._def.right);return[...w,...E]}}class C3{transform($,w){return Object.assign(Object.assign({},w(typeof $._def.value)),{enum:[$._def.value]})}}function $C($){let E=Object.keys($).filter((J)=>typeof $[$[J]]!=="number").map((J)=>$[J]),X=E.filter((J)=>typeof J==="number").length,G=X===0?"string":X===E.length?"numeric":"mixed";return{values:E,type:G}}class _3{transform($,w){let{type:E,values:X}=$C($._def.values);if(E==="mixed")throw new sG("Enum has mixed string and number values, please specify the OpenAPI type manually");return Object.assign(Object.assign({},w(E==="numeric"?"integer":"string")),{enum:X})}}class v3{transform($,w,E){return Object.assign(Object.assign({},w($.isInt?"integer":"number")),E($._def.checks))}}class f3{transform($,w,E,X){var G;let J=(G=g0.getInternalMetadata($))===null||G===void 0?void 0:G.extendedFrom,A=this.requiredKeysOf($),D=dG($._def.shape(),X);if(!J)return Object.assign(Object.assign(Object.assign(Object.assign({},E("object")),{properties:D,default:w}),A.length>0?{required:A}:{}),this.generateAdditionalProperties($,X));let N=J.schema;X(N);let W=this.requiredKeysOf(N),O=dG(N===null||N===void 0?void 0:N._def.shape(),X),Y=Object.fromEntries(Object.entries(D).filter(([F,j])=>{return!rN(O[F],j)})),H=A.filter((F)=>!W.includes(F)),L=Object.assign(Object.assign(Object.assign(Object.assign({},E("object")),{default:w,properties:Y}),H.length>0?{required:H}:{}),this.generateAdditionalProperties($,X));return{allOf:[{$ref:`#/components/schemas/${J.refId}`},L]}}generateAdditionalProperties($,w){let E=$._def.unknownKeys,X=$._def.catchall;if(N0(X,"ZodNever")){if(E==="strict")return{additionalProperties:!1};return{}}return{additionalProperties:w(X)}}requiredKeysOf($){return Object.entries($._def.shape()).filter(([w,E])=>!g0.isOptionalSchema(E)).map(([w,E])=>w)}}class x3{transform($,w,E){let X=$._def.valueType,G=$._def.keyType,J=E(X);if(N0(G,"ZodEnum")||N0(G,"ZodNativeEnum")){let D=Object.values(G.enum).filter(V3).reduce((N,W)=>Object.assign(Object.assign({},N),{[W]:J}),{});return Object.assign(Object.assign({},w("object")),{properties:D})}return Object.assign(Object.assign({},w("object")),{additionalProperties:J})}}class y3{transform($,w){var E,X,G;let J=this.getZodStringCheck($,"regex"),A=(E=this.getZodStringCheck($,"length"))===null||E===void 0?void 0:E.value,D=Number.isFinite($.minLength)?(X=$.minLength)!==null&&X!==void 0?X:void 0:void 0,N=Number.isFinite($.maxLength)?(G=$.maxLength)!==null&&G!==void 0?G:void 0:void 0;return Object.assign(Object.assign({},w("string")),{minLength:A!==null&&A!==void 0?A:D,maxLength:A!==null&&A!==void 0?A:N,format:this.mapStringFormat($),pattern:J===null||J===void 0?void 0:J.regex.source})}mapStringFormat($){if($.isUUID)return"uuid";if($.isEmail)return"email";if($.isURL)return"uri";if($.isDate)return"date";if($.isDatetime)return"date-time";if($.isCUID)return"cuid";if($.isCUID2)return"cuid2";if($.isULID)return"ulid";if($.isIP)return"ip";if($.isEmoji)return"emoji";return}getZodStringCheck($,w){return $._def.checks.find((E)=>{return E.kind===w})}}class g3{constructor($){this.versionSpecifics=$}transform($,w,E){let{items:X}=$._def,G=X.map(E);return Object.assign(Object.assign({},w("array")),this.versionSpecifics.mapTupleItems(G))}}class u3{transform($,w,E){let G=this.flattenUnionTypes($).map((J)=>{let A=this.unwrapNullable(J);return E(A)});return{anyOf:w(G)}}flattenUnionTypes($){if(!N0($,"ZodUnion"))return[$];return $._def.options.flatMap((E)=>this.flattenUnionTypes(E))}unwrapNullable($){if(N0($,"ZodNullable"))return this.unwrapNullable($.unwrap());return $}}class h3{constructor($){this.versionSpecifics=$,this.objectTransformer=new f3,this.stringTransformer=new y3,this.numberTransformer=new v3,this.bigIntTransformer=new S3,this.literalTransformer=new C3,this.enumTransformer=new b3,this.nativeEnumTransformer=new _3,this.arrayTransformer=new q3,this.unionTransformer=new u3,this.discriminatedUnionTransformer=new k3,this.intersectionTransformer=new Z3,this.recordTransformer=new x3,this.tupleTransformer=new g3($)}transform($,w,E,X,G){if(N0($,"ZodNull"))return this.versionSpecifics.nullType;if(N0($,"ZodUnknown")||N0($,"ZodAny"))return this.versionSpecifics.mapNullableType(void 0,w);if(N0($,"ZodObject"))return this.objectTransformer.transform($,G,(A)=>this.versionSpecifics.mapNullableType(A,w),E);let J=this.transformSchemaWithoutDefault($,w,E,X);return Object.assign(Object.assign({},J),{default:G})}transformSchemaWithoutDefault($,w,E,X){if(N0($,"ZodUnknown")||N0($,"ZodAny"))return this.versionSpecifics.mapNullableType(void 0,w);if(N0($,"ZodString"))return this.stringTransformer.transform($,(J)=>this.versionSpecifics.mapNullableType(J,w));if(N0($,"ZodNumber"))return this.numberTransformer.transform($,(J)=>this.versionSpecifics.mapNullableType(J,w),(J)=>this.versionSpecifics.getNumberChecks(J));if(N0($,"ZodBigInt"))return this.bigIntTransformer.transform((J)=>this.versionSpecifics.mapNullableType(J,w));if(N0($,"ZodBoolean"))return this.versionSpecifics.mapNullableType("boolean",w);if(N0($,"ZodLiteral"))return this.literalTransformer.transform($,(J)=>this.versionSpecifics.mapNullableType(J,w));if(N0($,"ZodEnum"))return this.enumTransformer.transform($,(J)=>this.versionSpecifics.mapNullableType(J,w));if(N0($,"ZodNativeEnum"))return this.nativeEnumTransformer.transform($,(J)=>this.versionSpecifics.mapNullableType(J,w));if(N0($,"ZodArray"))return this.arrayTransformer.transform($,(J)=>this.versionSpecifics.mapNullableType(J,w),E);if(N0($,"ZodTuple"))return this.tupleTransformer.transform($,(J)=>this.versionSpecifics.mapNullableType(J,w),E);if(N0($,"ZodUnion"))return this.unionTransformer.transform($,(J)=>this.versionSpecifics.mapNullableOfArray(J,w),E);if(N0($,"ZodDiscriminatedUnion"))return this.discriminatedUnionTransformer.transform($,w,(J)=>this.versionSpecifics.mapNullableOfArray(J,w),E,X);if(N0($,"ZodIntersection"))return this.intersectionTransformer.transform($,w,(J)=>this.versionSpecifics.mapNullableOfArray(J,w),E);if(N0($,"ZodRecord"))return this.recordTransformer.transform($,(J)=>this.versionSpecifics.mapNullableType(J,w),E);if(N0($,"ZodDate"))return this.versionSpecifics.mapNullableType("string",w);let G=g0.getRefId($);throw new P3({currentSchema:$._def,schemaName:G})}}class oN{constructor($,w){this.definitions=$,this.versionSpecifics=w,this.schemaRefs={},this.paramRefs={},this.pathRefs={},this.rawComponents=[],this.openApiTransformer=new h3(w),this.sortDefinitions()}generateDocumentData(){return this.definitions.forEach(($)=>this.generateSingle($)),{components:this.buildComponents(),paths:this.pathRefs}}generateComponents(){return this.definitions.forEach(($)=>this.generateSingle($)),{components:this.buildComponents()}}buildComponents(){var $,w;let E={};return this.rawComponents.forEach(({componentType:X,name:G,component:J})=>{var A;(A=E[X])!==null&&A!==void 0||(E[X]={}),E[X][G]=J}),Object.assign(Object.assign({},E),{schemas:Object.assign(Object.assign({},($=E.schemas)!==null&&$!==void 0?$:{}),this.schemaRefs),parameters:Object.assign(Object.assign({},(w=E.parameters)!==null&&w!==void 0?w:{}),this.paramRefs)})}sortDefinitions(){let $=["schema","parameter","component","route"];this.definitions.sort((w,E)=>{if(!("type"in w)){if(!("type"in E))return 0;return-1}if(!("type"in E))return 1;let X=$.findIndex((J)=>J===w.type),G=$.findIndex((J)=>J===E.type);return X-G})}generateSingle($){if(!("type"in $)){this.generateSchemaWithRef($);return}switch($.type){case"parameter":this.generateParameterDefinition($.schema);return;case"schema":this.generateSchemaWithRef($.schema);return;case"route":this.generateSingleRoute($.route);return;case"component":this.rawComponents.push($);return}}generateParameterDefinition($){let w=g0.getRefId($),E=this.generateParameter($);if(w)this.paramRefs[w]=E;return E}getParameterRef($,w){var E,X,G,J,A;let D=(E=$===null||$===void 0?void 0:$.metadata)===null||E===void 0?void 0:E.param,N=((X=$===null||$===void 0?void 0:$._internal)===null||X===void 0?void 0:X.refId)?this.paramRefs[(G=$._internal)===null||G===void 0?void 0:G.refId]:void 0;if(!((J=$===null||$===void 0?void 0:$._internal)===null||J===void 0?void 0:J.refId)||!N)return;if(D&&N.in!==D.in||(w===null||w===void 0?void 0:w.in)&&N.in!==w.in)throw new BX(`Conflicting location for parameter ${N.name}`,{key:"in",values:Q3([N.in,w===null||w===void 0?void 0:w.in,D===null||D===void 0?void 0:D.in])});if(D&&N.name!==D.name||(w===null||w===void 0?void 0:w.name)&&N.name!==(w===null||w===void 0?void 0:w.name))throw new BX("Conflicting names for parameter",{key:"name",values:Q3([N.name,w===null||w===void 0?void 0:w.name,D===null||D===void 0?void 0:D.name])});return{$ref:`#/components/parameters/${(A=$._internal)===null||A===void 0?void 0:A.refId}`}}generateInlineParameters($,w){var E;let X=g0.getMetadata($),G=(E=X===null||X===void 0?void 0:X.metadata)===null||E===void 0?void 0:E.param,J=this.getParameterRef(X,{in:w});if(J)return[J];if(N0($,"ZodObject")){let A=$._def.shape();return Object.entries(A).map(([N,W])=>{var O,Y;let H=g0.getMetadata(W),L=this.getParameterRef(H,{in:w,name:N});if(L)return L;let F=(O=H===null||H===void 0?void 0:H.metadata)===null||O===void 0?void 0:O.param;if((F===null||F===void 0?void 0:F.name)&&F.name!==N)throw new BX("Conflicting names for parameter",{key:"name",values:[N,F.name]});if((F===null||F===void 0?void 0:F.in)&&F.in!==w)throw new BX(`Conflicting location for parameter ${(Y=F.name)!==null&&Y!==void 0?Y:N}`,{key:"in",values:[w,F.in]});return this.generateParameter(W.openapi({param:{name:N,in:w}}))})}if((G===null||G===void 0?void 0:G.in)&&G.in!==w)throw new BX(`Conflicting location for parameter ${G.name}`,{key:"in",values:[w,G.in]});return[this.generateParameter($.openapi({param:{in:w}}))]}generateSimpleParameter($){var w;let E=g0.getParamMetadata($),X=(w=E===null||E===void 0?void 0:E.metadata)===null||w===void 0?void 0:w.param,G=!g0.isOptionalSchema($)&&!$.isNullable(),J=this.generateSchemaWithRef($);return Object.assign({schema:J,required:G},X?g0.buildParameterMetadata(X):{})}generateParameter($){var w;let E=g0.getMetadata($),X=(w=E===null||E===void 0?void 0:E.metadata)===null||w===void 0?void 0:w.param,G=X===null||X===void 0?void 0:X.name,J=X===null||X===void 0?void 0:X.in;if(!G)throw new lG({missingField:"name"});if(!J)throw new lG({missingField:"in",paramName:G});let A=this.generateSimpleParameter($);return Object.assign(Object.assign({},A),{in:J,name:G})}generateSchemaWithMetadata($){var w;let E=g0.unwrapChained($),X=g0.getMetadata($),G=g0.getDefaultValue($),J=((w=X===null||X===void 0?void 0:X.metadata)===null||w===void 0?void 0:w.type)?{type:X===null||X===void 0?void 0:X.metadata.type}:this.toOpenAPISchema(E,$.isNullable(),G);return(X===null||X===void 0?void 0:X.metadata)?g0.applySchemaMetadata(J,X.metadata):QX(J,iG)}constructReferencedOpenAPISchema($){var w;let E=g0.getMetadata($),X=g0.unwrapChained($),G=g0.getDefaultValue($),J=$.isNullable();if((w=E===null||E===void 0?void 0:E.metadata)===null||w===void 0?void 0:w.type)return this.versionSpecifics.mapNullableType(E.metadata.type,J);return this.toOpenAPISchema(X,J,G)}generateSimpleSchema($){var w;let E=g0.getMetadata($),X=g0.getRefId($);if(!X||!this.schemaRefs[X])return this.generateSchemaWithMetadata($);let G=this.schemaRefs[X],J={$ref:this.generateSchemaRef(X)},A=QX(g0.buildSchemaMetadata((w=E===null||E===void 0?void 0:E.metadata)!==null&&w!==void 0?w:{}),(W,O)=>W===void 0||rN(W,G[O]));if(A.type)return{allOf:[J,A]};let D=QX(this.constructReferencedOpenAPISchema($),(W,O)=>W===void 0||rN(W,G[O])),N=g0.applySchemaMetadata(D,A);if(Object.keys(N).length>0)return{allOf:[J,N]};return J}generateSchemaWithRef($){let w=g0.getRefId($),E=this.generateSimpleSchema($);if(w&&this.schemaRefs[w]===void 0)return this.schemaRefs[w]=E,{$ref:this.generateSchemaRef(w)};return E}generateSchemaRef($){return`#/components/schemas/${$}`}getRequestBody($){if(!$)return;let{content:w}=$,E=tG($,["content"]),X=this.getBodyContent(w);return Object.assign(Object.assign({},E),{content:X})}getParameters($){if(!$)return[];let{headers:w}=$,E=this.cleanParameter($.query),X=this.cleanParameter($.params),G=this.cleanParameter($.cookies),J=oG(()=>E?this.generateInlineParameters(E,"query"):[],{location:"query"}),A=oG(()=>X?this.generateInlineParameters(X,"path"):[],{location:"path"}),D=oG(()=>G?this.generateInlineParameters(G,"cookie"):[],{location:"cookie"}),N=oG(()=>{if(Array.isArray(w))return w.flatMap((O)=>this.generateInlineParameters(O,"header"));let W=this.cleanParameter(w);return W?this.generateInlineParameters(W,"header"):[]},{location:"header"});return[...A,...J,...N,...D]}cleanParameter($){if(!$)return;return N0($,"ZodEffects")?this.cleanParameter($._def.schema):$}generatePath($){let{method:w,path:E,request:X,responses:G}=$,J=tG($,["method","path","request","responses"]),A=dG(G,(O)=>{return this.getResponse(O)}),D=oG(()=>this.getParameters(X),{route:`${w} ${E}`}),N=this.getRequestBody(X===null||X===void 0?void 0:X.body);return{[w]:Object.assign(Object.assign(Object.assign(Object.assign({},J),D.length>0?{parameters:[...J.parameters||[],...D]}:{}),N?{requestBody:N}:{}),{responses:A})}}generateSingleRoute($){let w=this.generatePath($);return this.pathRefs[$.path]=Object.assign(Object.assign({},this.pathRefs[$.path]),w),w}getResponse($){if(this.isReferenceObject($))return $;let{content:w,headers:E}=$,X=tG($,["content","headers"]),G=w?{content:this.getBodyContent(w)}:{};if(!E)return Object.assign(Object.assign({},X),G);let J=N0(E,"ZodObject")?this.getResponseHeaders(E):E;return Object.assign(Object.assign(Object.assign({},X),{headers:J}),G)}isReferenceObject($){return"$ref"in $}getResponseHeaders($){let w=$._def.shape();return dG(w,(X)=>this.generateSimpleParameter(X))}getBodyContent($){return dG($,(w)=>{if(!w||!sZ(w.schema))return w;let{schema:E}=w,X=tG(w,["schema"]),G=this.generateSchemaWithRef(E);return Object.assign({schema:G},X)})}toOpenAPISchema($,w,E){return this.openApiTransformer.transform($,w,(X)=>this.generateSchemaWithRef(X),(X)=>this.generateSchemaRef(X),E)}}class c3{get nullType(){return{nullable:!0}}mapNullableOfArray($,w){if(w)return[...$,this.nullType];return $}mapNullableType($,w){return Object.assign(Object.assign({},$?{type:$}:void 0),w?this.nullType:void 0)}mapTupleItems($){let w=eZ($);return{items:w.length===1?w[0]:{anyOf:w},minItems:$.length,maxItems:$.length}}getNumberChecks($){return Object.assign({},...$.map((w)=>{switch(w.kind){case"min":return w.inclusive?{minimum:Number(w.value)}:{minimum:Number(w.value),exclusiveMinimum:!0};case"max":return w.inclusive?{maximum:Number(w.value)}:{maximum:Number(w.value),exclusiveMaximum:!0};default:return{}}}))}}class tN{constructor($){let w=new c3;this.generator=new oN($,w)}generateDocument($){let w=this.generator.generateDocumentData();return Object.assign(Object.assign({},$),w)}generateComponents(){return this.generator.generateComponents()}}class n3{get nullType(){return{type:"null"}}mapNullableOfArray($,w){if(w)return[...$,this.nullType];return $}mapNullableType($,w){if(!$)return{};if(w)return{type:Array.isArray($)?[...$,"null"]:[$,"null"]};return{type:$}}mapTupleItems($){return{prefixItems:$}}getNumberChecks($){return Object.assign({},...$.map((w)=>{switch(w.kind){case"min":return w.inclusive?{minimum:Number(w.value)}:{exclusiveMinimum:Number(w.value)};case"max":return w.inclusive?{maximum:Number(w.value)}:{exclusiveMaximum:Number(w.value)};default:return{}}}))}}function wC($){return"type"in $&&$.type==="webhook"}class iN{constructor($){this.definitions=$,this.webhookRefs={};let w=new n3;this.generator=new oN(this.definitions,w)}generateDocument($){let w=this.generator.generateDocumentData();return this.definitions.filter(wC).forEach((E)=>this.generateSingleWebhook(E.webhook)),Object.assign(Object.assign(Object.assign({},$),w),{webhooks:this.webhookRefs})}generateComponents(){return this.generator.generateComponents()}generateSingleWebhook($){let w=this.generator.generatePath($);return this.webhookRefs[$.path]=Object.assign(Object.assign({},this.webhookRefs[$.path]),w),w}}var rN,BX,lG,P3;var m3=R(()=>{rN=PA;BX=class BX extends sG{constructor($,w){super($);this.data=w}};lG=class lG extends sG{constructor($){super(`Missing parameter data, please specify \`${$.missingField}\` and other OpenAPI parameter props using the \`param\` field of \`ZodSchema.openapi\``);this.data=$}};P3=class P3 extends sG{constructor($){super("Unknown zod object type, please specify `type` and other OpenAPI props using `ZodSchema.openapi`.");this.data=$}}});var lN=($)=>{let w=$.split("/");if(w[0]==="")w.shift();return w},r3=($)=>{let{groups:w,path:E}=EC($),X=lN(E);return XC(X,w)},EC=($)=>{let w=[];return $=$.replace(/\{[^}]+\}/g,(E,X)=>{let G=`@${X}`;return w.push([G,E]),G}),{groups:w,path:$}},XC=($,w)=>{for(let E=w.length-1;E>=0;E--){let[X]=w[E];for(let G=$.length-1;G>=0;G--)if($[G].includes(X)){$[G]=$[G].replace(X,w[E][1]);break}}return $},qA,p3=($,w)=>{if($==="*")return"*";let E=$.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(E){let X=`${$}#${w}`;if(!qA[X])if(E[2])qA[X]=w&&w[0]!==":"&&w[0]!=="*"?[X,E[1],new RegExp(`^${E[2]}(?=/${w})`)]:[$,E[1],new RegExp(`^${E[2]}$`)];else qA[X]=[$,E[1],!0];return qA[X]}return null},IX=($,w)=>{try{return w($)}catch{return $.replace(/(?:%[0-9A-Fa-f]{2})+/g,(E)=>{try{return w(E)}catch{return E}})}},GC=($)=>IX($,decodeURI),sN=($)=>{let w=$.url,E=w.indexOf("/",w.indexOf(":")+4),X=E;for(;X<w.length;X++){let G=w.charCodeAt(X);if(G===37){let J=w.indexOf("?",X),A=w.indexOf("#",X),D=J===-1?A===-1?void 0:A:A===-1?J:Math.min(J,A),N=w.slice(E,D);return GC(N.includes("%25")?N.replace(/%25/g,"%2525"):N)}else if(G===63||G===35)break}return w.slice(E,X)},o3=($)=>{let w=sN($);return w.length>1&&w.at(-1)==="/"?w.slice(0,-1):w},f1=($,w,...E)=>{if(E.length)w=f1(w,...E);return`${$?.[0]==="/"?"":"/"}${$}${w==="/"?"":`${$?.at(-1)==="/"?"":"/"}${w?.[0]==="/"?w.slice(1):w}`}`},SA=($)=>{if($.charCodeAt($.length-1)!==63||!$.includes(":"))return null;let w=$.split("/"),E=[],X="";return w.forEach((G)=>{if(G!==""&&!/\:/.test(G))X+="/"+G;else if(/\:/.test(G))if(/\?/.test(G)){if(E.length===0&&X==="")E.push("/");else E.push(X);let J=G.replace("?","");X+="/"+J,E.push(X)}else X+="/"+G}),E.filter((G,J,A)=>A.indexOf(G)===J)},dN=($)=>{if(!/[%+]/.test($))return $;if($.indexOf("+")!==-1)$=$.replace(/\+/g," ");return $.indexOf("%")!==-1?IX($,aG):$},t3=($,w,E)=>{let X;if(!E&&w&&!/[%+]/.test(w)){let A=$.indexOf("?",8);if(A===-1)return;if(!$.startsWith(w,A+1))A=$.indexOf(`&${w}`,A+1);while(A!==-1){let D=$.charCodeAt(A+w.length+1);if(D===61){let N=A+w.length+2,W=$.indexOf("&",N);return dN($.slice(N,W===-1?void 0:W))}else if(D==38||isNaN(D))return"";A=$.indexOf(`&${w}`,A+1)}if(X=/[%+]/.test($),!X)return}let G={};X??=/[%+]/.test($);let J=$.indexOf("?",8);while(J!==-1){let A=$.indexOf("&",J+1),D=$.indexOf("=",J);if(D>A&&A!==-1)D=-1;let N=$.slice(J+1,D===-1?A===-1?void 0:A:D);if(X)N=dN(N);if(J=A,N==="")continue;let W;if(D===-1)W="";else if(W=$.slice(D+1,A===-1?void 0:A),X)W=dN(W);if(E){if(!(G[N]&&Array.isArray(G[N])))G[N]=[];G[N].push(W)}else G[N]??=W}return w?G[w]:G},i3,d3=($,w)=>{return t3($,w,!0)},aG;var pw=R(()=>{qA={},i3=t3,aG=decodeURIComponent});var JC,AC,aN=($,w)=>{if(w&&$.indexOf(w)===-1)return{};let E=$.trim().split(";"),X={};for(let G of E){G=G.trim();let J=G.indexOf("=");if(J===-1)continue;let A=G.substring(0,J).trim();if(w&&w!==A||!JC.test(A))continue;let D=G.substring(J+1).trim();if(D.startsWith('"')&&D.endsWith('"'))D=D.slice(1,-1);if(AC.test(D)){if(X[A]=D.indexOf("%")!==-1?IX(D,aG):D,w)break}}return X};var l3=R(()=>{pw();JC=/^[\w!#$%&'*.^`|~+-]+$/,AC=/^[ !#-:<-[\]-~]*$/});var s3=($,w,E)=>{let X=$.req.raw.headers.get("Cookie");if(typeof w==="string"){if(!X)return;let J=w;if(E==="secure")J="__Secure-"+w;else if(E==="host")J="__Host-"+w;return aN(X,J)[J]}if(!X)return{};return aN(X)};var a3=R(()=>{l3()});var kA;var eN=R(()=>{kA=class extends Error{res;status;constructor($=500,w){super(w?.message,{cause:w?.cause});this.res=w?.res,this.status=$}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}}});var e3=()=>{};var $F=($,w)=>{return new Response($,{headers:{"Content-Type":w}}).formData()};var wF=R(()=>{e3()});var DC,NC,WC,$9=($,w)=>{return async(E,X)=>{let G={},J=E.req.header("Content-Type");switch($){case"json":if(!J||!DC.test(J))break;try{G=await E.req.json()}catch{throw new kA(400,{message:"Malformed JSON in request body"})}break;case"form":{if(!J||!(NC.test(J)||WC.test(J)))break;let D;if(E.req.bodyCache.formData)D=await E.req.bodyCache.formData;else try{let W=await E.req.arrayBuffer();D=await $F(W,J),E.req.bodyCache.formData=D}catch(W){let O="Malformed FormData request.";throw O+=W instanceof Error?` ${W.message}`:` ${String(W)}`,new kA(400,{message:O})}let N=Object.create(null);D.forEach((W,O)=>{if(O.endsWith("[]"))(N[O]??=[]).push(W);else if(Array.isArray(N[O]))N[O].push(W);else if(Object.hasOwn(N,O))N[O]=[N[O],W];else N[O]=W}),G=N;break}case"query":G=Object.fromEntries(Object.entries(E.req.queries()).map(([D,N])=>{return N.length===1?[D,N[0]]:[D,N]}));break;case"param":G=E.req.param();break;case"header":G=E.req.header();break;case"cookie":G=s3(E);break}let A=await w(G,E);if(A instanceof Response)return A;return E.req.addValidatedData($,A),await X()}};var EF=R(()=>{a3();eN();wF();DC=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,NC=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,WC=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/});var XF=R(()=>{EF()});function OC($,w,E,X){return $9($,async(G,J)=>{let A=G;if($==="header"&&"_def"in w||$==="header"&&"_zod"in w){let N=Object.keys("in"in w?w.in.shape:w.shape),W=Object.fromEntries(N.map((O)=>[O.toLowerCase(),O]));A=Object.fromEntries(Object.entries(G).map(([O,Y])=>[W[O]||O,Y]))}let D=X&&X.validationFunction?await X.validationFunction(w,A):await w.safeParseAsync(A);if(E){let N=await E({data:A,...D,target:$},J);if(N){if(N instanceof Response)return N;if("response"in N)return N.response}}if(!D.success)return J.json(D,400);return D.data})}var BE;var GF=R(()=>{XF();BE=OC});var w9=($,w,E)=>{return(X,G)=>{let J=-1;return A(0);async function A(D){if(D<=J)throw Error("next() called multiple times");J=D;let N,W=!1,O;if($[D])O=$[D][0][0],X.req.routeIndex=D;else O=D===$.length&&G||void 0;if(O)try{N=await O(X,()=>A(D+1))}catch(Y){if(Y instanceof Error&&w)X.error=Y,N=await w(Y,X),W=!0;else throw Y}else if(X.finalized===!1&&E)N=await E(X);if(N&&(X.finalized===!1||W))X.res=N;return X}}};var JF=()=>{};var AF;var DF=R(()=>{AF=Symbol()});async function UC($,w){let E=await $.formData();if(E)return YC(E,w);return{}}function YC($,w){let E=Object.create(null);if($.forEach((X,G)=>{if(!(w.all||G.endsWith("[]")))E[G]=X;else HC(E,G,X)}),w.dot)Object.entries(E).forEach(([X,G])=>{if(X.includes("."))LC(E,X,G),delete E[X]});return E}var NF=async($,w=Object.create(null))=>{let{all:E=!1,dot:X=!1}=w,J=($ instanceof bA?$.raw.headers:$.headers).get("Content-Type");if(J?.startsWith("multipart/form-data")||J?.startsWith("application/x-www-form-urlencoded"))return UC($,{all:E,dot:X});return{}},HC=($,w,E)=>{if($[w]!==void 0)if(Array.isArray($[w]))$[w].push(E);else $[w]=[$[w],E];else if(!w.endsWith("[]"))$[w]=E;else $[w]=[E]},LC=($,w,E)=>{if(/(?:^|\.)__proto__\./.test(w))return;let X=$,G=w.split(".");G.forEach((J,A)=>{if(A===G.length-1)X[J]=E;else{if(!X[J]||typeof X[J]!=="object"||Array.isArray(X[J])||X[J]instanceof File)X[J]=Object.create(null);X=X[J]}})};var WF=R(()=>{E9()});var OF=($)=>IX($,aG),bA;var E9=R(()=>{eN();DF();WF();pw();bA=class{raw;#$;#w;routeIndex=0;path;bodyCache={};constructor($,w="/",E=[[]]){this.raw=$,this.path=w,this.#w=E,this.#$={}}param($){return $?this.#E($):this.#J()}#E($){let w=this.#w[0][this.routeIndex][1][$],E=this.#G(w);return E&&/\%/.test(E)?OF(E):E}#J(){let $={},w=Object.keys(this.#w[0][this.routeIndex][1]);for(let E of w){let X=this.#G(this.#w[0][this.routeIndex][1][E]);if(X!==void 0)$[E]=/\%/.test(X)?OF(X):X}return $}#G($){return this.#w[1]?this.#w[1][$]:$}query($){return i3(this.url,$)}queries($){return d3(this.url,$)}header($){if($)return this.raw.headers.get($)??void 0;let w={};return this.raw.headers.forEach((E,X)=>{w[X]=E}),w}async parseBody($){return this.bodyCache.parsedBody??=await NF(this,$)}#X=($)=>{let{bodyCache:w,raw:E}=this,X=w[$];if(X)return X;let G=Object.keys(w)[0];if(G)return w[G].then((J)=>{if(G==="json")J=JSON.stringify(J);return new Response(J)[$]()});return w[$]=E[$]()};json(){return this.#X("text").then(($)=>JSON.parse($))}text(){return this.#X("text")}arrayBuffer(){return this.#X("arrayBuffer")}blob(){return this.#X("blob")}formData(){return this.#X("formData")}addValidatedData($,w){this.#$[$]=w}valid($){return this.#$[$]}get url(){return this.raw.url}get method(){return this.raw.method}get[AF](){return this.#w}get matchedRoutes(){return this.#w[0].map(([[,$]])=>$)}get routePath(){return this.#w[0].map(([[,$]])=>$)[this.routeIndex].path}}});var FC="text/plain; charset=UTF-8",X9=($,w)=>{return{"Content-Type":$,...w}},eG=($,w)=>new Response($,w),UF=class{#$;#w;env={};#E;finalized=!1;error;#J;#G;#X;#O;#N;#W;#D;#U;#Y;constructor($,w){if(this.#$=$,w)this.#G=w.executionCtx,this.env=w.env,this.#W=w.notFoundHandler,this.#Y=w.path,this.#U=w.matchResult}get req(){return this.#w??=new bA(this.#$,this.#Y,this.#U),this.#w}get event(){if(this.#G&&"respondWith"in this.#G)return this.#G;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#G)return this.#G;else throw Error("This context has no ExecutionContext")}get res(){return this.#X||=eG(null,{headers:this.#D??=new Headers})}set res($){if(this.#X&&$){$=eG($.body,$);for(let[w,E]of this.#X.headers.entries()){if(w==="content-type")continue;if(w==="set-cookie"){let X=this.#X.headers.getSetCookie();$.headers.delete("set-cookie");for(let G of X)$.headers.append("set-cookie",G)}else $.headers.set(w,E)}}this.#X=$,this.finalized=!0}render=(...$)=>{return this.#N??=(w)=>this.html(w),this.#N(...$)};setLayout=($)=>this.#O=$;getLayout=()=>this.#O;setRenderer=($)=>{this.#N=$};header=($,w,E)=>{if(this.finalized)this.#X=eG(this.#X.body,this.#X);let X=this.#X?this.#X.headers:this.#D??=new Headers;if(w===void 0)X.delete($);else if(E?.append)X.append($,w);else X.set($,w)};status=($)=>{this.#J=$};set=($,w)=>{this.#E??=new Map,this.#E.set($,w)};get=($)=>{return this.#E?this.#E.get($):void 0};get var(){if(!this.#E)return{};return Object.fromEntries(this.#E)}#A($,w,E){let X=this.#X?new Headers(this.#X.headers):this.#D??new Headers;if(typeof w==="object"&&"headers"in w){let J=w.headers instanceof Headers?w.headers:new Headers(w.headers);for(let[A,D]of J)if(A.toLowerCase()==="set-cookie")X.append(A,D);else X.set(A,D)}if(E)for(let[J,A]of Object.entries(E))if(typeof A==="string")X.set(J,A);else{X.delete(J);for(let D of A)X.append(J,D)}let G=typeof w==="number"?w:w?.status??this.#J;return eG($,{status:G,headers:X})}newResponse=(...$)=>this.#A(...$);body=($,w,E)=>this.#A($,w,E);text=($,w,E)=>{return!this.#D&&!this.#J&&!w&&!E&&!this.finalized?new Response($):this.#A($,w,X9(FC,E))};json=($,w,E)=>{return this.#A(JSON.stringify($),w,X9("application/json",E))};html=($,w,E)=>{let X=(G)=>this.#A(G,w,X9("text/html; charset=UTF-8",E));return typeof $==="object"?cN($,hN.Stringify,!1,{}).then(X):X($)};redirect=($,w)=>{let E=String($);return this.header("Location",!/[^\x00-\xFF]/.test(E)?E:encodeURI(E)),this.newResponse(null,w??302)};notFound=()=>{return this.#W??=()=>eG(),this.#W(this)}};var YF=R(()=>{E9();nN()});var k0="ALL",HF="all",LF,ZA="Can not add a route since the matcher is already built.",CA;var QE=R(()=>{LF=["get","post","put","delete","options","patch"],CA=class extends Error{}});var FF="__COMPOSED_HANDLER";var jF=()=>{};var jC=($)=>{return $.text("404 Not Found",404)},MF=($,w)=>{if("getResponse"in $){let E=$.getResponse();return w.newResponse(E.body,E)}return console.error($),w.text("Internal Server Error",500)},RF=class ${get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#$="/";routes=[];constructor(w={}){[...LF,HF].forEach((J)=>{this[J]=(A,...D)=>{if(typeof A==="string")this.#$=A;else this.#J(J,this.#$,A);return D.forEach((N)=>{this.#J(J,this.#$,N)}),this}}),this.on=(J,A,...D)=>{for(let N of[A].flat()){this.#$=N;for(let W of[J].flat())D.map((O)=>{this.#J(W.toUpperCase(),this.#$,O)})}return this},this.use=(J,...A)=>{if(typeof J==="string")this.#$=J;else this.#$="*",A.unshift(J);return A.forEach((D)=>{this.#J(k0,this.#$,D)}),this};let{strict:X,...G}=w;Object.assign(this,G),this.getPath=X??!0?w.getPath??sN:o3}#w(){let w=new $({router:this.router,getPath:this.getPath});return w.errorHandler=this.errorHandler,w.#E=this.#E,w.routes=this.routes,w}#E=jC;errorHandler=MF;route(w,E){let X=this.basePath(w);return E.routes.map((G)=>{let J;if(E.errorHandler===MF)J=G.handler;else J=async(A,D)=>(await w9([],E.errorHandler)(A,()=>G.handler(A,D))).res,J[FF]=G.handler;X.#J(G.method,G.path,J)}),this}basePath(w){let E=this.#w();return E._basePath=f1(this._basePath,w),E}onError=(w)=>{return this.errorHandler=w,this};notFound=(w)=>{return this.#E=w,this};mount(w,E,X){let G,J;if(X)if(typeof X==="function")J=X;else if(J=X.optionHandler,X.replaceRequest===!1)G=(N)=>N;else G=X.replaceRequest;let A=J?(N)=>{let W=J(N);return Array.isArray(W)?W:[W]}:(N)=>{let W=void 0;try{W=N.executionCtx}catch{}return[N.env,W]};G||=(()=>{let N=f1(this._basePath,w),W=N==="/"?0:N.length;return(O)=>{let Y=new URL(O.url);return Y.pathname=Y.pathname.slice(W)||"/",new Request(Y,O)}})();let D=async(N,W)=>{let O=await E(G(N.req.raw),...A(N));if(O)return O;await W()};return this.#J(k0,f1(w,"*"),D),this}#J(w,E,X){w=w.toUpperCase(),E=f1(this._basePath,E);let G={basePath:this._basePath,path:E,method:w,handler:X};this.router.add(w,E,[X,G]),this.routes.push(G)}#G(w,E){if(w instanceof Error)return this.errorHandler(w,E);throw w}#X(w,E,X,G){if(G==="HEAD")return(async()=>new Response(null,await this.#X(w,E,X,"GET")))();let J=this.getPath(w,{env:X}),A=this.router.match(G,J),D=new UF(w,{path:J,matchResult:A,env:X,executionCtx:E,notFoundHandler:this.#E});if(A[0].length===1){let W;try{W=A[0][0][0][0](D,async()=>{D.res=await this.#E(D)})}catch(O){return this.#G(O,D)}return W instanceof Promise?W.then((O)=>O||(D.finalized?D.res:this.#E(D))).catch((O)=>this.#G(O,D)):W??this.#E(D)}let N=w9(A[0],this.errorHandler,this.#E);return(async()=>{try{let W=await N(D);if(!W.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return W.res}catch(W){return this.#G(W,D)}})()}fetch=(w,...E)=>{return this.#X(w,E[1],E[0],w.method)};request=(w,E,X,G)=>{if(w instanceof Request)return this.fetch(E?new Request(w,E):w,X,G);return w=w.toString(),this.fetch(new Request(/^https?:\/\//.test(w)?w:`http://localhost${f1("/",w)}`,E),X,G)};fire=()=>{addEventListener("fetch",(w)=>{w.respondWith(this.#X(w.request,w,void 0,w.request.method))})}};var zF=R(()=>{JF();YF();QE();jF();pw()});function _A($,w){let E=this.buildAllMatchers(),X=(G,J)=>{let A=E[G]||E[k0],D=A[2][J];if(D)return D;let N=J.match(A[0]);if(!N)return[[],$6];let W=N.indexOf("",1);return[A[1][W],N]};return this.match=X,X($,w)}var $6;var G9=R(()=>{QE();$6=[]});function RC($,w){if($.length===1)return w.length===1?$<w?-1:1:-1;if(w.length===1)return 1;if($===w6||$===E6)return 1;else if(w===w6||w===E6)return-1;if($===vA)return 1;else if(w===vA)return-1;return $.length===w.length?$<w?-1:1:w.length-$.length}var vA="[^/]+",w6=".*",E6="(?:|/.*)",IE,MC,TF=class ${#$;#w;#E=Object.create(null);insert(w,E,X,G,J){if(w.length===0){if(this.#$!==void 0)throw IE;if(J)return;this.#$=E;return}let[A,...D]=w,N=A==="*"?D.length===0?["","",w6]:["","",vA]:A==="/*"?["","",E6]:A.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),W;if(N){let O=N[1],Y=N[2]||vA;if(O&&N[2]){if(Y===".*")throw IE;if(Y=Y.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(Y))throw IE}if(W=this.#E[Y],!W){if(Object.keys(this.#E).some((H)=>H!==w6&&H!==E6))throw IE;if(J)return;if(W=this.#E[Y]=new $,O!=="")W.#w=G.varIndex++}if(!J&&O!=="")X.push([O,W.#w])}else if(W=this.#E[A],!W){if(Object.keys(this.#E).some((O)=>O.length>1&&O!==w6&&O!==E6))throw IE;if(J)return;W=this.#E[A]=new $}W.insert(D,E,X,G,J)}buildRegExpStr(){let E=Object.keys(this.#E).sort(RC).map((X)=>{let G=this.#E[X];return(typeof G.#w==="number"?`(${X})@${G.#w}`:MC.has(X)?`\\${X}`:X)+G.buildRegExpStr()});if(typeof this.#$==="number")E.unshift(`#${this.#$}`);if(E.length===0)return"";if(E.length===1)return E[0];return"(?:"+E.join("|")+")"}};var J9=R(()=>{IE=Symbol(),MC=new Set(".\\+*[^]$()")});var BF=class{#$={varIndex:0};#w=new TF;insert($,w,E){let X=[],G=[];for(let A=0;;){let D=!1;if($=$.replace(/\{[^}]+\}/g,(N)=>{let W=`@\\${A}`;return G[A]=[W,N],A++,D=!0,W}),!D)break}let J=$.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let A=G.length-1;A>=0;A--){let[D]=G[A];for(let N=J.length-1;N>=0;N--)if(J[N].indexOf(D)!==-1){J[N]=J[N].replace(D,G[A][1]);break}}return this.#w.insert(J,w,X,this.#$,E),X}buildRegExp(){let $=this.#w.buildRegExpStr();if($==="")return[/^$/,[],[]];let w=0,E=[],X=[];return $=$.replace(/#(\d+)|@(\d+)|\.\*\$/g,(G,J,A)=>{if(J!==void 0)return E[++w]=Number(J),"$()";if(A!==void 0)return X[Number(A)]=++w,"";return""}),[new RegExp(`^${$}`),E,X]}};var QF=R(()=>{J9()});function KF($){return IF[$]??=new RegExp($==="*"?"":`^${$.replace(/\/\*$|([.\\+*[^\]$()])/g,(w,E)=>E?`\\${E}`:"(?:|/.*)")}$`)}function TC(){IF=Object.create(null)}function BC($){let w=new BF,E=[];if($.length===0)return zC;let X=$.map((W)=>[!/\*|\/:/.test(W[0]),...W]).sort(([W,O],[Y,H])=>W?1:Y?-1:O.length-H.length),G=Object.create(null);for(let W=0,O=-1,Y=X.length;W<Y;W++){let[H,L,F]=X[W];if(H)G[L]=[F.map(([M])=>[M,Object.create(null)]),$6];else O++;let j;try{j=w.insert(L,O,H)}catch(M){throw M===IE?new CA(L):M}if(H)continue;E[O]=F.map(([M,z])=>{let B=Object.create(null);z-=1;for(;z>=0;z--){let[Q,k]=j[z];B[Q]=k}return[M,B]})}let[J,A,D]=w.buildRegExp();for(let W=0,O=E.length;W<O;W++)for(let Y=0,H=E[W].length;Y<H;Y++){let L=E[W][Y]?.[1];if(!L)continue;let F=Object.keys(L);for(let j=0,M=F.length;j<M;j++)L[F[j]]=D[L[F[j]]]}let N=[];for(let W in A)N[W]=E[A[W]];return[J,N,G]}function KX($,w){if(!$)return;for(let E of Object.keys($).sort((X,G)=>G.length-X.length))if(KF(E).test(w))return[...$[E]];return}var zC,IF,fA=class{name="RegExpRouter";#$;#w;constructor(){this.#$={[k0]:Object.create(null)},this.#w={[k0]:Object.create(null)}}add($,w,E){let X=this.#$,G=this.#w;if(!X||!G)throw Error(ZA);if(!X[$])[X,G].forEach((D)=>{D[$]=Object.create(null),Object.keys(D[k0]).forEach((N)=>{D[$][N]=[...D[k0][N]]})});if(w==="/*")w="*";let J=(w.match(/\/:/g)||[]).length;if(/\*$/.test(w)){let D=KF(w);if($===k0)Object.keys(X).forEach((N)=>{X[N][w]||=KX(X[N],w)||KX(X[k0],w)||[]});else X[$][w]||=KX(X[$],w)||KX(X[k0],w)||[];Object.keys(X).forEach((N)=>{if($===k0||$===N)Object.keys(X[N]).forEach((W)=>{D.test(W)&&X[N][W].push([E,J])})}),Object.keys(G).forEach((N)=>{if($===k0||$===N)Object.keys(G[N]).forEach((W)=>D.test(W)&&G[N][W].push([E,J]))});return}let A=SA(w)||[w];for(let D=0,N=A.length;D<N;D++){let W=A[D];Object.keys(G).forEach((O)=>{if($===k0||$===O)G[O][W]||=[...KX(X[O],W)||KX(X[k0],W)||[]],G[O][W].push([E,J-N+D+1])})}}match=_A;buildAllMatchers(){let $=Object.create(null);return Object.keys(this.#w).concat(Object.keys(this.#$)).forEach((w)=>{$[w]||=this.#E(w)}),this.#$=this.#w=void 0,TC(),$}#E($){let w=[],E=$===k0;if([this.#$,this.#w].forEach((X)=>{let G=X[$]?Object.keys(X[$]).map((J)=>[J,X[$][J]]):[];if(G.length!==0)E||=!0,w.push(...G);else if($!==k0)w.push(...Object.keys(X[k0]).map((J)=>[J,X[k0][J]]))}),!E)return null;else return BC(w)}};var A9=R(()=>{QE();pw();G9();J9();QF();zC=[/^$/,[],Object.create(null)],IF=Object.create(null)});var QC=class{name="PreparedRegExpRouter";#$;#w;constructor($,w){this.#$=$,this.#w=w}#E($,w){let E=this.#$[$];E[1].forEach((X)=>X&&X.push(w)),Object.values(E[2]).forEach((X)=>X[0].push(w))}#J($,w,E,X,G){let J=this.#$[$];if(!G)J[2][w][0].push([E,{}]);else X.forEach((A)=>{if(typeof A==="number")J[1][A].push([E,G]);else J[2][A||w][0].push([E,G])})}add($,w,E){if(!this.#$[$]){let G=this.#$[k0],J={};for(let A in G[2])J[A]=[G[2][A][0].slice(),$6];this.#$[$]=[G[0],G[1].map((A)=>Array.isArray(A)?A.slice():0),J]}if(w==="/*"||w==="*"){let G=[E,{}];if($===k0)for(let J in this.#$)this.#E(J,G);else this.#E($,G);return}let X=this.#w[w];if(!X)throw Error(`Path ${w} is not registered`);for(let[G,J]of X)if($===k0)for(let A in this.#$)this.#J(A,w,E,G,J);else this.#J($,w,E,G,J)}buildAllMatchers(){return this.#$}match=_A};var VF=R(()=>{QE();G9();A9()});var PF=R(()=>{A9();VF()});var D9=class{name="SmartRouter";#$=[];#w=[];constructor($){this.#$=$.routers}add($,w,E){if(!this.#w)throw Error(ZA);this.#w.push([$,w,E])}match($,w){if(!this.#w)throw Error("Fatal error");let E=this.#$,X=this.#w,G=E.length,J=0,A;for(;J<G;J++){let D=E[J];try{for(let N=0,W=X.length;N<W;N++)D.add(...X[N]);A=D.match($,w)}catch(N){if(N instanceof CA)continue;throw N}this.match=D.match.bind(D),this.#$=[D],this.#w=void 0;break}if(J===G)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,A}get activeRouter(){if(this.#w||this.#$.length!==1)throw Error("No active router has been determined yet.");return this.#$[0]}};var qF=R(()=>{QE()});var SF=R(()=>{qF()});var X6,IC=($)=>{for(let w in $)return!0;return!1},kF=class ${#$;#w;#E;#J=0;#G=X6;constructor(w,E,X){if(this.#w=X||Object.create(null),this.#$=[],w&&E){let G=Object.create(null);G[w]={handler:E,possibleKeys:[],score:0},this.#$=[G]}this.#E=[]}insert(w,E,X){this.#J=++this.#J;let G=this,J=r3(E),A=[];for(let D=0,N=J.length;D<N;D++){let W=J[D],O=J[D+1],Y=p3(W,O),H=Array.isArray(Y)?Y[0]:W;if(H in G.#w){if(G=G.#w[H],Y)A.push(Y[1]);continue}if(G.#w[H]=new $,Y)G.#E.push(Y),A.push(Y[1]);G=G.#w[H]}return G.#$.push({[w]:{handler:X,possibleKeys:A.filter((D,N,W)=>W.indexOf(D)===N),score:this.#J}}),G}#X(w,E,X,G,J){for(let A=0,D=E.#$.length;A<D;A++){let N=E.#$[A],W=N[X]||N[k0],O={};if(W!==void 0){if(W.params=Object.create(null),w.push(W),G!==X6||J&&J!==X6)for(let Y=0,H=W.possibleKeys.length;Y<H;Y++){let L=W.possibleKeys[Y],F=O[W.score];W.params[L]=J?.[L]&&!F?J[L]:G[L]??J?.[L],O[W.score]=!0}}}}search(w,E){let X=[];this.#G=X6;let J=[this],A=lN(E),D=[],N=A.length,W=null;for(let O=0;O<N;O++){let Y=A[O],H=O===N-1,L=[];for(let j=0,M=J.length;j<M;j++){let z=J[j],B=z.#w[Y];if(B)if(B.#G=z.#G,H){if(B.#w["*"])this.#X(X,B.#w["*"],w,z.#G);this.#X(X,B,w,z.#G)}else L.push(B);for(let Q=0,k=z.#E.length;Q<k;Q++){let v=z.#E[Q],C=z.#G===X6?{}:{...z.#G};if(v==="*"){let d0=z.#w["*"];if(d0)this.#X(X,d0,w,z.#G),d0.#G=C,L.push(d0);continue}let[n,T0,f0]=v;if(!Y&&!(f0 instanceof RegExp))continue;let c0=z.#w[n];if(f0 instanceof RegExp){if(W===null){W=Array(N);let U$=E[0]==="/"?1:0;for(let O1=0;O1<N;O1++)W[O1]=U$,U$+=A[O1].length+1}let d0=E.substring(W[O]),K0=f0.exec(d0);if(K0){if(C[T0]=K0[0],this.#X(X,c0,w,z.#G,C),IC(c0.#w)){c0.#G=C;let U$=K0[0].match(/\//)?.length??0;(D[U$]||=[]).push(c0)}continue}}if(f0===!0||f0.test(Y))if(C[T0]=Y,H){if(this.#X(X,c0,w,C,z.#G),c0.#w["*"])this.#X(X,c0.#w["*"],w,C,z.#G)}else c0.#G=C,L.push(c0)}}let F=D.shift();J=F?L.concat(F):L}if(X.length>1)X.sort((O,Y)=>{return O.score-Y.score});return[X.map(({handler:O,params:Y})=>[O,Y])]}};var bF=R(()=>{QE();pw();X6=Object.create(null)});var N9=class{name="TrieRouter";#$;constructor(){this.#$=new kF}add($,w,E){let X=SA(w);if(X){for(let G=0,J=X.length;G<J;G++)this.#$.insert($,X[G],E);return}this.#$.insert($,w,E)}match($,w){return this.#$.search($,w)}};var ZF=R(()=>{pw();bF()});var CF=R(()=>{ZF()});var W9;var _F=R(()=>{zF();PF();SF();CF();W9=class extends RF{constructor($={}){super($);this.router=$.router??new D9({routers:[new fA,new N9]})}}});var vF=R(()=>{_F()});function fF($,w){let E={};return Object.keys($.paths).forEach((X)=>{E[f1(w.replaceAll(/:([^\/]+)/g,"{$1}"),X)]=$.paths[X]}),{...$,paths:E}}function xF($){return/^application\/([a-z-\.]+\+)?json/.test($)}function yF($){return $.startsWith("multipart/form-data")||$.startsWith("application/x-www-form-urlencoded")}var p0,m=($)=>{let w={...$,getRoutingPath(){return $.path.replaceAll(/\/{(.+?)}/g,"/:$1")}};return Object.defineProperty(w,"getRoutingPath",{enumerable:!1})};var N1=R(()=>{m3();GF();vF();pw();WG();p0=class $ extends W9{openAPIRegistry;defaultHook;constructor(w){super(w);this.openAPIRegistry=new pN,this.defaultHook=w?.defaultHook}openapi=({middleware:w,hide:E,...X},G,J=this.defaultHook)=>{if(!E)this.openAPIRegistry.registerPath(X);let A=[];if(X.request?.query){let W=BE("query",X.request.query,J);A.push(W)}if(X.request?.params){let W=BE("param",X.request.params,J);A.push(W)}if(X.request?.headers){let W=BE("header",X.request.headers,J);A.push(W)}if(X.request?.cookies){let W=BE("cookie",X.request.cookies,J);A.push(W)}let D=X.request?.body?.content;if(D)for(let W of Object.keys(D)){if(!D[W])continue;let O=D[W].schema;if(!(O instanceof G0))continue;if(xF(W)){let Y=BE("json",O,J);if(X.request?.body?.required)A.push(Y);else{let H=async(L,F)=>{if(L.req.header("content-type")){if(xF(L.req.header("content-type")))return await Y(L,F)}L.req.addValidatedData("json",{}),await F()};A.push(H)}}if(yF(W)){let Y=BE("form",O,J);if(X.request?.body?.required)A.push(Y);else{let H=async(L,F)=>{if(L.req.header("content-type")){if(yF(L.req.header("content-type")))return await Y(L,F)}L.req.addValidatedData("form",{}),await F()};A.push(H)}}}let N=w?Array.isArray(w)?w:[w]:[];return this.on([X.method],X.path.replaceAll(/\/{(.+?)}/g,"/:$1"),...N,...A,G),this};getOpenAPIDocument=(w)=>{let X=new tN(this.openAPIRegistry.definitions).generateDocument(w);return this._basePath?fF(X,this._basePath):X};getOpenAPI31Document=(w)=>{let X=new iN(this.openAPIRegistry.definitions).generateDocument(w);return this._basePath?fF(X,this._basePath):X};doc=(w,E)=>{return this.get(w,(X)=>{let G=typeof E==="function"?E(X):E;try{let J=this.getOpenAPIDocument(G);return X.json(J)}catch(J){return X.json(J,500)}})};doc31=(w,E)=>{return this.get(w,(X)=>{let G=typeof E==="function"?E(X):E;try{let J=this.getOpenAPI31Document(G);return X.json(J)}catch(J){return X.json(J,500)}})};route(w,E){let X=w.replaceAll(/:([^\/]+)/g,"{$1}");if(super.route(w,E),!(E instanceof $))return this;return E.openAPIRegistry.definitions.forEach((G)=>{switch(G.type){case"component":return this.openAPIRegistry.registerComponent(G.componentType,G.name,G.component);case"route":{this.openAPIRegistry.registerPath({...G.route,path:f1(X,E._basePath.replaceAll(/:([^\/]+)/g,"{$1}"),G.route.path)});return}case"webhook":{this.openAPIRegistry.registerWebhook({...G.webhook,path:f1(X,E._basePath.replaceAll(/:([^\/]+)/g,"{$1}"),G.webhook.path)});return}case"schema":return this.openAPIRegistry.register(G.schema._def.openapi._internal.refId,G.schema);case"parameter":return this.openAPIRegistry.registerParameter(G.schema._def.openapi._internal.refId,G.schema);default:throw Error(`Unknown registry type: ${G}`)}}),this}basePath(w){return new $({...super.basePath(w),defaultHook:this.defaultHook})}};I3(U)});var VX,U0,Ew,O9;var x1=R(()=>{VX=class VX extends Error{code;statusCode;constructor($,w,E=500){super($);this.code=w;this.statusCode=E;this.name="OrcError"}};U0=class U0 extends VX{constructor($,w){super(`${$} not found: ${w}`,"NOT_FOUND",404);this.name="NotFoundError"}};Ew=class Ew extends VX{constructor($){super($,"VALIDATION_ERROR",400);this.name="ValidationError"}};O9=class O9 extends VX{constructor($="Unauthorized"){super($,"UNAUTHORIZED",401);this.name="UnauthorizedError"}}});function gF($){return async(w,E)=>{if(!$)return E();let X=w.req.header("Authorization");if(!X?.startsWith("Bearer ")||X.slice(7)!==$)throw new O9;return E()}}var uF=R(()=>{x1()});var xA,KC,VC,PC,qC;var hF=R(()=>{N1();qN();xA=new p0,KC=U.object({running:U.boolean(),status:U.string()}).openapi("GatewayStatus"),VC=U.object({platform:U.string(),chat_id:U.string(),text:U.string(),thread_id:U.string().optional()}).openapi("GatewaySend"),PC=m({method:"get",path:"/gateway/status",tags:["Gateway"],summary:"Get gateway status",responses:{200:{content:{"application/json":{schema:KC}},description:"Gateway status"}}}),qC=m({method:"post",path:"/gateway/send",tags:["Gateway"],summary:"Send a message via the gateway",request:{body:{content:{"application/json":{schema:VC}}}},responses:{204:{description:"Message sent"},503:{content:{"application/json":{schema:U.object({error:U.string()})}},description:"Gateway not running"}}});xA.openapi(PC,async($)=>{let w=MA()!==null;return $.json({running:w,status:PN()})});xA.openapi(qC,async($)=>{if(!MA())return $.json({error:"Gateway is not running"},503);let{platform:w,chat_id:E,text:X,thread_id:G}=$.req.valid("json");return await VN(w,E,X,G?{threadId:G}:void 0),$.body(null,204)})});var U9,SC,kC;var cF=R(()=>{N1();U9=new p0,SC=m({method:"get",path:"/health",tags:["System"],summary:"Health check",responses:{200:{description:"Service is healthy",content:{"application/json":{schema:U.object({status:U.literal("ok"),version:U.string(),uptime:U.number()})}}}}}),kC=Date.now();U9.openapi(SC,($)=>{return $.json({status:"ok",version:"0.0.1",uptime:Math.floor((Date.now()-kC)/1000)})})});var yA,G6,gA,nF,uA,qw0,Sw0,kw0,Y9,bw0,Zw0,Cw0;var hA=R(()=>{WG();yA=U.enum(["todo","doing","review","changes_requested","blocked","done","cancelled"]),G6=U.enum(["low","normal","high","critical"]),gA=U.enum(["one-shot","cron","watch","webhook","manual","bridge-msg"]),nF=U.enum(["pending","running","success","failed","cancelled","skipped"]),uA=U.enum(["skip","queue","kill"]),qw0=U.enum(["low","normal","high","critical"]),Sw0=U.enum(["telegram","slack","discord","feishu"]),kw0=U.enum(["direct","agent:claude","agent:codex","agent:cursor","multi"]).or(U.string().startsWith("job:")),Y9=U.enum(["blocks","blocked_by","relates_to","duplicates","clones","subtask_of","parent_of"]),bw0=U.enum(["active","archived","paused"]),Zw0=U.enum(["solo","pair","parallel","handoff"]),Cw0=U.enum(["solo","human_agent","multi_agent"])});function nA($){return{...$,project_id:$.project_id??null,last_run_at:$.last_run_at?.toISOString()??null,next_run_at:$.next_run_at?.toISOString()??null,created_at:$.created_at.toISOString(),updated_at:$.updated_at.toISOString()}}function mC($){return{...$,started_at:$.started_at?.toISOString()??null,ended_at:$.ended_at?.toISOString()??null,created_at:$.created_at.toISOString()}}var bC,Xw,cA,ZC,CC,_C,vC,fC,xC,yC,gC,uC,hC,cC,nC;var mF=R(()=>{N1();x1();X1();p$();hA();y$();d$();nw();i$();bC=Z0("api:jobs"),Xw=new p0,cA=U.object({id:U.string(),name:U.string(),description:U.string().nullable(),command:U.string(),trigger_type:gA,cron_expr:U.string().nullable(),enabled:U.boolean(),timeout_secs:U.number(),max_retries:U.number(),overlap:uA,notify_on:U.enum(["never","failure","always"]),project_id:U.string().nullable(),run_count:U.number(),last_run_at:U.string().datetime().nullable(),next_run_at:U.string().datetime().nullable(),created_at:U.string().datetime(),updated_at:U.string().datetime()}).openapi("Job"),ZC=U.object({name:U.string().min(1).max(100),description:U.string().optional(),command:U.string().min(1),trigger_type:gA,cron_expr:U.string().optional(),watch_path:U.string().optional(),timeout_secs:U.number().int().positive().optional().default(300),max_retries:U.number().int().min(0).optional().default(0),overlap:uA.optional().default("skip"),notify_on:U.enum(["never","failure","always"]).optional().default("failure"),env_vars:U.record(U.string()).optional(),working_dir:U.string().optional(),project_id:U.string().optional()}).openapi("CreateJob"),CC=U.object({id:U.string(),job_id:U.string(),status:nF,trigger_by:U.string().nullable(),started_at:U.string().datetime().nullable(),ended_at:U.string().datetime().nullable(),exit_code:U.number().nullable(),error_msg:U.string().nullable(),retry_num:U.number(),created_at:U.string().datetime()}).openapi("JobRun"),_C=U.object({id:U.number(),run_id:U.string(),ts:U.string().datetime(),stream:U.enum(["stdout","stderr"]),line:U.string()}).openapi("JobRunLog"),vC=m({method:"get",path:"/jobs",tags:["Jobs"],summary:"List jobs",request:{query:U.object({enabled:U.coerce.boolean().optional(),project_id:U.string().optional(),limit:U.coerce.number().int().min(1).max(100).optional().default(50)})},responses:{200:{description:"Jobs",content:{"application/json":{schema:U.object({jobs:U.array(cA)})}}}}}),fC=m({method:"get",path:"/jobs/{id}",tags:["Jobs"],summary:"Get job",request:{params:U.object({id:U.string()})},responses:{200:{description:"Job",content:{"application/json":{schema:cA}}}}}),xC=m({method:"post",path:"/jobs",tags:["Jobs"],summary:"Create job",request:{body:{content:{"application/json":{schema:ZC}}}},responses:{201:{description:"Created",content:{"application/json":{schema:cA}}}}}),yC=U.object({name:U.string().min(1).max(100).optional(),description:U.string().optional(),command:U.string().min(1).optional(),trigger_type:gA.optional(),cron_expr:U.string().optional(),watch_path:U.string().optional(),timeout_secs:U.number().int().positive().optional(),max_retries:U.number().int().min(0).optional(),overlap:uA.optional(),notify_on:U.enum(["never","failure","always"]).optional(),enabled:U.boolean().optional(),env_vars:U.record(U.string()).optional(),working_dir:U.string().optional(),project_id:U.string().optional()}).openapi("UpdateJob"),gC=m({method:"patch",path:"/jobs/{id}",tags:["Jobs"],summary:"Update job",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:yC}}}},responses:{200:{description:"Updated",content:{"application/json":{schema:cA}}}}}),uC=m({method:"delete",path:"/jobs/{id}",tags:["Jobs"],summary:"Delete job",request:{params:U.object({id:U.string()})},responses:{204:{description:"Deleted"}}}),hC=m({method:"post",path:"/jobs/{id}/trigger",tags:["Jobs"],summary:"Manually trigger a job",request:{params:U.object({id:U.string()})},responses:{202:{description:"Triggered",content:{"application/json":{schema:U.object({run_id:U.string()})}}}}}),cC=m({method:"get",path:"/jobs/{id}/runs",tags:["Jobs"],summary:"List job runs",request:{params:U.object({id:U.string()}),query:U.object({limit:U.coerce.number().int().min(1).max(50).optional().default(20)})},responses:{200:{description:"Runs",content:{"application/json":{schema:U.object({runs:U.array(CC)})}}}}}),nC=m({method:"get",path:"/jobs/{id}/runs/{runId}/logs",tags:["Jobs"],summary:"Stream log lines for a specific run",request:{params:U.object({id:U.string(),runId:U.string()}),query:U.object({stream:U.enum(["stdout","stderr"]).optional(),limit:U.coerce.number().int().min(1).max(5000).optional().default(500)})},responses:{200:{description:"Log lines",content:{"application/json":{schema:U.object({logs:U.array(_C)})}}}}});Xw.openapi(vC,async($)=>{let w=x(),{limit:E,project_id:X}=$.req.valid("query"),G=[];if(X)G.push(V(I0.project_id,X));let J=await w.query.jobs.findMany({where:G.length?S0(...G):void 0,limit:E,orderBy:(A,{asc:D})=>[D(A.name)]});return $.json({jobs:J.map(nA)})});Xw.openapi(fC,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=await w.query.jobs.findFirst({where:V(I0.id,E)});if(!X)throw new U0("Job",E);return $.json(nA(X))});Xw.openapi(xC,async($)=>{let w=x(),E=$.req.valid("json"),X=new Date,G=i();await w.insert(I0).values({id:G,name:E.name,description:E.description,command:E.command,trigger_type:E.trigger_type,cron_expr:E.cron_expr,watch_path:E.watch_path,timeout_secs:E.timeout_secs,max_retries:E.max_retries,overlap:E.overlap,notify_on:E.notify_on,env_vars:E.env_vars,working_dir:E.working_dir,project_id:E.project_id,created_at:X,updated_at:X});let J=await w.query.jobs.findFirst({where:V(I0.id,G)});if(!J)throw Error("Expected job to exist after write");return $.json(nA(J),201)});Xw.openapi(gC,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=$.req.valid("json");if(!await w.query.jobs.findFirst({where:V(I0.id,E)}))throw new U0("Job",E);await w.update(I0).set({...X.name!==void 0?{name:X.name}:{},...X.description!==void 0?{description:X.description}:{},...X.command!==void 0?{command:X.command}:{},...X.trigger_type!==void 0?{trigger_type:X.trigger_type}:{},...X.cron_expr!==void 0?{cron_expr:X.cron_expr}:{},...X.watch_path!==void 0?{watch_path:X.watch_path}:{},...X.timeout_secs!==void 0?{timeout_secs:X.timeout_secs}:{},...X.max_retries!==void 0?{max_retries:X.max_retries}:{},...X.overlap!==void 0?{overlap:X.overlap}:{},...X.notify_on!==void 0?{notify_on:X.notify_on}:{},...X.enabled!==void 0?{enabled:X.enabled}:{},...X.env_vars!==void 0?{env_vars:X.env_vars}:{},...X.working_dir!==void 0?{working_dir:X.working_dir}:{},...X.project_id!==void 0?{project_id:X.project_id}:{},updated_at:new Date}).where(V(I0.id,E));let J=await w.query.jobs.findFirst({where:V(I0.id,E)});if(!J)throw Error("Expected job to exist after write");return $.json(nA(J))});Xw.openapi(uC,async($)=>{let w=x(),{id:E}=$.req.valid("param");if(!await w.query.jobs.findFirst({where:V(I0.id,E)}))throw new U0("Job",E);return await w.delete(I0).where(V(I0.id,E)),new Response(null,{status:204})});Xw.openapi(hC,async($)=>{let w=x(),{id:E}=$.req.valid("param");if(!await w.query.jobs.findFirst({where:V(I0.id,E)}))throw new U0("Job",E);let G=i();return await w.insert(E$).values({id:G,job_id:E,status:"pending",trigger_by:"api",created_at:new Date}),A1({jobId:E,runId:G,triggerBy:"api"}).catch((J)=>bC.error(`Background execution failed for run ${G}: ${J instanceof Error?J.message:String(J)}`)),$.json({run_id:G},202)});Xw.openapi(cC,async($)=>{let w=x(),{id:E}=$.req.valid("param"),{limit:X}=$.req.valid("query"),G=await w.query.job_runs.findMany({where:V(E$.job_id,E),limit:X,orderBy:[x0(E$.created_at)]});return $.json({runs:G.map(mC)})});Xw.openapi(nC,async($)=>{let w=x(),{id:E,runId:X}=$.req.valid("param"),{stream:G,limit:J}=$.req.valid("query"),A=await w.query.job_runs.findFirst({where:V(E$.id,X)});if(!A||A.job_id!==E)throw new U0("JobRun",X);let D=await w.query.job_run_logs.findMany({where:G?S0(V(cw.run_id,X),V(cw.stream,G)):V(cw.run_id,X),limit:J,orderBy:[VJ(cw.ts)]});return $.json({logs:D.map((N)=>({...N,ts:N.ts.toISOString()}))})})});function rC($,w=80){return $.length<=w?$:`${$.slice(0,w-1)}\u2026`}function pC($){let w=Date.now()-$*1000,E=Math.floor(w/60000);if(E<60)return`${E}m ago`;let X=Math.floor(E/60);if(X<24)return`${X}h ago`;return`${Math.floor(X/24)}d ago`}function oC($,w,E){return{id:$.id,snippet:rC($.content),scope:$.scope,type:$.type??"fact",importance:$.importance,age:pC($.created_at),rank:w,matchLayer:E}}function pF(){return x().$client}function oF($,w,E){let X=[],G=[];if($)X.push("m.scope = ?"),G.push($);if(w)X.push("m.type = ?"),G.push(w);if(E)X.push("m.project_id = ?"),G.push(E);return{clause:X.length?` AND ${X.join(" AND ")}`:"",params:G}}function mA($,w,E,X,G,J,A){let{clause:D,params:N}=oF(X,G,A),W=`SELECT ${L9}
|
|
439
|
+
`)};var K3=R(()=>{B3();J0={STRING_ARRAY:"string_array",STRING:"string",JSON_STRING:"json_string",RAW:"raw"},Q3={configUrl:J0.STRING,deepLinking:J0.RAW,presets:J0.STRING_ARRAY,plugins:J0.STRING_ARRAY,spec:J0.JSON_STRING,url:J0.STRING,urls:J0.JSON_STRING,layout:J0.STRING,docExpansion:J0.STRING,maxDisplayedTags:J0.RAW,operationsSorter:J0.RAW,requestInterceptor:J0.RAW,responseInterceptor:J0.RAW,persistAuthorization:J0.RAW,defaultModelsExpandDepth:J0.RAW,defaultModelExpandDepth:J0.RAW,defaultModelRendering:J0.STRING,displayRequestDuration:J0.RAW,filter:J0.RAW,showExtensions:J0.RAW,showCommonExtensions:J0.RAW,queryConfigEnabled:J0.RAW,displayOperationId:J0.RAW,tagsSorter:J0.RAW,onComplete:J0.RAW,syntaxHighlight:J0.JSON_STRING,tryItOutEnabled:J0.RAW,requestSnippetsEnabled:J0.RAW,requestSnippets:J0.JSON_STRING,oauth2RedirectUrl:J0.STRING,showMutabledRequest:J0.RAW,request:J0.JSON_STRING,supportedSubmitMethods:J0.JSON_STRING,validatorUrl:J0.STRING,withCredentials:J0.RAW,modelPropertyMacro:J0.RAW,parameterMacro:J0.RAW}});function iG($,w){var E={};for(var X in $)if(Object.prototype.hasOwnProperty.call($,X)&&w.indexOf(X)<0)E[X]=$[X];if($!=null&&typeof Object.getOwnPropertySymbols==="function"){for(var G=0,X=Object.getOwnPropertySymbols($);G<X.length;G++)if(w.indexOf(X[G])<0&&Object.prototype.propertyIsEnumerable.call($,X[G]))E[X[G]]=$[X[G]]}return E}function N0($,w){var E;return((E=$===null||$===void 0?void 0:$._def)===null||E===void 0?void 0:E.typeName)===w}function GC($){return"_def"in $}function oG($,w){let E=$.ZodType.prototype[w];$.ZodType.prototype[w]=function(...X){let G=E.apply(this,X);return G._def.openapi=this._def.openapi,G}}function P3($){if(typeof $.ZodType.prototype.openapi<"u")return;$.ZodType.prototype.openapi=function(G,J){var A,D,N,W,O,Y;let H=typeof G==="string"?J:G,L=H!==null&&H!==void 0?H:{},{param:F}=L,j=iG(L,["param"]),M=Object.assign(Object.assign({},(A=this._def.openapi)===null||A===void 0?void 0:A._internal),typeof G==="string"?{refId:G}:void 0),z=Object.assign(Object.assign(Object.assign({},(D=this._def.openapi)===null||D===void 0?void 0:D.metadata),j),((W=(N=this._def.openapi)===null||N===void 0?void 0:N.metadata)===null||W===void 0?void 0:W.param)||F?{param:Object.assign(Object.assign({},(Y=(O=this._def.openapi)===null||O===void 0?void 0:O.metadata)===null||Y===void 0?void 0:Y.param),F)}:void 0),B=new this.constructor(Object.assign(Object.assign({},this._def),{openapi:Object.assign(Object.assign({},Object.keys(M).length>0?{_internal:M}:void 0),Object.keys(z).length>0?{metadata:z}:void 0)}));if(N0(this,"ZodObject")){let Q=this.extend;B.extend=function(...k){var v,C,n,T0,f0,c0,d0;let K0=Q.apply(this,k);return K0._def.openapi={_internal:{extendedFrom:((C=(v=this._def.openapi)===null||v===void 0?void 0:v._internal)===null||C===void 0?void 0:C.refId)?{refId:(T0=(n=this._def.openapi)===null||n===void 0?void 0:n._internal)===null||T0===void 0?void 0:T0.refId,schema:this}:(c0=(f0=this._def.openapi)===null||f0===void 0?void 0:f0._internal)===null||c0===void 0?void 0:c0.extendedFrom},metadata:(d0=K0._def.openapi)===null||d0===void 0?void 0:d0.metadata},K0}}return B},oG($,"optional"),oG($,"nullable"),oG($,"default"),oG($,"transform"),oG($,"refine");let w=$.ZodObject.prototype.deepPartial;$.ZodObject.prototype.deepPartial=function(){let G=this._def.shape(),J=w.apply(this),A=J._def.shape();return Object.entries(A).forEach(([D,N])=>{var W,O;N._def.openapi=(O=(W=G[D])===null||W===void 0?void 0:W._def)===null||O===void 0?void 0:O.openapi}),J._def.openapi=void 0,J};let E=$.ZodObject.prototype.pick;$.ZodObject.prototype.pick=function(...G){let J=E.apply(this,G);return J._def.openapi=void 0,J};let X=$.ZodObject.prototype.omit;$.ZodObject.prototype.omit=function(...G){let J=X.apply(this,G);return J._def.openapi=void 0,J}}function SA($,w){if($===null||$===void 0||w===null||w===void 0)return $===w;if($===w||$.valueOf()===w.valueOf())return!0;if(Array.isArray($)){if(!Array.isArray(w))return!1;if($.length!==w.length)return!1}if(!($ instanceof Object)||!(w instanceof Object))return!1;let E=Object.keys($);return Object.keys(w).every((X)=>E.indexOf(X)!==-1)&&E.every((X)=>SA($[X],w[X]))}class q3{constructor(){this.buckets=new Map}put($){let w=this.hashCodeOf($),E=this.buckets.get(w);if(!E){this.buckets.set(w,[$]);return}if(!E.some((G)=>SA(G,$)))E.push($)}contains($){let w=this.hashCodeOf($),E=this.buckets.get(w);if(!E)return!1;return E.some((X)=>SA(X,$))}values(){return[...this.buckets.values()].flat()}stats(){let $=0,w=0,E=0;for(let G of this.buckets.values())if($+=1,w+=G.length,G.length>1)E+=1;let X=$/w;return{totalBuckets:$,collisions:E,totalValues:w,hashEffectiveness:X}}hashCodeOf($){let w=0;if(Array.isArray($)){for(let E=0;E<$.length;E++)w^=this.hashCodeOf($[E])*E;return w}if(typeof $==="string"){for(let E=0;E<$.length;E++)w^=$.charCodeAt(E)*E;return w}if(typeof $==="number")return $;if(typeof $==="object")for(let[E,X]of Object.entries($))w^=this.hashCodeOf(E)+this.hashCodeOf(X!==null&&X!==void 0?X:"");return w}}function dG($){return $===void 0}function lG($,w){let E={};return Object.entries($).forEach(([X,G])=>{E[X]=w(G)}),E}function JC($,w){let E={};return Object.entries($).forEach(([X,G])=>{if(!w.some((J)=>J===X))E[X]=G}),E}function IX($,w){let E={};return Object.entries($).forEach(([X,G])=>{if(!w(G,X))E[X]=G}),E}function V3($){return $.filter((w)=>!dG(w))}function AC($){let w=new q3;return $.forEach((E)=>w.put(E)),[...w.values()]}function S3($){return typeof $==="string"}class iN{constructor($){this.parents=$,this._definitions=[]}get definitions(){var $,w;return[...(w=($=this.parents)===null||$===void 0?void 0:$.flatMap((X)=>X.definitions))!==null&&w!==void 0?w:[],...this._definitions]}register($,w){let E=this.schemaWithRefId($,w);return this._definitions.push({type:"schema",schema:E}),E}registerParameter($,w){var E,X,G;let J=this.schemaWithRefId($,w),A=(E=J._def.openapi)===null||E===void 0?void 0:E.metadata,D=J.openapi(Object.assign(Object.assign({},A),{param:Object.assign(Object.assign({},A===null||A===void 0?void 0:A.param),{name:(G=(X=A===null||A===void 0?void 0:A.param)===null||X===void 0?void 0:X.name)!==null&&G!==void 0?G:$})}));return this._definitions.push({type:"parameter",schema:D}),D}registerPath($){this._definitions.push({type:"route",route:$})}registerWebhook($){this._definitions.push({type:"webhook",webhook:$})}registerComponent($,w,E){return this._definitions.push({type:"component",componentType:$,name:w,component:E}),{name:w,ref:{$ref:`#/components/${$}/${w}`}}}schemaWithRefId($,w){return w.openapi($)}}class aG{constructor($){this.message=$}}function tG($,w){try{return $()}catch(E){if(E instanceof sG)throw new sG(Object.assign(Object.assign({},E.data),w));throw E}}class g0{static getMetadata($){var w;let E=this.unwrapChained($),X=$._def.openapi?$._def.openapi:E._def.openapi,G=(w=$.description)!==null&&w!==void 0?w:E.description;return{_internal:X===null||X===void 0?void 0:X._internal,metadata:Object.assign({description:G},X===null||X===void 0?void 0:X.metadata)}}static getInternalMetadata($){let w=this.unwrapChained($),E=$._def.openapi?$._def.openapi:w._def.openapi;return E===null||E===void 0?void 0:E._internal}static getParamMetadata($){var w,E;let X=this.unwrapChained($),G=$._def.openapi?$._def.openapi:X._def.openapi,J=(w=$.description)!==null&&w!==void 0?w:X.description;return{_internal:G===null||G===void 0?void 0:G._internal,metadata:Object.assign(Object.assign({},G===null||G===void 0?void 0:G.metadata),{param:Object.assign({description:J},(E=G===null||G===void 0?void 0:G.metadata)===null||E===void 0?void 0:E.param)})}}static buildSchemaMetadata($){return IX(JC($,["param"]),dG)}static buildParameterMetadata($){return IX($,dG)}static applySchemaMetadata($,w){return IX(Object.assign(Object.assign({},$),this.buildSchemaMetadata(w)),dG)}static getRefId($){var w;return(w=this.getInternalMetadata($))===null||w===void 0?void 0:w.refId}static unwrapChained($){return this.unwrapUntil($)}static getDefaultValue($){let w=this.unwrapUntil($,"ZodDefault");return w===null||w===void 0?void 0:w._def.defaultValue()}static unwrapUntil($,w){if(w&&N0($,w))return $;if(N0($,"ZodOptional")||N0($,"ZodNullable")||N0($,"ZodBranded"))return this.unwrapUntil($.unwrap(),w);if(N0($,"ZodDefault")||N0($,"ZodReadonly"))return this.unwrapUntil($._def.innerType,w);if(N0($,"ZodEffects"))return this.unwrapUntil($._def.schema,w);if(N0($,"ZodPipeline"))return this.unwrapUntil($._def.in,w);return w?void 0:$}static isOptionalSchema($){return $.isOptional()}}class b3{transform($,w,E){var X,G;let J=$._def.type;return Object.assign(Object.assign({},w("array")),{items:E(J),minItems:(X=$._def.minLength)===null||X===void 0?void 0:X.value,maxItems:(G=$._def.maxLength)===null||G===void 0?void 0:G.value})}}class Z3{transform($){return Object.assign(Object.assign({},$("string")),{pattern:"^d+$"})}}class C3{transform($,w,E,X,G){let J=[...$.options.values()],A=J.map(X);if(w)return{oneOf:E(A,w)};return{oneOf:A,discriminator:this.mapDiscriminator(J,$.discriminator,G)}}mapDiscriminator($,w,E){if($.some((G)=>g0.getRefId(G)===void 0))return;let X={};return $.forEach((G)=>{var J;let A=g0.getRefId(G),D=(J=G.shape)===null||J===void 0?void 0:J[w];if(N0(D,"ZodEnum")||N0(D,"ZodNativeEnum")){Object.values(D.enum).filter(S3).forEach((O)=>{X[O]=E(A)});return}let N=D===null||D===void 0?void 0:D._def.value;if(typeof N!=="string")throw Error(`Discriminator ${w} could not be found in one of the values of a discriminated union`);X[N]=E(A)}),{propertyName:w,mapping:X}}}class _3{transform($,w){return Object.assign(Object.assign({},w("string")),{enum:$._def.values})}}class v3{transform($,w,E,X){let J={allOf:this.flattenIntersectionTypes($).map(X)};if(w)return{anyOf:E([J],w)};return J}flattenIntersectionTypes($){if(!N0($,"ZodIntersection"))return[$];let w=this.flattenIntersectionTypes($._def.left),E=this.flattenIntersectionTypes($._def.right);return[...w,...E]}}class f3{transform($,w){return Object.assign(Object.assign({},w(typeof $._def.value)),{enum:[$._def.value]})}}function DC($){let E=Object.keys($).filter((J)=>typeof $[$[J]]!=="number").map((J)=>$[J]),X=E.filter((J)=>typeof J==="number").length,G=X===0?"string":X===E.length?"numeric":"mixed";return{values:E,type:G}}class x3{transform($,w){let{type:E,values:X}=DC($._def.values);if(E==="mixed")throw new aG("Enum has mixed string and number values, please specify the OpenAPI type manually");return Object.assign(Object.assign({},w(E==="numeric"?"integer":"string")),{enum:X})}}class y3{transform($,w,E){return Object.assign(Object.assign({},w($.isInt?"integer":"number")),E($._def.checks))}}class g3{transform($,w,E,X){var G;let J=(G=g0.getInternalMetadata($))===null||G===void 0?void 0:G.extendedFrom,A=this.requiredKeysOf($),D=lG($._def.shape(),X);if(!J)return Object.assign(Object.assign(Object.assign(Object.assign({},E("object")),{properties:D,default:w}),A.length>0?{required:A}:{}),this.generateAdditionalProperties($,X));let N=J.schema;X(N);let W=this.requiredKeysOf(N),O=lG(N===null||N===void 0?void 0:N._def.shape(),X),Y=Object.fromEntries(Object.entries(D).filter(([F,j])=>{return!tN(O[F],j)})),H=A.filter((F)=>!W.includes(F)),L=Object.assign(Object.assign(Object.assign(Object.assign({},E("object")),{default:w,properties:Y}),H.length>0?{required:H}:{}),this.generateAdditionalProperties($,X));return{allOf:[{$ref:`#/components/schemas/${J.refId}`},L]}}generateAdditionalProperties($,w){let E=$._def.unknownKeys,X=$._def.catchall;if(N0(X,"ZodNever")){if(E==="strict")return{additionalProperties:!1};return{}}return{additionalProperties:w(X)}}requiredKeysOf($){return Object.entries($._def.shape()).filter(([w,E])=>!g0.isOptionalSchema(E)).map(([w,E])=>w)}}class u3{transform($,w,E){let X=$._def.valueType,G=$._def.keyType,J=E(X);if(N0(G,"ZodEnum")||N0(G,"ZodNativeEnum")){let D=Object.values(G.enum).filter(S3).reduce((N,W)=>Object.assign(Object.assign({},N),{[W]:J}),{});return Object.assign(Object.assign({},w("object")),{properties:D})}return Object.assign(Object.assign({},w("object")),{additionalProperties:J})}}class h3{transform($,w){var E,X,G;let J=this.getZodStringCheck($,"regex"),A=(E=this.getZodStringCheck($,"length"))===null||E===void 0?void 0:E.value,D=Number.isFinite($.minLength)?(X=$.minLength)!==null&&X!==void 0?X:void 0:void 0,N=Number.isFinite($.maxLength)?(G=$.maxLength)!==null&&G!==void 0?G:void 0:void 0;return Object.assign(Object.assign({},w("string")),{minLength:A!==null&&A!==void 0?A:D,maxLength:A!==null&&A!==void 0?A:N,format:this.mapStringFormat($),pattern:J===null||J===void 0?void 0:J.regex.source})}mapStringFormat($){if($.isUUID)return"uuid";if($.isEmail)return"email";if($.isURL)return"uri";if($.isDate)return"date";if($.isDatetime)return"date-time";if($.isCUID)return"cuid";if($.isCUID2)return"cuid2";if($.isULID)return"ulid";if($.isIP)return"ip";if($.isEmoji)return"emoji";return}getZodStringCheck($,w){return $._def.checks.find((E)=>{return E.kind===w})}}class c3{constructor($){this.versionSpecifics=$}transform($,w,E){let{items:X}=$._def,G=X.map(E);return Object.assign(Object.assign({},w("array")),this.versionSpecifics.mapTupleItems(G))}}class n3{transform($,w,E){let G=this.flattenUnionTypes($).map((J)=>{let A=this.unwrapNullable(J);return E(A)});return{anyOf:w(G)}}flattenUnionTypes($){if(!N0($,"ZodUnion"))return[$];return $._def.options.flatMap((E)=>this.flattenUnionTypes(E))}unwrapNullable($){if(N0($,"ZodNullable"))return this.unwrapNullable($.unwrap());return $}}class m3{constructor($){this.versionSpecifics=$,this.objectTransformer=new g3,this.stringTransformer=new h3,this.numberTransformer=new y3,this.bigIntTransformer=new Z3,this.literalTransformer=new f3,this.enumTransformer=new _3,this.nativeEnumTransformer=new x3,this.arrayTransformer=new b3,this.unionTransformer=new n3,this.discriminatedUnionTransformer=new C3,this.intersectionTransformer=new v3,this.recordTransformer=new u3,this.tupleTransformer=new c3($)}transform($,w,E,X,G){if(N0($,"ZodNull"))return this.versionSpecifics.nullType;if(N0($,"ZodUnknown")||N0($,"ZodAny"))return this.versionSpecifics.mapNullableType(void 0,w);if(N0($,"ZodObject"))return this.objectTransformer.transform($,G,(A)=>this.versionSpecifics.mapNullableType(A,w),E);let J=this.transformSchemaWithoutDefault($,w,E,X);return Object.assign(Object.assign({},J),{default:G})}transformSchemaWithoutDefault($,w,E,X){if(N0($,"ZodUnknown")||N0($,"ZodAny"))return this.versionSpecifics.mapNullableType(void 0,w);if(N0($,"ZodString"))return this.stringTransformer.transform($,(J)=>this.versionSpecifics.mapNullableType(J,w));if(N0($,"ZodNumber"))return this.numberTransformer.transform($,(J)=>this.versionSpecifics.mapNullableType(J,w),(J)=>this.versionSpecifics.getNumberChecks(J));if(N0($,"ZodBigInt"))return this.bigIntTransformer.transform((J)=>this.versionSpecifics.mapNullableType(J,w));if(N0($,"ZodBoolean"))return this.versionSpecifics.mapNullableType("boolean",w);if(N0($,"ZodLiteral"))return this.literalTransformer.transform($,(J)=>this.versionSpecifics.mapNullableType(J,w));if(N0($,"ZodEnum"))return this.enumTransformer.transform($,(J)=>this.versionSpecifics.mapNullableType(J,w));if(N0($,"ZodNativeEnum"))return this.nativeEnumTransformer.transform($,(J)=>this.versionSpecifics.mapNullableType(J,w));if(N0($,"ZodArray"))return this.arrayTransformer.transform($,(J)=>this.versionSpecifics.mapNullableType(J,w),E);if(N0($,"ZodTuple"))return this.tupleTransformer.transform($,(J)=>this.versionSpecifics.mapNullableType(J,w),E);if(N0($,"ZodUnion"))return this.unionTransformer.transform($,(J)=>this.versionSpecifics.mapNullableOfArray(J,w),E);if(N0($,"ZodDiscriminatedUnion"))return this.discriminatedUnionTransformer.transform($,w,(J)=>this.versionSpecifics.mapNullableOfArray(J,w),E,X);if(N0($,"ZodIntersection"))return this.intersectionTransformer.transform($,w,(J)=>this.versionSpecifics.mapNullableOfArray(J,w),E);if(N0($,"ZodRecord"))return this.recordTransformer.transform($,(J)=>this.versionSpecifics.mapNullableType(J,w),E);if(N0($,"ZodDate"))return this.versionSpecifics.mapNullableType("string",w);let G=g0.getRefId($);throw new k3({currentSchema:$._def,schemaName:G})}}class dN{constructor($,w){this.definitions=$,this.versionSpecifics=w,this.schemaRefs={},this.paramRefs={},this.pathRefs={},this.rawComponents=[],this.openApiTransformer=new m3(w),this.sortDefinitions()}generateDocumentData(){return this.definitions.forEach(($)=>this.generateSingle($)),{components:this.buildComponents(),paths:this.pathRefs}}generateComponents(){return this.definitions.forEach(($)=>this.generateSingle($)),{components:this.buildComponents()}}buildComponents(){var $,w;let E={};return this.rawComponents.forEach(({componentType:X,name:G,component:J})=>{var A;(A=E[X])!==null&&A!==void 0||(E[X]={}),E[X][G]=J}),Object.assign(Object.assign({},E),{schemas:Object.assign(Object.assign({},($=E.schemas)!==null&&$!==void 0?$:{}),this.schemaRefs),parameters:Object.assign(Object.assign({},(w=E.parameters)!==null&&w!==void 0?w:{}),this.paramRefs)})}sortDefinitions(){let $=["schema","parameter","component","route"];this.definitions.sort((w,E)=>{if(!("type"in w)){if(!("type"in E))return 0;return-1}if(!("type"in E))return 1;let X=$.findIndex((J)=>J===w.type),G=$.findIndex((J)=>J===E.type);return X-G})}generateSingle($){if(!("type"in $)){this.generateSchemaWithRef($);return}switch($.type){case"parameter":this.generateParameterDefinition($.schema);return;case"schema":this.generateSchemaWithRef($.schema);return;case"route":this.generateSingleRoute($.route);return;case"component":this.rawComponents.push($);return}}generateParameterDefinition($){let w=g0.getRefId($),E=this.generateParameter($);if(w)this.paramRefs[w]=E;return E}getParameterRef($,w){var E,X,G,J,A;let D=(E=$===null||$===void 0?void 0:$.metadata)===null||E===void 0?void 0:E.param,N=((X=$===null||$===void 0?void 0:$._internal)===null||X===void 0?void 0:X.refId)?this.paramRefs[(G=$._internal)===null||G===void 0?void 0:G.refId]:void 0;if(!((J=$===null||$===void 0?void 0:$._internal)===null||J===void 0?void 0:J.refId)||!N)return;if(D&&N.in!==D.in||(w===null||w===void 0?void 0:w.in)&&N.in!==w.in)throw new QX(`Conflicting location for parameter ${N.name}`,{key:"in",values:V3([N.in,w===null||w===void 0?void 0:w.in,D===null||D===void 0?void 0:D.in])});if(D&&N.name!==D.name||(w===null||w===void 0?void 0:w.name)&&N.name!==(w===null||w===void 0?void 0:w.name))throw new QX("Conflicting names for parameter",{key:"name",values:V3([N.name,w===null||w===void 0?void 0:w.name,D===null||D===void 0?void 0:D.name])});return{$ref:`#/components/parameters/${(A=$._internal)===null||A===void 0?void 0:A.refId}`}}generateInlineParameters($,w){var E;let X=g0.getMetadata($),G=(E=X===null||X===void 0?void 0:X.metadata)===null||E===void 0?void 0:E.param,J=this.getParameterRef(X,{in:w});if(J)return[J];if(N0($,"ZodObject")){let A=$._def.shape();return Object.entries(A).map(([N,W])=>{var O,Y;let H=g0.getMetadata(W),L=this.getParameterRef(H,{in:w,name:N});if(L)return L;let F=(O=H===null||H===void 0?void 0:H.metadata)===null||O===void 0?void 0:O.param;if((F===null||F===void 0?void 0:F.name)&&F.name!==N)throw new QX("Conflicting names for parameter",{key:"name",values:[N,F.name]});if((F===null||F===void 0?void 0:F.in)&&F.in!==w)throw new QX(`Conflicting location for parameter ${(Y=F.name)!==null&&Y!==void 0?Y:N}`,{key:"in",values:[w,F.in]});return this.generateParameter(W.openapi({param:{name:N,in:w}}))})}if((G===null||G===void 0?void 0:G.in)&&G.in!==w)throw new QX(`Conflicting location for parameter ${G.name}`,{key:"in",values:[w,G.in]});return[this.generateParameter($.openapi({param:{in:w}}))]}generateSimpleParameter($){var w;let E=g0.getParamMetadata($),X=(w=E===null||E===void 0?void 0:E.metadata)===null||w===void 0?void 0:w.param,G=!g0.isOptionalSchema($)&&!$.isNullable(),J=this.generateSchemaWithRef($);return Object.assign({schema:J,required:G},X?g0.buildParameterMetadata(X):{})}generateParameter($){var w;let E=g0.getMetadata($),X=(w=E===null||E===void 0?void 0:E.metadata)===null||w===void 0?void 0:w.param,G=X===null||X===void 0?void 0:X.name,J=X===null||X===void 0?void 0:X.in;if(!G)throw new sG({missingField:"name"});if(!J)throw new sG({missingField:"in",paramName:G});let A=this.generateSimpleParameter($);return Object.assign(Object.assign({},A),{in:J,name:G})}generateSchemaWithMetadata($){var w;let E=g0.unwrapChained($),X=g0.getMetadata($),G=g0.getDefaultValue($),J=((w=X===null||X===void 0?void 0:X.metadata)===null||w===void 0?void 0:w.type)?{type:X===null||X===void 0?void 0:X.metadata.type}:this.toOpenAPISchema(E,$.isNullable(),G);return(X===null||X===void 0?void 0:X.metadata)?g0.applySchemaMetadata(J,X.metadata):IX(J,dG)}constructReferencedOpenAPISchema($){var w;let E=g0.getMetadata($),X=g0.unwrapChained($),G=g0.getDefaultValue($),J=$.isNullable();if((w=E===null||E===void 0?void 0:E.metadata)===null||w===void 0?void 0:w.type)return this.versionSpecifics.mapNullableType(E.metadata.type,J);return this.toOpenAPISchema(X,J,G)}generateSimpleSchema($){var w;let E=g0.getMetadata($),X=g0.getRefId($);if(!X||!this.schemaRefs[X])return this.generateSchemaWithMetadata($);let G=this.schemaRefs[X],J={$ref:this.generateSchemaRef(X)},A=IX(g0.buildSchemaMetadata((w=E===null||E===void 0?void 0:E.metadata)!==null&&w!==void 0?w:{}),(W,O)=>W===void 0||tN(W,G[O]));if(A.type)return{allOf:[J,A]};let D=IX(this.constructReferencedOpenAPISchema($),(W,O)=>W===void 0||tN(W,G[O])),N=g0.applySchemaMetadata(D,A);if(Object.keys(N).length>0)return{allOf:[J,N]};return J}generateSchemaWithRef($){let w=g0.getRefId($),E=this.generateSimpleSchema($);if(w&&this.schemaRefs[w]===void 0)return this.schemaRefs[w]=E,{$ref:this.generateSchemaRef(w)};return E}generateSchemaRef($){return`#/components/schemas/${$}`}getRequestBody($){if(!$)return;let{content:w}=$,E=iG($,["content"]),X=this.getBodyContent(w);return Object.assign(Object.assign({},E),{content:X})}getParameters($){if(!$)return[];let{headers:w}=$,E=this.cleanParameter($.query),X=this.cleanParameter($.params),G=this.cleanParameter($.cookies),J=tG(()=>E?this.generateInlineParameters(E,"query"):[],{location:"query"}),A=tG(()=>X?this.generateInlineParameters(X,"path"):[],{location:"path"}),D=tG(()=>G?this.generateInlineParameters(G,"cookie"):[],{location:"cookie"}),N=tG(()=>{if(Array.isArray(w))return w.flatMap((O)=>this.generateInlineParameters(O,"header"));let W=this.cleanParameter(w);return W?this.generateInlineParameters(W,"header"):[]},{location:"header"});return[...A,...J,...N,...D]}cleanParameter($){if(!$)return;return N0($,"ZodEffects")?this.cleanParameter($._def.schema):$}generatePath($){let{method:w,path:E,request:X,responses:G}=$,J=iG($,["method","path","request","responses"]),A=lG(G,(O)=>{return this.getResponse(O)}),D=tG(()=>this.getParameters(X),{route:`${w} ${E}`}),N=this.getRequestBody(X===null||X===void 0?void 0:X.body);return{[w]:Object.assign(Object.assign(Object.assign(Object.assign({},J),D.length>0?{parameters:[...J.parameters||[],...D]}:{}),N?{requestBody:N}:{}),{responses:A})}}generateSingleRoute($){let w=this.generatePath($);return this.pathRefs[$.path]=Object.assign(Object.assign({},this.pathRefs[$.path]),w),w}getResponse($){if(this.isReferenceObject($))return $;let{content:w,headers:E}=$,X=iG($,["content","headers"]),G=w?{content:this.getBodyContent(w)}:{};if(!E)return Object.assign(Object.assign({},X),G);let J=N0(E,"ZodObject")?this.getResponseHeaders(E):E;return Object.assign(Object.assign(Object.assign({},X),{headers:J}),G)}isReferenceObject($){return"$ref"in $}getResponseHeaders($){let w=$._def.shape();return lG(w,(X)=>this.generateSimpleParameter(X))}getBodyContent($){return lG($,(w)=>{if(!w||!GC(w.schema))return w;let{schema:E}=w,X=iG(w,["schema"]),G=this.generateSchemaWithRef(E);return Object.assign({schema:G},X)})}toOpenAPISchema($,w,E){return this.openApiTransformer.transform($,w,(X)=>this.generateSchemaWithRef(X),(X)=>this.generateSchemaRef(X),E)}}class r3{get nullType(){return{nullable:!0}}mapNullableOfArray($,w){if(w)return[...$,this.nullType];return $}mapNullableType($,w){return Object.assign(Object.assign({},$?{type:$}:void 0),w?this.nullType:void 0)}mapTupleItems($){let w=AC($);return{items:w.length===1?w[0]:{anyOf:w},minItems:$.length,maxItems:$.length}}getNumberChecks($){return Object.assign({},...$.map((w)=>{switch(w.kind){case"min":return w.inclusive?{minimum:Number(w.value)}:{minimum:Number(w.value),exclusiveMinimum:!0};case"max":return w.inclusive?{maximum:Number(w.value)}:{maximum:Number(w.value),exclusiveMaximum:!0};default:return{}}}))}}class lN{constructor($){let w=new r3;this.generator=new dN($,w)}generateDocument($){let w=this.generator.generateDocumentData();return Object.assign(Object.assign({},$),w)}generateComponents(){return this.generator.generateComponents()}}class p3{get nullType(){return{type:"null"}}mapNullableOfArray($,w){if(w)return[...$,this.nullType];return $}mapNullableType($,w){if(!$)return{};if(w)return{type:Array.isArray($)?[...$,"null"]:[$,"null"]};return{type:$}}mapTupleItems($){return{prefixItems:$}}getNumberChecks($){return Object.assign({},...$.map((w)=>{switch(w.kind){case"min":return w.inclusive?{minimum:Number(w.value)}:{exclusiveMinimum:Number(w.value)};case"max":return w.inclusive?{maximum:Number(w.value)}:{exclusiveMaximum:Number(w.value)};default:return{}}}))}}function NC($){return"type"in $&&$.type==="webhook"}class sN{constructor($){this.definitions=$,this.webhookRefs={};let w=new p3;this.generator=new dN(this.definitions,w)}generateDocument($){let w=this.generator.generateDocumentData();return this.definitions.filter(NC).forEach((E)=>this.generateSingleWebhook(E.webhook)),Object.assign(Object.assign(Object.assign({},$),w),{webhooks:this.webhookRefs})}generateComponents(){return this.generator.generateComponents()}generateSingleWebhook($){let w=this.generator.generatePath($);return this.webhookRefs[$.path]=Object.assign(Object.assign({},this.webhookRefs[$.path]),w),w}}var tN,QX,sG,k3;var o3=R(()=>{tN=SA;QX=class QX extends aG{constructor($,w){super($);this.data=w}};sG=class sG extends aG{constructor($){super(`Missing parameter data, please specify \`${$.missingField}\` and other OpenAPI parameter props using the \`param\` field of \`ZodSchema.openapi\``);this.data=$}};k3=class k3 extends aG{constructor($){super("Unknown zod object type, please specify `type` and other OpenAPI props using `ZodSchema.openapi`.");this.data=$}}});var eN=($)=>{let w=$.split("/");if(w[0]==="")w.shift();return w},t3=($)=>{let{groups:w,path:E}=WC($),X=eN(E);return OC(X,w)},WC=($)=>{let w=[];return $=$.replace(/\{[^}]+\}/g,(E,X)=>{let G=`@${X}`;return w.push([G,E]),G}),{groups:w,path:$}},OC=($,w)=>{for(let E=w.length-1;E>=0;E--){let[X]=w[E];for(let G=$.length-1;G>=0;G--)if($[G].includes(X)){$[G]=$[G].replace(X,w[E][1]);break}}return $},kA,i3=($,w)=>{if($==="*")return"*";let E=$.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(E){let X=`${$}#${w}`;if(!kA[X])if(E[2])kA[X]=w&&w[0]!==":"&&w[0]!=="*"?[X,E[1],new RegExp(`^${E[2]}(?=/${w})`)]:[$,E[1],new RegExp(`^${E[2]}$`)];else kA[X]=[$,E[1],!0];return kA[X]}return null},KX=($,w)=>{try{return w($)}catch{return $.replace(/(?:%[0-9A-Fa-f]{2})+/g,(E)=>{try{return w(E)}catch{return E}})}},UC=($)=>KX($,decodeURI),$9=($)=>{let w=$.url,E=w.indexOf("/",w.indexOf(":")+4),X=E;for(;X<w.length;X++){let G=w.charCodeAt(X);if(G===37){let J=w.indexOf("?",X),A=w.indexOf("#",X),D=J===-1?A===-1?void 0:A:A===-1?J:Math.min(J,A),N=w.slice(E,D);return UC(N.includes("%25")?N.replace(/%25/g,"%2525"):N)}else if(G===63||G===35)break}return w.slice(E,X)},d3=($)=>{let w=$9($);return w.length>1&&w.at(-1)==="/"?w.slice(0,-1):w},f1=($,w,...E)=>{if(E.length)w=f1(w,...E);return`${$?.[0]==="/"?"":"/"}${$}${w==="/"?"":`${$?.at(-1)==="/"?"":"/"}${w?.[0]==="/"?w.slice(1):w}`}`},bA=($)=>{if($.charCodeAt($.length-1)!==63||!$.includes(":"))return null;let w=$.split("/"),E=[],X="";return w.forEach((G)=>{if(G!==""&&!/\:/.test(G))X+="/"+G;else if(/\:/.test(G))if(/\?/.test(G)){if(E.length===0&&X==="")E.push("/");else E.push(X);let J=G.replace("?","");X+="/"+J,E.push(X)}else X+="/"+G}),E.filter((G,J,A)=>A.indexOf(G)===J)},aN=($)=>{if(!/[%+]/.test($))return $;if($.indexOf("+")!==-1)$=$.replace(/\+/g," ");return $.indexOf("%")!==-1?KX($,eG):$},l3=($,w,E)=>{let X;if(!E&&w&&!/[%+]/.test(w)){let A=$.indexOf("?",8);if(A===-1)return;if(!$.startsWith(w,A+1))A=$.indexOf(`&${w}`,A+1);while(A!==-1){let D=$.charCodeAt(A+w.length+1);if(D===61){let N=A+w.length+2,W=$.indexOf("&",N);return aN($.slice(N,W===-1?void 0:W))}else if(D==38||isNaN(D))return"";A=$.indexOf(`&${w}`,A+1)}if(X=/[%+]/.test($),!X)return}let G={};X??=/[%+]/.test($);let J=$.indexOf("?",8);while(J!==-1){let A=$.indexOf("&",J+1),D=$.indexOf("=",J);if(D>A&&A!==-1)D=-1;let N=$.slice(J+1,D===-1?A===-1?void 0:A:D);if(X)N=aN(N);if(J=A,N==="")continue;let W;if(D===-1)W="";else if(W=$.slice(D+1,A===-1?void 0:A),X)W=aN(W);if(E){if(!(G[N]&&Array.isArray(G[N])))G[N]=[];G[N].push(W)}else G[N]??=W}return w?G[w]:G},s3,a3=($,w)=>{return l3($,w,!0)},eG;var pw=R(()=>{kA={},s3=l3,eG=decodeURIComponent});var YC,HC,w9=($,w)=>{if(w&&$.indexOf(w)===-1)return{};let E=$.trim().split(";"),X={};for(let G of E){G=G.trim();let J=G.indexOf("=");if(J===-1)continue;let A=G.substring(0,J).trim();if(w&&w!==A||!YC.test(A))continue;let D=G.substring(J+1).trim();if(D.startsWith('"')&&D.endsWith('"'))D=D.slice(1,-1);if(HC.test(D)){if(X[A]=D.indexOf("%")!==-1?KX(D,eG):D,w)break}}return X};var e3=R(()=>{pw();YC=/^[\w!#$%&'*.^`|~+-]+$/,HC=/^[ !#-:<-[\]-~]*$/});var $F=($,w,E)=>{let X=$.req.raw.headers.get("Cookie");if(typeof w==="string"){if(!X)return;let J=w;if(E==="secure")J="__Secure-"+w;else if(E==="host")J="__Host-"+w;return w9(X,J)[J]}if(!X)return{};return w9(X)};var wF=R(()=>{e3()});var ZA;var E9=R(()=>{ZA=class extends Error{res;status;constructor($=500,w){super(w?.message,{cause:w?.cause});this.res=w?.res,this.status=$}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}}});var EF=()=>{};var XF=($,w)=>{return new Response($,{headers:{"Content-Type":w}}).formData()};var GF=R(()=>{EF()});var LC,FC,jC,X9=($,w)=>{return async(E,X)=>{let G={},J=E.req.header("Content-Type");switch($){case"json":if(!J||!LC.test(J))break;try{G=await E.req.json()}catch{throw new ZA(400,{message:"Malformed JSON in request body"})}break;case"form":{if(!J||!(FC.test(J)||jC.test(J)))break;let D;if(E.req.bodyCache.formData)D=await E.req.bodyCache.formData;else try{let W=await E.req.arrayBuffer();D=await XF(W,J),E.req.bodyCache.formData=D}catch(W){let O="Malformed FormData request.";throw O+=W instanceof Error?` ${W.message}`:` ${String(W)}`,new ZA(400,{message:O})}let N=Object.create(null);D.forEach((W,O)=>{if(O.endsWith("[]"))(N[O]??=[]).push(W);else if(Array.isArray(N[O]))N[O].push(W);else if(Object.hasOwn(N,O))N[O]=[N[O],W];else N[O]=W}),G=N;break}case"query":G=Object.fromEntries(Object.entries(E.req.queries()).map(([D,N])=>{return N.length===1?[D,N[0]]:[D,N]}));break;case"param":G=E.req.param();break;case"header":G=E.req.header();break;case"cookie":G=$F(E);break}let A=await w(G,E);if(A instanceof Response)return A;return E.req.addValidatedData($,A),await X()}};var JF=R(()=>{wF();E9();GF();LC=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,FC=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,jC=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/});var AF=R(()=>{JF()});function MC($,w,E,X){return X9($,async(G,J)=>{let A=G;if($==="header"&&"_def"in w||$==="header"&&"_zod"in w){let N=Object.keys("in"in w?w.in.shape:w.shape),W=Object.fromEntries(N.map((O)=>[O.toLowerCase(),O]));A=Object.fromEntries(Object.entries(G).map(([O,Y])=>[W[O]||O,Y]))}let D=X&&X.validationFunction?await X.validationFunction(w,A):await w.safeParseAsync(A);if(E){let N=await E({data:A,...D,target:$},J);if(N){if(N instanceof Response)return N;if("response"in N)return N.response}}if(!D.success)return J.json(D,400);return D.data})}var BE;var DF=R(()=>{AF();BE=MC});var G9=($,w,E)=>{return(X,G)=>{let J=-1;return A(0);async function A(D){if(D<=J)throw Error("next() called multiple times");J=D;let N,W=!1,O;if($[D])O=$[D][0][0],X.req.routeIndex=D;else O=D===$.length&&G||void 0;if(O)try{N=await O(X,()=>A(D+1))}catch(Y){if(Y instanceof Error&&w)X.error=Y,N=await w(Y,X),W=!0;else throw Y}else if(X.finalized===!1&&E)N=await E(X);if(N&&(X.finalized===!1||W))X.res=N;return X}}};var NF=()=>{};var WF;var OF=R(()=>{WF=Symbol()});async function RC($,w){let E=await $.formData();if(E)return zC(E,w);return{}}function zC($,w){let E=Object.create(null);if($.forEach((X,G)=>{if(!(w.all||G.endsWith("[]")))E[G]=X;else TC(E,G,X)}),w.dot)Object.entries(E).forEach(([X,G])=>{if(X.includes("."))BC(E,X,G),delete E[X]});return E}var UF=async($,w=Object.create(null))=>{let{all:E=!1,dot:X=!1}=w,J=($ instanceof CA?$.raw.headers:$.headers).get("Content-Type");if(J?.startsWith("multipart/form-data")||J?.startsWith("application/x-www-form-urlencoded"))return RC($,{all:E,dot:X});return{}},TC=($,w,E)=>{if($[w]!==void 0)if(Array.isArray($[w]))$[w].push(E);else $[w]=[$[w],E];else if(!w.endsWith("[]"))$[w]=E;else $[w]=[E]},BC=($,w,E)=>{if(/(?:^|\.)__proto__\./.test(w))return;let X=$,G=w.split(".");G.forEach((J,A)=>{if(A===G.length-1)X[J]=E;else{if(!X[J]||typeof X[J]!=="object"||Array.isArray(X[J])||X[J]instanceof File)X[J]=Object.create(null);X=X[J]}})};var YF=R(()=>{J9()});var HF=($)=>KX($,eG),CA;var J9=R(()=>{E9();OF();YF();pw();CA=class{raw;#$;#w;routeIndex=0;path;bodyCache={};constructor($,w="/",E=[[]]){this.raw=$,this.path=w,this.#w=E,this.#$={}}param($){return $?this.#E($):this.#J()}#E($){let w=this.#w[0][this.routeIndex][1][$],E=this.#G(w);return E&&/\%/.test(E)?HF(E):E}#J(){let $={},w=Object.keys(this.#w[0][this.routeIndex][1]);for(let E of w){let X=this.#G(this.#w[0][this.routeIndex][1][E]);if(X!==void 0)$[E]=/\%/.test(X)?HF(X):X}return $}#G($){return this.#w[1]?this.#w[1][$]:$}query($){return s3(this.url,$)}queries($){return a3(this.url,$)}header($){if($)return this.raw.headers.get($)??void 0;let w={};return this.raw.headers.forEach((E,X)=>{w[X]=E}),w}async parseBody($){return this.bodyCache.parsedBody??=await UF(this,$)}#X=($)=>{let{bodyCache:w,raw:E}=this,X=w[$];if(X)return X;let G=Object.keys(w)[0];if(G)return w[G].then((J)=>{if(G==="json")J=JSON.stringify(J);return new Response(J)[$]()});return w[$]=E[$]()};json(){return this.#X("text").then(($)=>JSON.parse($))}text(){return this.#X("text")}arrayBuffer(){return this.#X("arrayBuffer")}blob(){return this.#X("blob")}formData(){return this.#X("formData")}addValidatedData($,w){this.#$[$]=w}valid($){return this.#$[$]}get url(){return this.raw.url}get method(){return this.raw.method}get[WF](){return this.#w}get matchedRoutes(){return this.#w[0].map(([[,$]])=>$)}get routePath(){return this.#w[0].map(([[,$]])=>$)[this.routeIndex].path}}});var QC="text/plain; charset=UTF-8",A9=($,w)=>{return{"Content-Type":$,...w}},$6=($,w)=>new Response($,w),LF=class{#$;#w;env={};#E;finalized=!1;error;#J;#G;#X;#O;#N;#W;#D;#U;#Y;constructor($,w){if(this.#$=$,w)this.#G=w.executionCtx,this.env=w.env,this.#W=w.notFoundHandler,this.#Y=w.path,this.#U=w.matchResult}get req(){return this.#w??=new CA(this.#$,this.#Y,this.#U),this.#w}get event(){if(this.#G&&"respondWith"in this.#G)return this.#G;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#G)return this.#G;else throw Error("This context has no ExecutionContext")}get res(){return this.#X||=$6(null,{headers:this.#D??=new Headers})}set res($){if(this.#X&&$){$=$6($.body,$);for(let[w,E]of this.#X.headers.entries()){if(w==="content-type")continue;if(w==="set-cookie"){let X=this.#X.headers.getSetCookie();$.headers.delete("set-cookie");for(let G of X)$.headers.append("set-cookie",G)}else $.headers.set(w,E)}}this.#X=$,this.finalized=!0}render=(...$)=>{return this.#N??=(w)=>this.html(w),this.#N(...$)};setLayout=($)=>this.#O=$;getLayout=()=>this.#O;setRenderer=($)=>{this.#N=$};header=($,w,E)=>{if(this.finalized)this.#X=$6(this.#X.body,this.#X);let X=this.#X?this.#X.headers:this.#D??=new Headers;if(w===void 0)X.delete($);else if(E?.append)X.append($,w);else X.set($,w)};status=($)=>{this.#J=$};set=($,w)=>{this.#E??=new Map,this.#E.set($,w)};get=($)=>{return this.#E?this.#E.get($):void 0};get var(){if(!this.#E)return{};return Object.fromEntries(this.#E)}#A($,w,E){let X=this.#X?new Headers(this.#X.headers):this.#D??new Headers;if(typeof w==="object"&&"headers"in w){let J=w.headers instanceof Headers?w.headers:new Headers(w.headers);for(let[A,D]of J)if(A.toLowerCase()==="set-cookie")X.append(A,D);else X.set(A,D)}if(E)for(let[J,A]of Object.entries(E))if(typeof A==="string")X.set(J,A);else{X.delete(J);for(let D of A)X.append(J,D)}let G=typeof w==="number"?w:w?.status??this.#J;return $6($,{status:G,headers:X})}newResponse=(...$)=>this.#A(...$);body=($,w,E)=>this.#A($,w,E);text=($,w,E)=>{return!this.#D&&!this.#J&&!w&&!E&&!this.finalized?new Response($):this.#A($,w,A9(QC,E))};json=($,w,E)=>{return this.#A(JSON.stringify($),w,A9("application/json",E))};html=($,w,E)=>{let X=(G)=>this.#A(G,w,A9("text/html; charset=UTF-8",E));return typeof $==="object"?rN($,mN.Stringify,!1,{}).then(X):X($)};redirect=($,w)=>{let E=String($);return this.header("Location",!/[^\x00-\xFF]/.test(E)?E:encodeURI(E)),this.newResponse(null,w??302)};notFound=()=>{return this.#W??=()=>$6(),this.#W(this)}};var FF=R(()=>{J9();pN()});var k0="ALL",jF="all",MF,_A="Can not add a route since the matcher is already built.",vA;var QE=R(()=>{MF=["get","post","put","delete","options","patch"],vA=class extends Error{}});var RF="__COMPOSED_HANDLER";var zF=()=>{};var IC=($)=>{return $.text("404 Not Found",404)},TF=($,w)=>{if("getResponse"in $){let E=$.getResponse();return w.newResponse(E.body,E)}return console.error($),w.text("Internal Server Error",500)},BF=class ${get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#$="/";routes=[];constructor(w={}){[...MF,jF].forEach((J)=>{this[J]=(A,...D)=>{if(typeof A==="string")this.#$=A;else this.#J(J,this.#$,A);return D.forEach((N)=>{this.#J(J,this.#$,N)}),this}}),this.on=(J,A,...D)=>{for(let N of[A].flat()){this.#$=N;for(let W of[J].flat())D.map((O)=>{this.#J(W.toUpperCase(),this.#$,O)})}return this},this.use=(J,...A)=>{if(typeof J==="string")this.#$=J;else this.#$="*",A.unshift(J);return A.forEach((D)=>{this.#J(k0,this.#$,D)}),this};let{strict:X,...G}=w;Object.assign(this,G),this.getPath=X??!0?w.getPath??$9:d3}#w(){let w=new $({router:this.router,getPath:this.getPath});return w.errorHandler=this.errorHandler,w.#E=this.#E,w.routes=this.routes,w}#E=IC;errorHandler=TF;route(w,E){let X=this.basePath(w);return E.routes.map((G)=>{let J;if(E.errorHandler===TF)J=G.handler;else J=async(A,D)=>(await G9([],E.errorHandler)(A,()=>G.handler(A,D))).res,J[RF]=G.handler;X.#J(G.method,G.path,J)}),this}basePath(w){let E=this.#w();return E._basePath=f1(this._basePath,w),E}onError=(w)=>{return this.errorHandler=w,this};notFound=(w)=>{return this.#E=w,this};mount(w,E,X){let G,J;if(X)if(typeof X==="function")J=X;else if(J=X.optionHandler,X.replaceRequest===!1)G=(N)=>N;else G=X.replaceRequest;let A=J?(N)=>{let W=J(N);return Array.isArray(W)?W:[W]}:(N)=>{let W=void 0;try{W=N.executionCtx}catch{}return[N.env,W]};G||=(()=>{let N=f1(this._basePath,w),W=N==="/"?0:N.length;return(O)=>{let Y=new URL(O.url);return Y.pathname=Y.pathname.slice(W)||"/",new Request(Y,O)}})();let D=async(N,W)=>{let O=await E(G(N.req.raw),...A(N));if(O)return O;await W()};return this.#J(k0,f1(w,"*"),D),this}#J(w,E,X){w=w.toUpperCase(),E=f1(this._basePath,E);let G={basePath:this._basePath,path:E,method:w,handler:X};this.router.add(w,E,[X,G]),this.routes.push(G)}#G(w,E){if(w instanceof Error)return this.errorHandler(w,E);throw w}#X(w,E,X,G){if(G==="HEAD")return(async()=>new Response(null,await this.#X(w,E,X,"GET")))();let J=this.getPath(w,{env:X}),A=this.router.match(G,J),D=new LF(w,{path:J,matchResult:A,env:X,executionCtx:E,notFoundHandler:this.#E});if(A[0].length===1){let W;try{W=A[0][0][0][0](D,async()=>{D.res=await this.#E(D)})}catch(O){return this.#G(O,D)}return W instanceof Promise?W.then((O)=>O||(D.finalized?D.res:this.#E(D))).catch((O)=>this.#G(O,D)):W??this.#E(D)}let N=G9(A[0],this.errorHandler,this.#E);return(async()=>{try{let W=await N(D);if(!W.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return W.res}catch(W){return this.#G(W,D)}})()}fetch=(w,...E)=>{return this.#X(w,E[1],E[0],w.method)};request=(w,E,X,G)=>{if(w instanceof Request)return this.fetch(E?new Request(w,E):w,X,G);return w=w.toString(),this.fetch(new Request(/^https?:\/\//.test(w)?w:`http://localhost${f1("/",w)}`,E),X,G)};fire=()=>{addEventListener("fetch",(w)=>{w.respondWith(this.#X(w.request,w,void 0,w.request.method))})}};var QF=R(()=>{NF();FF();QE();zF();pw()});function fA($,w){let E=this.buildAllMatchers(),X=(G,J)=>{let A=E[G]||E[k0],D=A[2][J];if(D)return D;let N=J.match(A[0]);if(!N)return[[],w6];let W=N.indexOf("",1);return[A[1][W],N]};return this.match=X,X($,w)}var w6;var D9=R(()=>{QE();w6=[]});function VC($,w){if($.length===1)return w.length===1?$<w?-1:1:-1;if(w.length===1)return 1;if($===E6||$===X6)return 1;else if(w===E6||w===X6)return-1;if($===xA)return 1;else if(w===xA)return-1;return $.length===w.length?$<w?-1:1:w.length-$.length}var xA="[^/]+",E6=".*",X6="(?:|/.*)",IE,KC,IF=class ${#$;#w;#E=Object.create(null);insert(w,E,X,G,J){if(w.length===0){if(this.#$!==void 0)throw IE;if(J)return;this.#$=E;return}let[A,...D]=w,N=A==="*"?D.length===0?["","",E6]:["","",xA]:A==="/*"?["","",X6]:A.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),W;if(N){let O=N[1],Y=N[2]||xA;if(O&&N[2]){if(Y===".*")throw IE;if(Y=Y.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(Y))throw IE}if(W=this.#E[Y],!W){if(Object.keys(this.#E).some((H)=>H!==E6&&H!==X6))throw IE;if(J)return;if(W=this.#E[Y]=new $,O!=="")W.#w=G.varIndex++}if(!J&&O!=="")X.push([O,W.#w])}else if(W=this.#E[A],!W){if(Object.keys(this.#E).some((O)=>O.length>1&&O!==E6&&O!==X6))throw IE;if(J)return;W=this.#E[A]=new $}W.insert(D,E,X,G,J)}buildRegExpStr(){let E=Object.keys(this.#E).sort(VC).map((X)=>{let G=this.#E[X];return(typeof G.#w==="number"?`(${X})@${G.#w}`:KC.has(X)?`\\${X}`:X)+G.buildRegExpStr()});if(typeof this.#$==="number")E.unshift(`#${this.#$}`);if(E.length===0)return"";if(E.length===1)return E[0];return"(?:"+E.join("|")+")"}};var N9=R(()=>{IE=Symbol(),KC=new Set(".\\+*[^]$()")});var KF=class{#$={varIndex:0};#w=new IF;insert($,w,E){let X=[],G=[];for(let A=0;;){let D=!1;if($=$.replace(/\{[^}]+\}/g,(N)=>{let W=`@\\${A}`;return G[A]=[W,N],A++,D=!0,W}),!D)break}let J=$.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let A=G.length-1;A>=0;A--){let[D]=G[A];for(let N=J.length-1;N>=0;N--)if(J[N].indexOf(D)!==-1){J[N]=J[N].replace(D,G[A][1]);break}}return this.#w.insert(J,w,X,this.#$,E),X}buildRegExp(){let $=this.#w.buildRegExpStr();if($==="")return[/^$/,[],[]];let w=0,E=[],X=[];return $=$.replace(/#(\d+)|@(\d+)|\.\*\$/g,(G,J,A)=>{if(J!==void 0)return E[++w]=Number(J),"$()";if(A!==void 0)return X[Number(A)]=++w,"";return""}),[new RegExp(`^${$}`),E,X]}};var VF=R(()=>{N9()});function qF($){return PF[$]??=new RegExp($==="*"?"":`^${$.replace(/\/\*$|([.\\+*[^\]$()])/g,(w,E)=>E?`\\${E}`:"(?:|/.*)")}$`)}function qC(){PF=Object.create(null)}function SC($){let w=new KF,E=[];if($.length===0)return PC;let X=$.map((W)=>[!/\*|\/:/.test(W[0]),...W]).sort(([W,O],[Y,H])=>W?1:Y?-1:O.length-H.length),G=Object.create(null);for(let W=0,O=-1,Y=X.length;W<Y;W++){let[H,L,F]=X[W];if(H)G[L]=[F.map(([M])=>[M,Object.create(null)]),w6];else O++;let j;try{j=w.insert(L,O,H)}catch(M){throw M===IE?new vA(L):M}if(H)continue;E[O]=F.map(([M,z])=>{let B=Object.create(null);z-=1;for(;z>=0;z--){let[Q,k]=j[z];B[Q]=k}return[M,B]})}let[J,A,D]=w.buildRegExp();for(let W=0,O=E.length;W<O;W++)for(let Y=0,H=E[W].length;Y<H;Y++){let L=E[W][Y]?.[1];if(!L)continue;let F=Object.keys(L);for(let j=0,M=F.length;j<M;j++)L[F[j]]=D[L[F[j]]]}let N=[];for(let W in A)N[W]=E[A[W]];return[J,N,G]}function VX($,w){if(!$)return;for(let E of Object.keys($).sort((X,G)=>G.length-X.length))if(qF(E).test(w))return[...$[E]];return}var PC,PF,yA=class{name="RegExpRouter";#$;#w;constructor(){this.#$={[k0]:Object.create(null)},this.#w={[k0]:Object.create(null)}}add($,w,E){let X=this.#$,G=this.#w;if(!X||!G)throw Error(_A);if(!X[$])[X,G].forEach((D)=>{D[$]=Object.create(null),Object.keys(D[k0]).forEach((N)=>{D[$][N]=[...D[k0][N]]})});if(w==="/*")w="*";let J=(w.match(/\/:/g)||[]).length;if(/\*$/.test(w)){let D=qF(w);if($===k0)Object.keys(X).forEach((N)=>{X[N][w]||=VX(X[N],w)||VX(X[k0],w)||[]});else X[$][w]||=VX(X[$],w)||VX(X[k0],w)||[];Object.keys(X).forEach((N)=>{if($===k0||$===N)Object.keys(X[N]).forEach((W)=>{D.test(W)&&X[N][W].push([E,J])})}),Object.keys(G).forEach((N)=>{if($===k0||$===N)Object.keys(G[N]).forEach((W)=>D.test(W)&&G[N][W].push([E,J]))});return}let A=bA(w)||[w];for(let D=0,N=A.length;D<N;D++){let W=A[D];Object.keys(G).forEach((O)=>{if($===k0||$===O)G[O][W]||=[...VX(X[O],W)||VX(X[k0],W)||[]],G[O][W].push([E,J-N+D+1])})}}match=fA;buildAllMatchers(){let $=Object.create(null);return Object.keys(this.#w).concat(Object.keys(this.#$)).forEach((w)=>{$[w]||=this.#E(w)}),this.#$=this.#w=void 0,qC(),$}#E($){let w=[],E=$===k0;if([this.#$,this.#w].forEach((X)=>{let G=X[$]?Object.keys(X[$]).map((J)=>[J,X[$][J]]):[];if(G.length!==0)E||=!0,w.push(...G);else if($!==k0)w.push(...Object.keys(X[k0]).map((J)=>[J,X[k0][J]]))}),!E)return null;else return SC(w)}};var W9=R(()=>{QE();pw();D9();N9();VF();PC=[/^$/,[],Object.create(null)],PF=Object.create(null)});var kC=class{name="PreparedRegExpRouter";#$;#w;constructor($,w){this.#$=$,this.#w=w}#E($,w){let E=this.#$[$];E[1].forEach((X)=>X&&X.push(w)),Object.values(E[2]).forEach((X)=>X[0].push(w))}#J($,w,E,X,G){let J=this.#$[$];if(!G)J[2][w][0].push([E,{}]);else X.forEach((A)=>{if(typeof A==="number")J[1][A].push([E,G]);else J[2][A||w][0].push([E,G])})}add($,w,E){if(!this.#$[$]){let G=this.#$[k0],J={};for(let A in G[2])J[A]=[G[2][A][0].slice(),w6];this.#$[$]=[G[0],G[1].map((A)=>Array.isArray(A)?A.slice():0),J]}if(w==="/*"||w==="*"){let G=[E,{}];if($===k0)for(let J in this.#$)this.#E(J,G);else this.#E($,G);return}let X=this.#w[w];if(!X)throw Error(`Path ${w} is not registered`);for(let[G,J]of X)if($===k0)for(let A in this.#$)this.#J(A,w,E,G,J);else this.#J($,w,E,G,J)}buildAllMatchers(){return this.#$}match=fA};var SF=R(()=>{QE();D9();W9()});var kF=R(()=>{W9();SF()});var O9=class{name="SmartRouter";#$=[];#w=[];constructor($){this.#$=$.routers}add($,w,E){if(!this.#w)throw Error(_A);this.#w.push([$,w,E])}match($,w){if(!this.#w)throw Error("Fatal error");let E=this.#$,X=this.#w,G=E.length,J=0,A;for(;J<G;J++){let D=E[J];try{for(let N=0,W=X.length;N<W;N++)D.add(...X[N]);A=D.match($,w)}catch(N){if(N instanceof vA)continue;throw N}this.match=D.match.bind(D),this.#$=[D],this.#w=void 0;break}if(J===G)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,A}get activeRouter(){if(this.#w||this.#$.length!==1)throw Error("No active router has been determined yet.");return this.#$[0]}};var bF=R(()=>{QE()});var ZF=R(()=>{bF()});var G6,bC=($)=>{for(let w in $)return!0;return!1},CF=class ${#$;#w;#E;#J=0;#G=G6;constructor(w,E,X){if(this.#w=X||Object.create(null),this.#$=[],w&&E){let G=Object.create(null);G[w]={handler:E,possibleKeys:[],score:0},this.#$=[G]}this.#E=[]}insert(w,E,X){this.#J=++this.#J;let G=this,J=t3(E),A=[];for(let D=0,N=J.length;D<N;D++){let W=J[D],O=J[D+1],Y=i3(W,O),H=Array.isArray(Y)?Y[0]:W;if(H in G.#w){if(G=G.#w[H],Y)A.push(Y[1]);continue}if(G.#w[H]=new $,Y)G.#E.push(Y),A.push(Y[1]);G=G.#w[H]}return G.#$.push({[w]:{handler:X,possibleKeys:A.filter((D,N,W)=>W.indexOf(D)===N),score:this.#J}}),G}#X(w,E,X,G,J){for(let A=0,D=E.#$.length;A<D;A++){let N=E.#$[A],W=N[X]||N[k0],O={};if(W!==void 0){if(W.params=Object.create(null),w.push(W),G!==G6||J&&J!==G6)for(let Y=0,H=W.possibleKeys.length;Y<H;Y++){let L=W.possibleKeys[Y],F=O[W.score];W.params[L]=J?.[L]&&!F?J[L]:G[L]??J?.[L],O[W.score]=!0}}}}search(w,E){let X=[];this.#G=G6;let J=[this],A=eN(E),D=[],N=A.length,W=null;for(let O=0;O<N;O++){let Y=A[O],H=O===N-1,L=[];for(let j=0,M=J.length;j<M;j++){let z=J[j],B=z.#w[Y];if(B)if(B.#G=z.#G,H){if(B.#w["*"])this.#X(X,B.#w["*"],w,z.#G);this.#X(X,B,w,z.#G)}else L.push(B);for(let Q=0,k=z.#E.length;Q<k;Q++){let v=z.#E[Q],C=z.#G===G6?{}:{...z.#G};if(v==="*"){let d0=z.#w["*"];if(d0)this.#X(X,d0,w,z.#G),d0.#G=C,L.push(d0);continue}let[n,T0,f0]=v;if(!Y&&!(f0 instanceof RegExp))continue;let c0=z.#w[n];if(f0 instanceof RegExp){if(W===null){W=Array(N);let U$=E[0]==="/"?1:0;for(let O1=0;O1<N;O1++)W[O1]=U$,U$+=A[O1].length+1}let d0=E.substring(W[O]),K0=f0.exec(d0);if(K0){if(C[T0]=K0[0],this.#X(X,c0,w,z.#G,C),bC(c0.#w)){c0.#G=C;let U$=K0[0].match(/\//)?.length??0;(D[U$]||=[]).push(c0)}continue}}if(f0===!0||f0.test(Y))if(C[T0]=Y,H){if(this.#X(X,c0,w,C,z.#G),c0.#w["*"])this.#X(X,c0.#w["*"],w,C,z.#G)}else c0.#G=C,L.push(c0)}}let F=D.shift();J=F?L.concat(F):L}if(X.length>1)X.sort((O,Y)=>{return O.score-Y.score});return[X.map(({handler:O,params:Y})=>[O,Y])]}};var _F=R(()=>{QE();pw();G6=Object.create(null)});var U9=class{name="TrieRouter";#$;constructor(){this.#$=new CF}add($,w,E){let X=bA(w);if(X){for(let G=0,J=X.length;G<J;G++)this.#$.insert($,X[G],E);return}this.#$.insert($,w,E)}match($,w){return this.#$.search($,w)}};var vF=R(()=>{pw();_F()});var fF=R(()=>{vF()});var Y9;var xF=R(()=>{QF();kF();ZF();fF();Y9=class extends BF{constructor($={}){super($);this.router=$.router??new O9({routers:[new yA,new U9]})}}});var yF=R(()=>{xF()});function gF($,w){let E={};return Object.keys($.paths).forEach((X)=>{E[f1(w.replaceAll(/:([^\/]+)/g,"{$1}"),X)]=$.paths[X]}),{...$,paths:E}}function uF($){return/^application\/([a-z-\.]+\+)?json/.test($)}function hF($){return $.startsWith("multipart/form-data")||$.startsWith("application/x-www-form-urlencoded")}var p0,m=($)=>{let w={...$,getRoutingPath(){return $.path.replaceAll(/\/{(.+?)}/g,"/:$1")}};return Object.defineProperty(w,"getRoutingPath",{enumerable:!1})};var N1=R(()=>{o3();DF();yF();pw();OG();p0=class $ extends Y9{openAPIRegistry;defaultHook;constructor(w){super(w);this.openAPIRegistry=new iN,this.defaultHook=w?.defaultHook}openapi=({middleware:w,hide:E,...X},G,J=this.defaultHook)=>{if(!E)this.openAPIRegistry.registerPath(X);let A=[];if(X.request?.query){let W=BE("query",X.request.query,J);A.push(W)}if(X.request?.params){let W=BE("param",X.request.params,J);A.push(W)}if(X.request?.headers){let W=BE("header",X.request.headers,J);A.push(W)}if(X.request?.cookies){let W=BE("cookie",X.request.cookies,J);A.push(W)}let D=X.request?.body?.content;if(D)for(let W of Object.keys(D)){if(!D[W])continue;let O=D[W].schema;if(!(O instanceof G0))continue;if(uF(W)){let Y=BE("json",O,J);if(X.request?.body?.required)A.push(Y);else{let H=async(L,F)=>{if(L.req.header("content-type")){if(uF(L.req.header("content-type")))return await Y(L,F)}L.req.addValidatedData("json",{}),await F()};A.push(H)}}if(hF(W)){let Y=BE("form",O,J);if(X.request?.body?.required)A.push(Y);else{let H=async(L,F)=>{if(L.req.header("content-type")){if(hF(L.req.header("content-type")))return await Y(L,F)}L.req.addValidatedData("form",{}),await F()};A.push(H)}}}let N=w?Array.isArray(w)?w:[w]:[];return this.on([X.method],X.path.replaceAll(/\/{(.+?)}/g,"/:$1"),...N,...A,G),this};getOpenAPIDocument=(w)=>{let X=new lN(this.openAPIRegistry.definitions).generateDocument(w);return this._basePath?gF(X,this._basePath):X};getOpenAPI31Document=(w)=>{let X=new sN(this.openAPIRegistry.definitions).generateDocument(w);return this._basePath?gF(X,this._basePath):X};doc=(w,E)=>{return this.get(w,(X)=>{let G=typeof E==="function"?E(X):E;try{let J=this.getOpenAPIDocument(G);return X.json(J)}catch(J){return X.json(J,500)}})};doc31=(w,E)=>{return this.get(w,(X)=>{let G=typeof E==="function"?E(X):E;try{let J=this.getOpenAPI31Document(G);return X.json(J)}catch(J){return X.json(J,500)}})};route(w,E){let X=w.replaceAll(/:([^\/]+)/g,"{$1}");if(super.route(w,E),!(E instanceof $))return this;return E.openAPIRegistry.definitions.forEach((G)=>{switch(G.type){case"component":return this.openAPIRegistry.registerComponent(G.componentType,G.name,G.component);case"route":{this.openAPIRegistry.registerPath({...G.route,path:f1(X,E._basePath.replaceAll(/:([^\/]+)/g,"{$1}"),G.route.path)});return}case"webhook":{this.openAPIRegistry.registerWebhook({...G.webhook,path:f1(X,E._basePath.replaceAll(/:([^\/]+)/g,"{$1}"),G.webhook.path)});return}case"schema":return this.openAPIRegistry.register(G.schema._def.openapi._internal.refId,G.schema);case"parameter":return this.openAPIRegistry.registerParameter(G.schema._def.openapi._internal.refId,G.schema);default:throw Error(`Unknown registry type: ${G}`)}}),this}basePath(w){return new $({...super.basePath(w),defaultHook:this.defaultHook})}};P3(U)});var PX,U0,Ew,H9;var x1=R(()=>{PX=class PX extends Error{code;statusCode;constructor($,w,E=500){super($);this.code=w;this.statusCode=E;this.name="OrcError"}};U0=class U0 extends PX{constructor($,w){super(`${$} not found: ${w}`,"NOT_FOUND",404);this.name="NotFoundError"}};Ew=class Ew extends PX{constructor($){super($,"VALIDATION_ERROR",400);this.name="ValidationError"}};H9=class H9 extends PX{constructor($="Unauthorized"){super($,"UNAUTHORIZED",401);this.name="UnauthorizedError"}}});function cF($){return async(w,E)=>{if(!$)return E();let X=w.req.header("Authorization");if(!X?.startsWith("Bearer ")||X.slice(7)!==$)throw new H9;return E()}}var nF=R(()=>{x1()});var gA,ZC,CC,_C,vC;var mF=R(()=>{N1();bN();gA=new p0,ZC=U.object({running:U.boolean(),status:U.string()}).openapi("GatewayStatus"),CC=U.object({platform:U.string(),chat_id:U.string(),text:U.string(),thread_id:U.string().optional()}).openapi("GatewaySend"),_C=m({method:"get",path:"/gateway/status",tags:["Gateway"],summary:"Get gateway status",responses:{200:{content:{"application/json":{schema:ZC}},description:"Gateway status"}}}),vC=m({method:"post",path:"/gateway/send",tags:["Gateway"],summary:"Send a message via the gateway",request:{body:{content:{"application/json":{schema:CC}}}},responses:{204:{description:"Message sent"},503:{content:{"application/json":{schema:U.object({error:U.string()})}},description:"Gateway not running"}}});gA.openapi(_C,async($)=>{let w=zA()!==null;return $.json({running:w,status:kN()})});gA.openapi(vC,async($)=>{if(!zA())return $.json({error:"Gateway is not running"},503);let{platform:w,chat_id:E,text:X,thread_id:G}=$.req.valid("json");return await SN(w,E,X,G?{threadId:G}:void 0),$.body(null,204)})});var L9,fC,xC;var rF=R(()=>{FJ();N1();L9=new p0,fC=m({method:"get",path:"/health",tags:["System"],summary:"Health check",responses:{200:{description:"Service is healthy",content:{"application/json":{schema:U.object({status:U.literal("ok"),version:U.string(),uptime:U.number()})}}}}}),xC=Date.now();L9.openapi(fC,($)=>{return $.json({status:"ok",version:lE,uptime:Math.floor((Date.now()-xC)/1000)})})});var uA,J6,hA,pF,cA,_w0,vw0,fw0,F9,xw0,yw0,gw0;var nA=R(()=>{OG();uA=U.enum(["todo","doing","review","changes_requested","blocked","done","cancelled"]),J6=U.enum(["low","normal","high","critical"]),hA=U.enum(["one-shot","cron","watch","webhook","manual","bridge-msg"]),pF=U.enum(["pending","running","success","failed","cancelled","skipped"]),cA=U.enum(["skip","queue","kill"]),_w0=U.enum(["low","normal","high","critical"]),vw0=U.enum(["telegram","slack","discord","feishu"]),fw0=U.enum(["direct","agent:claude","agent:codex","agent:cursor","multi"]).or(U.string().startsWith("job:")),F9=U.enum(["blocks","blocked_by","relates_to","duplicates","clones","subtask_of","parent_of"]),xw0=U.enum(["active","archived","paused"]),yw0=U.enum(["solo","pair","parallel","handoff"]),gw0=U.enum(["solo","human_agent","multi_agent"])});function rA($){return{...$,project_id:$.project_id??null,last_run_at:$.last_run_at?.toISOString()??null,next_run_at:$.next_run_at?.toISOString()??null,created_at:$.created_at.toISOString(),updated_at:$.updated_at.toISOString()}}function lC($){return{...$,started_at:$.started_at?.toISOString()??null,ended_at:$.ended_at?.toISOString()??null,created_at:$.created_at.toISOString()}}var yC,Xw,mA,gC,uC,hC,cC,nC,mC,rC,pC,oC,tC,iC,dC;var oF=R(()=>{N1();x1();X1();p$();nA();y$();d$();nw();i$();yC=Z0("api:jobs"),Xw=new p0,mA=U.object({id:U.string(),name:U.string(),description:U.string().nullable(),command:U.string(),trigger_type:hA,cron_expr:U.string().nullable(),enabled:U.boolean(),timeout_secs:U.number(),max_retries:U.number(),overlap:cA,notify_on:U.enum(["never","failure","always"]),project_id:U.string().nullable(),run_count:U.number(),last_run_at:U.string().datetime().nullable(),next_run_at:U.string().datetime().nullable(),created_at:U.string().datetime(),updated_at:U.string().datetime()}).openapi("Job"),gC=U.object({name:U.string().min(1).max(100),description:U.string().optional(),command:U.string().min(1),trigger_type:hA,cron_expr:U.string().optional(),watch_path:U.string().optional(),timeout_secs:U.number().int().positive().optional().default(300),max_retries:U.number().int().min(0).optional().default(0),overlap:cA.optional().default("skip"),notify_on:U.enum(["never","failure","always"]).optional().default("failure"),env_vars:U.record(U.string()).optional(),working_dir:U.string().optional(),project_id:U.string().optional()}).openapi("CreateJob"),uC=U.object({id:U.string(),job_id:U.string(),status:pF,trigger_by:U.string().nullable(),started_at:U.string().datetime().nullable(),ended_at:U.string().datetime().nullable(),exit_code:U.number().nullable(),error_msg:U.string().nullable(),retry_num:U.number(),created_at:U.string().datetime()}).openapi("JobRun"),hC=U.object({id:U.number(),run_id:U.string(),ts:U.string().datetime(),stream:U.enum(["stdout","stderr"]),line:U.string()}).openapi("JobRunLog"),cC=m({method:"get",path:"/jobs",tags:["Jobs"],summary:"List jobs",request:{query:U.object({enabled:U.coerce.boolean().optional(),project_id:U.string().optional(),limit:U.coerce.number().int().min(1).max(100).optional().default(50)})},responses:{200:{description:"Jobs",content:{"application/json":{schema:U.object({jobs:U.array(mA)})}}}}}),nC=m({method:"get",path:"/jobs/{id}",tags:["Jobs"],summary:"Get job",request:{params:U.object({id:U.string()})},responses:{200:{description:"Job",content:{"application/json":{schema:mA}}}}}),mC=m({method:"post",path:"/jobs",tags:["Jobs"],summary:"Create job",request:{body:{content:{"application/json":{schema:gC}}}},responses:{201:{description:"Created",content:{"application/json":{schema:mA}}}}}),rC=U.object({name:U.string().min(1).max(100).optional(),description:U.string().optional(),command:U.string().min(1).optional(),trigger_type:hA.optional(),cron_expr:U.string().optional(),watch_path:U.string().optional(),timeout_secs:U.number().int().positive().optional(),max_retries:U.number().int().min(0).optional(),overlap:cA.optional(),notify_on:U.enum(["never","failure","always"]).optional(),enabled:U.boolean().optional(),env_vars:U.record(U.string()).optional(),working_dir:U.string().optional(),project_id:U.string().optional()}).openapi("UpdateJob"),pC=m({method:"patch",path:"/jobs/{id}",tags:["Jobs"],summary:"Update job",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:rC}}}},responses:{200:{description:"Updated",content:{"application/json":{schema:mA}}}}}),oC=m({method:"delete",path:"/jobs/{id}",tags:["Jobs"],summary:"Delete job",request:{params:U.object({id:U.string()})},responses:{204:{description:"Deleted"}}}),tC=m({method:"post",path:"/jobs/{id}/trigger",tags:["Jobs"],summary:"Manually trigger a job",request:{params:U.object({id:U.string()})},responses:{202:{description:"Triggered",content:{"application/json":{schema:U.object({run_id:U.string()})}}}}}),iC=m({method:"get",path:"/jobs/{id}/runs",tags:["Jobs"],summary:"List job runs",request:{params:U.object({id:U.string()}),query:U.object({limit:U.coerce.number().int().min(1).max(50).optional().default(20)})},responses:{200:{description:"Runs",content:{"application/json":{schema:U.object({runs:U.array(uC)})}}}}}),dC=m({method:"get",path:"/jobs/{id}/runs/{runId}/logs",tags:["Jobs"],summary:"Stream log lines for a specific run",request:{params:U.object({id:U.string(),runId:U.string()}),query:U.object({stream:U.enum(["stdout","stderr"]).optional(),limit:U.coerce.number().int().min(1).max(5000).optional().default(500)})},responses:{200:{description:"Log lines",content:{"application/json":{schema:U.object({logs:U.array(hC)})}}}}});Xw.openapi(cC,async($)=>{let w=x(),{limit:E,project_id:X}=$.req.valid("query"),G=[];if(X)G.push(V(I0.project_id,X));let J=await w.query.jobs.findMany({where:G.length?S0(...G):void 0,limit:E,orderBy:(A,{asc:D})=>[D(A.name)]});return $.json({jobs:J.map(rA)})});Xw.openapi(nC,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=await w.query.jobs.findFirst({where:V(I0.id,E)});if(!X)throw new U0("Job",E);return $.json(rA(X))});Xw.openapi(mC,async($)=>{let w=x(),E=$.req.valid("json"),X=new Date,G=i();await w.insert(I0).values({id:G,name:E.name,description:E.description,command:E.command,trigger_type:E.trigger_type,cron_expr:E.cron_expr,watch_path:E.watch_path,timeout_secs:E.timeout_secs,max_retries:E.max_retries,overlap:E.overlap,notify_on:E.notify_on,env_vars:E.env_vars,working_dir:E.working_dir,project_id:E.project_id,created_at:X,updated_at:X});let J=await w.query.jobs.findFirst({where:V(I0.id,G)});if(!J)throw Error("Expected job to exist after write");return $.json(rA(J),201)});Xw.openapi(pC,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=$.req.valid("json");if(!await w.query.jobs.findFirst({where:V(I0.id,E)}))throw new U0("Job",E);await w.update(I0).set({...X.name!==void 0?{name:X.name}:{},...X.description!==void 0?{description:X.description}:{},...X.command!==void 0?{command:X.command}:{},...X.trigger_type!==void 0?{trigger_type:X.trigger_type}:{},...X.cron_expr!==void 0?{cron_expr:X.cron_expr}:{},...X.watch_path!==void 0?{watch_path:X.watch_path}:{},...X.timeout_secs!==void 0?{timeout_secs:X.timeout_secs}:{},...X.max_retries!==void 0?{max_retries:X.max_retries}:{},...X.overlap!==void 0?{overlap:X.overlap}:{},...X.notify_on!==void 0?{notify_on:X.notify_on}:{},...X.enabled!==void 0?{enabled:X.enabled}:{},...X.env_vars!==void 0?{env_vars:X.env_vars}:{},...X.working_dir!==void 0?{working_dir:X.working_dir}:{},...X.project_id!==void 0?{project_id:X.project_id}:{},updated_at:new Date}).where(V(I0.id,E));let J=await w.query.jobs.findFirst({where:V(I0.id,E)});if(!J)throw Error("Expected job to exist after write");return $.json(rA(J))});Xw.openapi(oC,async($)=>{let w=x(),{id:E}=$.req.valid("param");if(!await w.query.jobs.findFirst({where:V(I0.id,E)}))throw new U0("Job",E);return await w.delete(I0).where(V(I0.id,E)),new Response(null,{status:204})});Xw.openapi(tC,async($)=>{let w=x(),{id:E}=$.req.valid("param");if(!await w.query.jobs.findFirst({where:V(I0.id,E)}))throw new U0("Job",E);let G=i();return await w.insert(E$).values({id:G,job_id:E,status:"pending",trigger_by:"api",created_at:new Date}),A1({jobId:E,runId:G,triggerBy:"api"}).catch((J)=>yC.error(`Background execution failed for run ${G}: ${J instanceof Error?J.message:String(J)}`)),$.json({run_id:G},202)});Xw.openapi(iC,async($)=>{let w=x(),{id:E}=$.req.valid("param"),{limit:X}=$.req.valid("query"),G=await w.query.job_runs.findMany({where:V(E$.job_id,E),limit:X,orderBy:[x0(E$.created_at)]});return $.json({runs:G.map(lC)})});Xw.openapi(dC,async($)=>{let w=x(),{id:E,runId:X}=$.req.valid("param"),{stream:G,limit:J}=$.req.valid("query"),A=await w.query.job_runs.findFirst({where:V(E$.id,X)});if(!A||A.job_id!==E)throw new U0("JobRun",X);let D=await w.query.job_run_logs.findMany({where:G?S0(V(cw.run_id,X),V(cw.stream,G)):V(cw.run_id,X),limit:J,orderBy:[qJ(cw.ts)]});return $.json({logs:D.map((N)=>({...N,ts:N.ts.toISOString()}))})})});function sC($,w=80){return $.length<=w?$:`${$.slice(0,w-1)}\u2026`}function aC($){let w=Date.now()-$*1000,E=Math.floor(w/60000);if(E<60)return`${E}m ago`;let X=Math.floor(E/60);if(X<24)return`${X}h ago`;return`${Math.floor(X/24)}d ago`}function eC($,w,E){return{id:$.id,snippet:sC($.content),scope:$.scope,type:$.type??"fact",importance:$.importance,age:aC($.created_at),rank:w,matchLayer:E}}function iF(){return x().$client}function dF($,w,E){let X=[],G=[];if($)X.push("m.scope = ?"),G.push($);if(w)X.push("m.type = ?"),G.push(w);if(E)X.push("m.project_id = ?"),G.push(E);return{clause:X.length?` AND ${X.join(" AND ")}`:"",params:G}}function pA($,w,E,X,G,J,A){let{clause:D,params:N}=dF(X,G,A),W=`SELECT ${M9}
|
|
440
440
|
FROM ${w} f JOIN memories m ON m.id = f.id
|
|
441
441
|
WHERE f.${w} MATCH ?${D}
|
|
442
|
-
ORDER BY bm25(${w}, 0, 1.0, 3.0, 1.5, 0) LIMIT ?`;try{return $.query(W).all(E,...N,J)}catch{return[]}}function
|
|
442
|
+
ORDER BY bm25(${w}, 0, 1.0, 3.0, 1.5, 0) LIMIT ?`;try{return $.query(W).all(E,...N,J)}catch{return[]}}function j9($,w){let E=[],X=[],G=[],J=$.replace(/"([^"]+)"/g,(N,W)=>{return E.push(`"${W}"`),""});J=J.replace(/-(\S+)/g,(N,W)=>{return X.push(W),""}),G.push(...J.trim().split(/\s+/).filter((N)=>N.length>0));let A=[...E,...G].join(` ${w} `),D=X.map((N)=>`NOT ${N}`).join(" ");return[A,D].filter(Boolean).join(" ")}function tF($,w){return j9($,w)}function R9($,w,E=10,X,G){let J=iF(),A=$.trim();if(!A)return[];let D=new Set;function N(j,M){let z=[];for(let B of j)if(!D.has(B.id))D.add(B.id),z.push(eC(B,D.size,M));return z}let W=[],O=pA(J,"memories_fts",j9(A,"AND"),w,X,E,G);if(W.push(...N(O,"porter")),W.length>=E)return A6(W.slice(0,E));let Y=pA(J,"memories_fts",j9(A,"OR"),w,X,E,G);if(W.push(...N(Y,"porter")),W.length>=E)return A6(W.slice(0,E));let H=pA(J,"memories_fts_trigram",tF(A,"AND"),w,X,E,G);if(W.push(...N(H,"trigram")),W.length>=E)return A6(W.slice(0,E));let L=pA(J,"memories_fts_trigram",tF(A,"OR"),w,X,E,G);if(W.push(...N(L,"trigram")),W.length>=E)return A6(W.slice(0,E));if(W.length===0){let{clause:j,params:M}=dF(w,X,G),z=[`%${A.toLowerCase()}%`,...M,E],B=J.query(`SELECT ${M9} FROM memories m
|
|
443
443
|
WHERE m.content LIKE ?${j}
|
|
444
|
-
ORDER BY m.created_at DESC LIMIT ?`).all(...z);W.push(...N(B,"fallback"))}let F=
|
|
445
|
-
m.created_at, m.updated_at, m.source, m.tags, m.expires_at`;var
|
|
444
|
+
ORDER BY m.created_at DESC LIMIT ?`).all(...z);W.push(...N(B,"fallback"))}let F=A6(W.slice(0,E));if(F.length>0){let j=F.map((z)=>z.id),M=j.map(()=>"?").join(",");try{J.query(`UPDATE memories SET access_count = access_count + 1, last_accessed_at = unixepoch() WHERE id IN (${M})`).run(...j)}catch{}}return F}function A6($){return $.map((w,E)=>({...w,rank:E+1}))}function lF($){if($.length===0)return[];let w=iF(),E=$.map(()=>"?").join(",");return w.query(`SELECT ${M9} FROM memories m WHERE m.id IN (${E})`).all(...$).map((G)=>({id:G.id,title:G.title,type:G.type??"fact",content:G.content,source:G.source,scope:G.scope,tags:G.tags?JSON.parse(G.tags):null,importance:G.importance,created_at:new Date(G.created_at*1000).toISOString(),updated_at:new Date(G.updated_at*1000).toISOString()}))}var M9=`m.id, m.title, m.type, m.content, m.scope, m.importance,
|
|
445
|
+
m.created_at, m.updated_at, m.source, m.tags, m.expires_at`;var sF=R(()=>{y$()});import{createHash as $_}from"crypto";function Qw($,w){let E=w||O0().activeProject;if(!E)return null;return $.query("SELECT id, name FROM projects WHERE name = ? COLLATE NOCASE LIMIT 1").get(E)??null}async function D6($,w){let E=x();switch($){case"memory_search":{let{query:X,scope:G,type:J,limit:A,project:D}=w,N=Qw(z$(E),D),W=R9(X,G,A,J,N?.id);if(W.length===0)return"No memories found.";let O=[`Found ${W.length} results:`];for(let Y of W){let H=Y.type!=="fact"?` [${Y.type}]`:"";O.push(`[${Y.rank}] ${Y.id}${H} "${Y.snippet}" scope:${Y.scope??"\u2014"} ${Y.age} (${Y.matchLayer})`)}return O.push(`
|
|
446
446
|
Use memory_timeline(id) for context, memory_get([ids]) for full content.`),O.join(`
|
|
447
|
-
`)}case"memory_get":{let{ids:X}=w,G=
|
|
447
|
+
`)}case"memory_get":{let{ids:X}=w,G=lF(X);if(G.length===0)return"No memories found.";return G.map((J)=>{return`${J.title?`[${J.id}] [${J.type}] "${J.title}" (${J.importance})`:`[${J.id}] [${J.type}] (${J.importance})`}
|
|
448
448
|
${J.content}`}).join(`
|
|
449
449
|
|
|
450
450
|
---
|
|
@@ -473,25 +473,25 @@ ${G}`;return await E.update(r).set({status:"review",body:A,updated_at:new Date})
|
|
|
473
473
|
Task: ${G.title} [${G.status}]`}case"job_list":{let{limit:X,project:G}=w,J=Qw(z$(E),G),A=J?[V(I0.project_id,J.id)]:[],D=await E.query.jobs.findMany({where:A.length>0?S0(...A):void 0,limit:X??20});if(D.length===0)return"No jobs defined.";return D.map((N)=>`${N.enabled?"\u25CF":"\u25CB"} ${N.name.padEnd(24)} ${N.trigger_type.padEnd(12)} runs:${N.run_count}`).join(`
|
|
474
474
|
`)}case"job_run":{let{name:X}=w,G=await E.query.jobs.findFirst({where:V(I0.name,X)});if(!G)return`Job not found: ${X}`;let J=i();return await E.insert(E$).values({id:J,job_id:G.id,status:"pending",trigger_by:"mcp",created_at:new Date}),A1({jobId:G.id,runId:J,triggerBy:"mcp"}).catch(()=>{}),`Triggered: ${X} \u2192 run_id: ${J}`}case"job_status":{let{run_id:X}=w,G=await E.query.job_runs.findFirst({where:V(E$.id,X)});if(!G)return`Run not found: ${X}`;return JSON.stringify({status:G.status,exit_code:G.exit_code,error:G.error_msg})}case"context":{let{project:X}=w,G=O0(),J=G.context.layer1_task_limit,A=G.context.layer1_memory_limit,D=Qw(z$(E),X),N=[];if(D)N.push(V(r.project_id,D.id));let O=(await E.query.tasks.findMany({where:N.length>0?S0(...N):void 0,limit:J,orderBy:(k,{desc:v})=>[v(k.updated_at)]})).filter((k)=>!["done","cancelled"].includes(k.status)),Y=[];if(D)Y.push(V(H1.project_id,D.id));let H=await E.query.memories.findMany({where:Y.length>0?S0(...Y):void 0,limit:A*3,orderBy:(k,{desc:v})=>[v(k.created_at)]}),L={critical:4,high:3,normal:2,low:1},F={rule:3,decision:3,discovery:2,fact:1,event:1},j=Date.now(),M=H.map((k)=>{let v=(j-k.created_at.getTime())/3600000,C=Math.max(0,1-v/720),n=(L[k.importance]??1)*2+(F[k.type??"fact"]??1)+C*2;return{m:k,score:n}});M.sort((k,v)=>v.score-k.score);let z=M.slice(0,A).map((k)=>k.m),B=await E.query.sessions.findFirst({orderBy:[x0(C1.created_at)]}),Q=[];if(D)Q.push(`## Project: ${D.name}`);if(Q.push(D?`
|
|
475
475
|
## Active Tasks`:"## Active Tasks"),O.length===0)Q.push(" (none)");for(let k of O)Q.push(` [${k.id}] ${k.status.padEnd(10)} ${k.title}`);if(Q.push(`
|
|
476
|
-
## Key Memory`),z.length===0)Q.push(" (none)");for(let k of z){let v=k.type!=="fact"?` [${k.type}]`:"",C=k.title?` "${k.title}"`:"";Q.push(` [${k.id}]${v}${C} ${k.content.slice(0,60)} (${
|
|
476
|
+
## Key Memory`),z.length===0)Q.push(" (none)");for(let k of z){let v=k.type!=="fact"?` [${k.type}]`:"",C=k.title?` "${k.title}"`:"";Q.push(` [${k.id}]${v}${C} ${k.content.slice(0,60)} (${E_(k.created_at)})`)}if(B?.summary)Q.push(`
|
|
477
477
|
## Last Session (${B.agent})`),Q.push(` ${B.summary}`);return Q.push(`
|
|
478
478
|
Use task_get([ids]) or memory_get([ids]) for full content.`),Q.join(`
|
|
479
|
-
`)}case"session_event":{let{session_id:X,type:G,priority:J,data:A}=w,D=z$(E),N=X??process.env.ORC_SESSION_ID??"default",W=JSON.stringify(A),O
|
|
479
|
+
`)}case"session_event":{let{session_id:X,type:G,priority:J,data:A}=w,D=z$(E),N=X??process.env.ORC_SESSION_ID??"default",W=JSON.stringify(A),O=$_("sha256").update(W).digest("hex").slice(0,16);if(D.query(`SELECT data_hash FROM session_events
|
|
480
480
|
WHERE session_id = ? AND type = ?
|
|
481
481
|
ORDER BY created_at DESC LIMIT ?`).all(N,G,5).some((F)=>F.data_hash===O))return"Duplicate event skipped.";let{n:H}=D.query("SELECT COUNT(*) as n FROM session_events WHERE session_id = ?").get(N)??{n:0};if(H>=1000)D.query(`DELETE FROM session_events WHERE id = (
|
|
482
482
|
SELECT id FROM session_events WHERE session_id = ?
|
|
483
483
|
ORDER BY priority ASC, created_at ASC LIMIT 1
|
|
484
484
|
)`).run(N);let L=i();return D.query("INSERT INTO session_events(id, session_id, type, priority, data, data_hash) VALUES (?,?,?,?,?,?)").run(L,N,G,J??3,W,O),`Event recorded: ${L}`}case"session_snapshot":{let{session_id:X}=w,J=O0().context.snapshot_max_bytes,A=X??process.env.ORC_SESSION_ID??"default",N=(await E.query.tasks.findMany({limit:10,orderBy:(L,{desc:F})=>[F(L.updated_at)]})).filter((L)=>!["done","cancelled"].includes(L.status)),W=z$(E),O=W.query(`SELECT type, priority, data FROM session_events
|
|
485
485
|
WHERE session_id = ?
|
|
486
|
-
ORDER BY priority ASC, created_at DESC LIMIT 100`).all(A),Y=
|
|
486
|
+
ORDER BY priority ASC, created_at DESC LIMIT 100`).all(A),Y=w_(N,O,J),H=i();return W.query("INSERT INTO session_snapshots(id, session_id, xml) VALUES (?,?,?)").run(H,A,Y),Y}case"session_restore":{let{session_id:X}=w,G=X??process.env.ORC_SESSION_ID??"default",A=z$(E).query("SELECT xml FROM session_snapshots WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(G);if(!A)return"No session snapshot found. Starting fresh.";return`## Session Restored
|
|
487
487
|
|
|
488
488
|
${A.xml}`}case"session_log":{let{agent:X,agent_version:G,summary:J,session_id:A,project:D}=w,N=Qw(z$(E),D),W=A??process.env.ORC_SESSION_ID??"default",O=process.env.ORC_JOB_RUN_ID,H=z$(E).query("SELECT type, data FROM session_events WHERE session_id = ? ORDER BY created_at ASC").all(W),L=new Set,F=new Set,j=new Set;for(let Q of H)try{let k=JSON.parse(Q.data);if(Q.type==="file"&&k.path)L.add(k.path);if(Q.type==="task"&&k.id)F.add(k.id);if(Q.type==="memory"&&k.id)j.add(k.id)}catch{}let M=[J];if(L.size>0)M.push(`Files: ${[...L].join(", ")}`);if(F.size>0)M.push(`Tasks: ${[...F].join(", ")}`);if(j.size>0)M.push(`Memories: ${[...j].join(", ")}`);let z=M.join(`
|
|
489
489
|
`),B=i();return await E.insert(C1).values({id:B,agent:X,agent_version:G,summary:z,project_id:N?.id,job_run_id:O,created_at:new Date}),`Session logged: ${B}`}case"project_list":{let{status:X}=w,G=X?[V(n0.status,X)]:[],J=await E.query.projects.findMany({where:G.length>0?S0(...G):void 0,orderBy:(A,{asc:D})=>[D(A.name)]});if(J.length===0)return"No projects found.";return J.map((A)=>{let D=A.description?` ${A.description.slice(0,60)}`:"";return`${A.name.padEnd(24)} ${A.status}${D}`}).join(`
|
|
490
490
|
`)}case"task_batch_create":{let{tasks:X,project:G,author:J}=w,A=Qw(z$(E),G),D=new Date,N={};for(let Y of X){let H=i();N[Y.ref]=H,await E.insert(r).values({id:H,title:Y.title,body:Y.body,project_id:A?.id,priority:Y.priority??"normal",author:J??"agent",status:"todo",created_at:D,updated_at:D})}let W=z$(E);for(let Y of X){let H=N[Y.ref];if(Y.depends_on)for(let L of Y.depends_on){let F=N[L];if(!F)continue;W.query("INSERT INTO task_links (id, from_task_id, to_task_id, link_type, created_at) VALUES (?, ?, ?, 'blocks', unixepoch())").run(i(),F,H)}if(Y.subtask_of){let L=N[Y.subtask_of];if(L)W.query("INSERT INTO task_links (id, from_task_id, to_task_id, link_type, created_at) VALUES (?, ?, ?, 'subtask_of', unixepoch())").run(i(),H,L),W.query("INSERT INTO task_links (id, from_task_id, to_task_id, link_type, created_at) VALUES (?, ?, ?, 'parent_of', unixepoch())").run(i(),L,H)}}let O=X.map((Y)=>` ${Y.ref} \u2192 ${N[Y.ref]} \u2014 ${Y.title}`);return`Created ${X.length} tasks:
|
|
491
491
|
${O.join(`
|
|
492
|
-
`)}`}case"search":{let{query:X,resources:G,project:J,limit:A}=w,D=Qw(z$(E),J),N=A??10,W=[];if(!G||G.includes("memories")){let O=
|
|
493
|
-
`):"No results found."}default:return`Unknown tool: ${$}`}}function z$($){return $.$client}function
|
|
494
|
-
`),G=w.filter((O)=>
|
|
492
|
+
`)}`}case"search":{let{query:X,resources:G,project:J,limit:A}=w,D=Qw(z$(E),J),N=A??10,W=[];if(!G||G.includes("memories")){let O=R9(X,void 0,Math.ceil(N/2),void 0,D?.id);if(O.length>0){W.push("## Memories");for(let Y of O)W.push(` [memory] ${Y.id} [${Y.type}] ${Y.snippet} (${Y.age})`)}}if(!G||G.includes("tasks")){let O=z$(E),Y=X.trim().split(/\s+/).filter((F)=>F.length>0),H=Math.ceil(N/2),L=[];if(Y.length>0)try{let F=Y.join(" AND "),j="SELECT t.id, t.title, t.status FROM tasks_fts f JOIN tasks t ON t.id = f.id WHERE f.tasks_fts MATCH ?",M=[F];if(D)j+=" AND t.project_id = ?",M.push(D.id);j+=" ORDER BY rank LIMIT ?",M.push(H),L=O.query(j).all(...M)}catch{let F=`SELECT id, title, status FROM tasks WHERE (title LIKE ? OR body LIKE ?)${D?" AND project_id = ?":""} ORDER BY updated_at DESC LIMIT ?`,j=[`%${X}%`,`%${X}%`];if(D)j.push(D.id);j.push(H),L=O.query(F).all(...j)}if(L.length>0){W.push("## Tasks");for(let F of L)W.push(` [task] ${F.id} ${F.status} \u2014 ${F.title}`)}}return W.length>0?W.join(`
|
|
493
|
+
`):"No results found."}default:return`Unknown tool: ${$}`}}function z$($){return $.$client}function w_($,w,E){let X=$.map((O)=>` <task id="${O.id.slice(-6)}" status="${O.status}" priority="${O.priority}">${$j(O.title)}</task>`).join(`
|
|
494
|
+
`),G=w.filter((O)=>aF.has(O.type)),J=w.filter((O)=>eF.has(O.type)),A=w.filter((O)=>!aF.has(O.type)&&!eF.has(O.type));function D(O,Y=5){let H={};for(let L of O.slice(0,Y*3)){if(!H[L.type])H[L.type]=[];let F=H[L.type]??[];if(F.length>=Y)continue;try{let j=JSON.parse(L.data);F.push(Object.entries(j).map(([M,z])=>`${M}=${String(z).slice(0,80)}`).join(" "))}catch{F.push(String(L.data).slice(0,120))}}return Object.entries(H).map(([L,F])=>` <${L}s>${F.map((j)=>`<item>${$j(j)}</item>`).join("")}</${L}s>`).join(`
|
|
495
495
|
`)}function N(O,Y){let H=[`<tasks>
|
|
496
496
|
${X}
|
|
497
497
|
</tasks>`],L=D(G);if(L)H.push(`<context priority="high">
|
|
@@ -507,17 +507,17 @@ ${H.join(`
|
|
|
507
507
|
<tasks>
|
|
508
508
|
${X}
|
|
509
509
|
</tasks>
|
|
510
|
-
</session>`}function
|
|
511
|
-
m.importance, m.expires_at, m.created_at, m.updated_at`;var
|
|
512
|
-
WHERE f.${B} MATCH ?${W}${O}${Y} ORDER BY rank LIMIT ?`).all(Q,...H,A)}catch{return[]}},j=N.split(/\s+/).filter(Boolean),M=j.join(" AND "),z=j.join(" OR ");if(L=F("memories_fts",M),L.length===0)L=F("memories_fts",z);if(L.length===0)L=F("memories_fts_trigram",M);if(L.length===0)L=F("memories_fts_trigram",z);if(L.length===0){let B=[`%${N.toLowerCase()}%`,...H,A];L=D.query(`SELECT ${
|
|
510
|
+
</session>`}function $j($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function E_($){let w=Date.now()-$.getTime(),E=Math.floor(w/60000);if(E<60)return`${E}m ago`;let X=Math.floor(E/60);if(X<24)return`${X}h ago`;return`${Math.floor(X/24)}d ago`}var Bw,qX,aF,eF;var oA=R(()=>{C$();X1();y$();d$();nw();i$();OG();sF();Bw=U.string().optional().describe("Project name (e.g. 'orc'). Defaults to activeProject from config if not set."),qX=[{name:"memory_search",description:"Search memories (3-layer BM25: porter \u2192 trigram \u2192 fallback). Returns compact index: IDs + snippets. "+"Filter by type (fact|decision|event|rule|discovery) or scope. Use memory_get for full content.",inputSchema:U.object({query:U.string().describe("Search query \u2014 keywords, phrases, or natural language"),scope:U.string().optional().describe("Scope filter (e.g. domain area)"),type:U.enum(["fact","decision","event","rule","discovery"]).optional().describe("Filter by memory type"),project:Bw,limit:U.number().int().min(1).max(20).optional().default(10)})},{name:"memory_get",description:"Fetch full content of specific memories by IDs. Always batch multiple IDs in one call. "+"~10x more token-expensive than memory_search \u2014 only call after filtering by ID.",inputSchema:U.object({ids:U.array(U.string()).min(1).max(20).describe("Memory IDs to fetch")})},{name:"memory_store",description:"Store a fact, decision, or context entry. Use type to classify: 'decision' for choices made, 'rule' for conventions/constraints, 'discovery' for findings, 'event' for things that happened, 'fact' for general knowledge.",inputSchema:U.object({content:U.string().describe("Content to remember"),title:U.string().optional().describe("Short label (\u226460 chars) for quick scanning"),type:U.enum(["fact","decision","event","rule","discovery"]).optional().default("fact"),scope:U.string().optional().describe("Scope (e.g. domain area)"),tags:U.array(U.string()).optional(),importance:U.enum(["low","normal","high","critical"]).optional().default("normal"),project:Bw})},{name:"task_list",description:"List active tasks \u2014 compact layer-1 index. Does NOT include body/comments.",inputSchema:U.object({project:Bw,status:U.enum(["todo","doing","review","changes_requested","blocked"]).optional(),limit:U.number().int().min(1).max(50).optional().default(20)})},{name:"task_get",description:"Fetch full details of specific tasks by IDs (body, comments, full history).",inputSchema:U.object({ids:U.array(U.string()).min(1).max(10)})},{name:"task_create",description:"Create a new task.",inputSchema:U.object({title:U.string(),body:U.string().optional(),project:Bw,priority:U.enum(["low","normal","high","critical"]).optional().default("normal"),author:U.string().optional().default("agent")})},{name:"task_update",description:"Update task status, priority, or body.",inputSchema:U.object({id:U.string(),status:U.enum(["todo","doing","review","changes_requested","blocked","done","cancelled"]).optional(),body:U.string().optional(),priority:U.enum(["low","normal","high","critical"]).optional()})},{name:"task_submit_review",description:"Submit task for human review (HITL checkpoint). Sets status=review, sends Telegram card if configured.",inputSchema:U.object({id:U.string(),summary:U.string().describe("Summary of work done for the reviewer")})},{name:"task_check_review",description:"Poll HITL review result. Returns: pending | approved | changes_requested + comment.",inputSchema:U.object({id:U.string()})},{name:"task_batch_create",description:"Create multiple tasks with dependency links atomically. Use for PRD-to-task workflows. Each task has a 'ref' (temporary ID like 'T1') used to express dependencies between tasks in the batch.",inputSchema:U.object({tasks:U.array(U.object({ref:U.string().describe("Temporary reference ID, e.g. 'T1'"),title:U.string(),body:U.string().optional(),priority:U.enum(["low","normal","high","critical"]).optional().default("normal"),depends_on:U.array(U.string()).optional().describe("Refs of tasks that block this one"),subtask_of:U.string().optional().describe("Ref of parent task")})).min(1).max(100),project:Bw,author:U.string().optional().default("agent")})},{name:"search",description:"Unified search across tasks and memories. Returns mixed results with resource_type indicator. Use instead of separate memory_search + task_search calls.",inputSchema:U.object({query:U.string().describe("Search query"),resources:U.array(U.enum(["tasks","memories"])).optional().default(["tasks","memories"]),project:Bw,limit:U.number().int().min(1).max(20).optional().default(10)})},{name:"job_list",description:"List all jobs with last run status.",inputSchema:U.object({limit:U.number().int().optional().default(20),project:Bw})},{name:"job_run",description:"Trigger a job by name.",inputSchema:U.object({name:U.string()})},{name:"job_status",description:"Get run status + exit code + error for a specific run ID.",inputSchema:U.object({run_id:U.string()})},{name:"context",description:"Compact context index \u2014 active tasks + important memories. ~200 tokens. Call at session start. "+"Pass project name to scope, or omit to use activeProject from config. Use task_get or memory_get to drill into specific items.",inputSchema:U.object({project:Bw})},{name:"session_event",description:"Record a session event (file edit, decision, error, git op) for continuity across compaction. Duplicate events are silently deduped. Priority: 1=critical (file/task/rule), 2=high (git/env/error/decision), 3=normal, 4=low.",inputSchema:U.object({session_id:U.string().optional(),type:U.enum(["file","task","decision","error","git","env","intent","rule","plan","subagent"]),priority:U.number().int().min(1).max(4).optional().default(3),data:U.record(U.string()).describe("Event payload \u2014 tool, path, content, etc.")})},{name:"session_snapshot",description:"Build \u22642KB XML snapshot of current session state. Call from PreCompact hook before context window compacts.",inputSchema:U.object({session_id:U.string().optional()})},{name:"session_restore",description:"Restore session state after compaction or agent restart. Returns structured Session Guide.",inputSchema:U.object({session_id:U.string().optional()})},{name:"session_log",description:"Log a session summary after completing a unit of work. Auto-derives touched files, task changes, and stored memories from session events.",inputSchema:U.object({agent:U.string(),agent_version:U.string().optional().describe("Agent version string, e.g. 'claude-code/1.x'"),summary:U.string(),session_id:U.string().optional(),project:Bw})},{name:"project_list",description:"List all projects. Returns name, status, and description for each.",inputSchema:U.object({status:U.enum(["active","archived","paused"]).optional()})}];aF=new Set(["file","task","rule"]),eF=new Set(["decision","git","env","error","plan"])});var z9,X_;var wj=R(()=>{N1();x1();oA();z9=new p0,X_=m({method:"post",path:"/mcp/tool",tags:["MCP"],summary:"Execute an MCP tool by name \u2014 used by hook scripts",request:{body:{content:{"application/json":{schema:U.object({name:U.string().min(1),args:U.record(U.unknown()).optional().default({})}).openapi("McpToolCall")}}}},responses:{200:{description:"Tool result",content:{"application/json":{schema:U.object({result:U.string()}).openapi("McpToolResult")}}}}});z9.openapi(X_,async($)=>{let{name:w,args:E}=$.req.valid("json"),X=qX.find((A)=>A.name===w);if(!X)throw new Ew(`Unknown MCP tool: ${w}`);let G=X.inputSchema.safeParse(E??{});if(!G.success)throw new Ew(`Invalid args: ${G.error.message}`);let J=await D6(w,G.data);return $.json({result:J})})});function Ej($){return{id:$.id,title:$.title??null,type:$.type??"fact",content:$.content,source:$.source,scope:$.scope,project_id:$.project_id??null,tags:$.tags?JSON.parse($.tags):null,importance:$.importance,expires_at:$.expires_at?new Date($.expires_at*1000).toISOString():null,created_at:new Date($.created_at*1000).toISOString(),updated_at:new Date($.updated_at*1000).toISOString()}}function W_($){return{id:$.id,title:$.title??null,type:$.type??"fact",content:$.content,source:$.source??null,scope:$.scope??null,project_id:$.project_id??null,tags:$.tags??null,importance:$.importance,expires_at:$.expires_at?.toISOString()??null,created_at:$.created_at.toISOString(),updated_at:$.updated_at.toISOString()}}var SX,tA,B9,G_,J_,A_,D_,N_,T9=`m.id, m.title, m.type, m.content, m.source, m.scope, m.project_id, m.tags,
|
|
511
|
+
m.importance, m.expires_at, m.created_at, m.updated_at`;var Xj=R(()=>{N1();x1();X1();y$();d$();i$();SX=new p0,tA=U.enum(["fact","decision","event","rule","discovery"]),B9=U.object({id:U.string(),title:U.string().nullable(),type:tA,content:U.string(),source:U.string().nullable(),scope:U.string().nullable(),project_id:U.string().nullable(),tags:U.array(U.string()).nullable(),importance:U.enum(["low","normal","high","critical"]),expires_at:U.string().datetime().nullable(),created_at:U.string().datetime(),updated_at:U.string().datetime()}).openapi("Memory"),G_=U.object({content:U.string().min(1),title:U.string().optional(),type:tA.optional().default("fact"),source:U.string().optional(),scope:U.string().optional(),project_id:U.string().optional(),tags:U.array(U.string()).optional(),importance:U.enum(["low","normal","high","critical"]).optional().default("normal"),expires_at:U.string().datetime().optional()}).openapi("CreateMemory"),J_=m({method:"get",path:"/memories/search",tags:["Memory"],summary:"Search memories (3-layer BM25: porter \u2192 trigram \u2192 fallback)",request:{query:U.object({q:U.string().min(1),scope:U.string().optional(),type:tA.optional(),project_id:U.string().optional(),limit:U.coerce.number().int().min(1).max(50).optional().default(10)})},responses:{200:{description:"Search results",content:{"application/json":{schema:U.object({results:U.array(B9)})}}}}}),A_=m({method:"get",path:"/memories",tags:["Memory"],summary:"List memories",request:{query:U.object({scope:U.string().optional(),type:tA.optional(),project_id:U.string().optional(),limit:U.coerce.number().int().min(1).max(100).optional().default(20)})},responses:{200:{description:"Memory list",content:{"application/json":{schema:U.object({memories:U.array(B9)})}}}}}),D_=m({method:"post",path:"/memories",tags:["Memory"],summary:"Store a memory",request:{body:{content:{"application/json":{schema:G_}}}},responses:{201:{description:"Created",content:{"application/json":{schema:B9}}}}}),N_=m({method:"delete",path:"/memories/{id}",tags:["Memory"],summary:"Delete memory",request:{params:U.object({id:U.string()})},responses:{204:{description:"Deleted"}}});SX.openapi(J_,async($)=>{let w=x(),{q:E,scope:X,type:G,project_id:J,limit:A}=$.req.valid("query"),D=w.$client,N=E.replace(/["]/g," ").trim(),W=X?" AND m.scope = ?":"",O=G?" AND m.type = ?":"",Y=J?" AND m.project_id = ?":"",H=[...X?[X]:[],...G?[G]:[],...J?[J]:[]],L=[],F=(B,Q)=>{try{return D.query(`SELECT ${T9} FROM ${B} f JOIN memories m ON m.id = f.id
|
|
512
|
+
WHERE f.${B} MATCH ?${W}${O}${Y} ORDER BY rank LIMIT ?`).all(Q,...H,A)}catch{return[]}},j=N.split(/\s+/).filter(Boolean),M=j.join(" AND "),z=j.join(" OR ");if(L=F("memories_fts",M),L.length===0)L=F("memories_fts",z);if(L.length===0)L=F("memories_fts_trigram",M);if(L.length===0)L=F("memories_fts_trigram",z);if(L.length===0){let B=[`%${N.toLowerCase()}%`,...H,A];L=D.query(`SELECT ${T9} FROM memories m
|
|
513
513
|
WHERE m.content LIKE ?${W}${O}${Y}
|
|
514
|
-
ORDER BY m.created_at DESC LIMIT ?`).all(...B)}return $.json({results:L.map(eF)})});qX.openapi(eC,async($)=>{let w=x(),{scope:E,type:X,project_id:G,limit:J}=$.req.valid("query"),A=w.$client,D=[],N=[];if(E)D.push("scope = ?"),N.push(E);if(X)D.push("type = ?"),N.push(X);if(G)D.push("project_id = ?"),N.push(G);N.push(J);let W=D.length?`WHERE ${D.join(" AND ")}`:"",O=A.query(`SELECT ${M9} FROM memories m ${W} ORDER BY m.created_at DESC LIMIT ?`).all(...N);return $.json({memories:O.map(eF)})});qX.openapi($_,async($)=>{let w=x(),E=$.req.valid("json"),X=new Date,G=i();await w.insert(H1).values({id:G,title:E.title,type:E.type??"fact",content:E.content,source:E.source,scope:E.scope,project_id:E.project_id,tags:E.tags,importance:E.importance,expires_at:E.expires_at?new Date(E.expires_at):void 0,created_at:X,updated_at:X});let J=await w.query.memories.findFirst({where:V(H1.id,G)});return $.json(E_(J),201)});qX.openapi(w_,async($)=>{let w=x(),{id:E}=$.req.valid("param");if(!await w.query.memories.findFirst({where:V(H1.id,E)}))throw new U0("Memory",E);return await w.delete(H1).where(V(H1.id,E)),new Response(null,{status:204})})});function D6($){return{...$,created_at:$.created_at.toISOString(),updated_at:$.updated_at.toISOString()}}function wj($){return{...$,tags:typeof $.tags==="string"?JSON.parse($.tags):$.tags,created_at:new Date($.created_at*1000).toISOString(),updated_at:new Date($.updated_at*1000).toISOString()}}function Xj($){return{...$,created_at:$.created_at.toISOString()}}var y1,SX,X_,G_,J_,A_,D_,N_,W_,O_,U_,Ej,Y_,H_;var Gj=R(()=>{N1();x1();X1();y$();d$();i$();y1=new p0,SX=U.object({id:U.string(),name:U.string(),description:U.string().nullable(),status:U.enum(["active","archived","paused"]),scope:U.string().nullable(),tags:U.array(U.string()).nullable(),obsidian_path:U.string().nullable(),created_at:U.string().datetime(),updated_at:U.string().datetime()}).openapi("Project"),X_=U.object({name:U.string().regex(/^[a-zA-Z0-9_-]+$/).min(1).max(100),description:U.string().optional(),status:U.enum(["active","archived","paused"]).optional().default("active"),scope:U.string().optional(),tags:U.array(U.string()).optional(),obsidian_path:U.string().optional()}).openapi("CreateProject"),G_=U.object({name:U.string().regex(/^[a-zA-Z0-9_-]+$/).min(1).max(100).optional(),description:U.string().optional(),status:U.enum(["active","archived","paused"]).optional(),scope:U.string().optional(),tags:U.array(U.string()).optional(),obsidian_path:U.string().optional()}).openapi("UpdateProject"),J_=m({method:"get",path:"/projects",tags:["Projects"],summary:"List projects",request:{query:U.object({status:U.enum(["active","archived","paused"]).optional(),tag:U.string().optional(),limit:U.coerce.number().int().min(1).max(100).optional().default(50)})},responses:{200:{description:"Projects",content:{"application/json":{schema:U.object({projects:U.array(SX)})}}}}}),A_=m({method:"get",path:"/projects/{id}",tags:["Projects"],summary:"Get project by ID",request:{params:U.object({id:U.string()})},responses:{200:{description:"Project",content:{"application/json":{schema:SX}}}}}),D_=m({method:"post",path:"/projects",tags:["Projects"],summary:"Create project",request:{body:{content:{"application/json":{schema:X_}}}},responses:{201:{description:"Created",content:{"application/json":{schema:SX}}}}}),N_=m({method:"patch",path:"/projects/{id}",tags:["Projects"],summary:"Update project",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:G_}}}},responses:{200:{description:"Updated",content:{"application/json":{schema:SX}}}}}),W_=m({method:"delete",path:"/projects/{id}",tags:["Projects"],summary:"Delete project",request:{params:U.object({id:U.string()})},responses:{204:{description:"Deleted"}}}),O_=m({method:"get",path:"/projects/by-name/{name}",tags:["Projects"],summary:"Get project by name (case-insensitive)",request:{params:U.object({name:U.string()})},responses:{200:{description:"Project",content:{"application/json":{schema:SX}}}}}),U_=m({method:"get",path:"/projects/{id}/summary",tags:["Projects"],summary:"Get project summary with task/memory/job counts",request:{params:U.object({id:U.string()})},responses:{200:{description:"Project summary",content:{"application/json":{schema:U.object({project:SX,tasks:U.object({total:U.number(),by_status:U.record(U.number())}),memories:U.number(),jobs:U.number()})}}}}});y1.openapi(J_,async($)=>{let w=x(),{status:E,tag:X,limit:G}=$.req.valid("query");if(X){let D=w.$client,N="SELECT DISTINCT p.* FROM projects p, json_each(p.tags) AS j WHERE j.value = ?",W=[X];if(E)N+=" AND p.status = ?",W.push(E);N+=" ORDER BY p.name ASC LIMIT ?",W.push(G);let Y=D.query(N).all(...W).map(wj);return $.json({projects:Y})}let J=E?[V(n0.status,E)]:[],A=await w.query.projects.findMany({where:J.length>0?S0(...J):void 0,limit:G,orderBy:(D,{asc:N})=>[N(D.name)]});return $.json({projects:A.map(D6)})});y1.openapi(O_,async($)=>{let w=x(),{name:E}=$.req.valid("param"),G=w.$client.query("SELECT * FROM projects WHERE name = ? COLLATE NOCASE LIMIT 1").get(E);if(!G)throw new U0("Project",E);return $.json(wj(G))});y1.openapi(U_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=await w.query.projects.findFirst({where:V(n0.id,E)});if(!X)throw new U0("Project",E);let G=w.$client,J=G.query("SELECT status, COUNT(*) as count FROM tasks WHERE project_id = ? GROUP BY status").all(E),A={},D=0;for(let O of J)A[O.status]=O.count,D+=O.count;let N=G.query("SELECT COUNT(*) as count FROM memories WHERE project_id = ?").get(E)?.count??0,W=G.query("SELECT COUNT(*) as count FROM jobs WHERE project_id = ?").get(E)?.count??0;return $.json({project:D6(X),tasks:{total:D,by_status:A},memories:N,jobs:W})});y1.openapi(A_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=await w.query.projects.findFirst({where:V(n0.id,E)});if(!X)throw new U0("Project",E);return $.json(D6(X))});y1.openapi(D_,async($)=>{let w=x(),E=$.req.valid("json"),X=new Date,G=i();await w.insert(n0).values({id:G,name:E.name,description:E.description,status:E.status,scope:E.scope,tags:E.tags,obsidian_path:E.obsidian_path,created_at:X,updated_at:X});let J=await w.query.projects.findFirst({where:V(n0.id,G)});if(!J)throw Error("Expected project to exist after write");return $.json(D6(J),201)});y1.openapi(N_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=$.req.valid("json");if(!await w.query.projects.findFirst({where:V(n0.id,E)}))throw new U0("Project",E);await w.update(n0).set({...X.name!==void 0?{name:X.name}:{},...X.description!==void 0?{description:X.description}:{},...X.status!==void 0?{status:X.status}:{},...X.scope!==void 0?{scope:X.scope}:{},...X.tags!==void 0?{tags:X.tags}:{},...X.obsidian_path!==void 0?{obsidian_path:X.obsidian_path}:{},updated_at:new Date}).where(V(n0.id,E));let J=await w.query.projects.findFirst({where:V(n0.id,E)});if(!J)throw Error("Expected updated to exist after write");return $.json(D6(J))});y1.openapi(W_,async($)=>{let w=x(),{id:E}=$.req.valid("param");if(!await w.query.projects.findFirst({where:V(n0.id,E)}))throw new U0("Project",E);return await w.delete(n0).where(V(n0.id,E)),new Response(null,{status:204})});Ej=U.object({id:U.string(),resource_type:U.string(),resource_id:U.string(),content:U.string(),author:U.string(),created_at:U.string().datetime()}).openapi("ProjectComment"),Y_=m({method:"get",path:"/projects/{id}/comments",tags:["Projects"],summary:"List project comments",request:{params:U.object({id:U.string()})},responses:{200:{description:"Comments",content:{"application/json":{schema:U.object({comments:U.array(Ej)})}}}}}),H_=m({method:"post",path:"/projects/{id}/comments",tags:["Projects"],summary:"Add a comment to a project",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:U.object({content:U.string().min(1),author:U.string().optional().default("human")}).openapi("AddProjectComment")}}}},responses:{201:{description:"Comment added",content:{"application/json":{schema:Ej}}}}});y1.openapi(Y_,async($)=>{let w=x(),{id:E}=$.req.valid("param");if(!await w.query.projects.findFirst({where:V(n0.id,E)}))throw new U0("Project",E);let G=await w.query.comments.findMany({where:S0(V(G$.resource_type,"project"),V(G$.resource_id,E)),orderBy:[x0(G$.created_at)]});return $.json({comments:G.map(Xj)})});y1.openapi(H_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),{content:X,author:G}=$.req.valid("json");if(!await w.query.projects.findFirst({where:V(n0.id,E)}))throw new U0("Project",E);let A=i(),D=new Date;await w.insert(G$).values({id:A,resource_type:"project",resource_id:E,content:X,author:G,created_at:D});let N=await w.query.comments.findFirst({where:V(G$.id,A)});if(!N)throw Error("Expected comment to exist after write");return $.json(Xj(N),201)})});function tA($){return{...$,last_used_at:$.last_used_at?.toISOString()??null,created_at:$.created_at.toISOString(),updated_at:$.updated_at.toISOString()}}function V_($,w){return $.replace(/\{\{(\w+)\}\}/g,(E,X)=>w[X]??`{{${X}}}`)}function P_($){return{...$,changed_at:$.changed_at.toISOString()}}var Iw,oA,L_,F_,j_,M_,R_,z_,T_,B_,Q_,I_,K_;var Jj=R(()=>{N1();x1();X1();y$();d$();i$();Iw=new p0,oA=U.object({id:U.string(),name:U.string(),description:U.string().nullable(),template:U.string(),is_skill:U.boolean(),skill_dir:U.string().nullable(),skill_version:U.string().nullable(),tags:U.array(U.string()).nullable(),version:U.number(),pinned:U.boolean(),last_used_at:U.string().datetime().nullable(),created_at:U.string().datetime(),updated_at:U.string().datetime()}).openapi("Prompt"),L_=U.object({name:U.string().min(1).max(200),description:U.string().optional(),template:U.string().min(1),is_skill:U.boolean().optional().default(!1),skill_dir:U.string().optional(),skill_version:U.string().optional(),tags:U.array(U.string()).optional(),pinned:U.boolean().optional().default(!1)}).openapi("CreatePrompt"),F_=U.object({name:U.string().min(1).max(200).optional(),description:U.string().optional(),template:U.string().min(1).optional(),is_skill:U.boolean().optional(),skill_dir:U.string().optional(),skill_version:U.string().optional(),tags:U.array(U.string()).optional(),pinned:U.boolean().optional()}).openapi("UpdatePrompt"),j_=U.object({vars:U.record(U.string()).optional().default({})}).openapi("RenderPrompt"),M_=m({method:"get",path:"/prompts",tags:["Prompts"],summary:"List prompts",request:{query:U.object({is_skill:U.coerce.boolean().optional(),limit:U.coerce.number().int().min(1).max(100).optional().default(50)})},responses:{200:{description:"Prompts",content:{"application/json":{schema:U.object({prompts:U.array(oA)})}}}}}),R_=m({method:"get",path:"/prompts/{id}",tags:["Prompts"],summary:"Get prompt by ID",request:{params:U.object({id:U.string()})},responses:{200:{description:"Prompt",content:{"application/json":{schema:oA}}}}}),z_=m({method:"post",path:"/prompts",tags:["Prompts"],summary:"Create prompt",request:{body:{content:{"application/json":{schema:L_}}}},responses:{201:{description:"Created",content:{"application/json":{schema:oA}}}}}),T_=m({method:"patch",path:"/prompts/{id}",tags:["Prompts"],summary:"Update prompt (bumps version)",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:F_}}}},responses:{200:{description:"Updated",content:{"application/json":{schema:oA}}}}}),B_=m({method:"delete",path:"/prompts/{id}",tags:["Prompts"],summary:"Delete prompt",request:{params:U.object({id:U.string()})},responses:{204:{description:"Deleted"}}}),Q_=m({method:"post",path:"/prompts/{id}/render",tags:["Prompts"],summary:"Render prompt with variable interpolation",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:j_}}}},responses:{200:{description:"Rendered",content:{"application/json":{schema:U.object({rendered:U.string(),prompt_id:U.string(),version:U.number()}).openapi("RenderedPrompt")}}}}}),I_=U.object({id:U.string(),prompt_id:U.string(),version:U.number(),name:U.string(),description:U.string().nullable(),template:U.string(),tags:U.array(U.string()).nullable(),changed_by:U.string(),changed_at:U.string().datetime()}).openapi("PromptHistoryEntry"),K_=m({method:"get",path:"/prompts/{id}/history",tags:["Prompts"],summary:"List prompt version history (newest first)",request:{params:U.object({id:U.string()}),query:U.object({limit:U.coerce.number().int().min(1).max(100).optional().default(20)})},responses:{200:{description:"History",content:{"application/json":{schema:U.object({history:U.array(I_)})}}}}});Iw.openapi(M_,async($)=>{let w=x(),{is_skill:E,limit:X}=$.req.valid("query"),G=await w.query.prompts.findMany({where:E!==void 0?V(D$.is_skill,E):void 0,limit:X,orderBy:(J,{asc:A})=>[A(J.name)]});return $.json({prompts:G.map(tA)})});Iw.openapi(R_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=await w.query.prompts.findFirst({where:V(D$.id,E)});if(!X)throw new U0("Prompt",E);return $.json(tA(X))});Iw.openapi(z_,async($)=>{let w=x(),E=$.req.valid("json"),X=new Date,G=i();await w.insert(D$).values({id:G,name:E.name,description:E.description,template:E.template,is_skill:E.is_skill,skill_dir:E.skill_dir,skill_version:E.skill_version,tags:E.tags,pinned:E.pinned,created_at:X,updated_at:X});let J=await w.query.prompts.findFirst({where:V(D$.id,G)});if(!J)throw Error("Expected prompt to exist after write");return $.json(tA(J),201)});Iw.openapi(T_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=$.req.valid("json"),G=await w.query.prompts.findFirst({where:V(D$.id,E)});if(!G)throw new U0("Prompt",E);await w.insert(bG).values({id:i(),prompt_id:G.id,version:G.version,name:G.name,description:G.description,template:G.template,tags:G.tags,changed_by:"human",changed_at:new Date}),await w.update(D$).set({...X.name!==void 0?{name:X.name}:{},...X.description!==void 0?{description:X.description}:{},...X.template!==void 0?{template:X.template}:{},...X.is_skill!==void 0?{is_skill:X.is_skill}:{},...X.skill_dir!==void 0?{skill_dir:X.skill_dir}:{},...X.skill_version!==void 0?{skill_version:X.skill_version}:{},...X.tags!==void 0?{tags:X.tags}:{},...X.pinned!==void 0?{pinned:X.pinned}:{},version:G.version+1,updated_at:new Date}).where(V(D$.id,E));let J=await w.query.prompts.findFirst({where:V(D$.id,E)});if(!J)throw Error("Expected updated to exist after write");return $.json(tA(J))});Iw.openapi(B_,async($)=>{let w=x(),{id:E}=$.req.valid("param");if(!await w.query.prompts.findFirst({where:V(D$.id,E)}))throw new U0("Prompt",E);return await w.delete(D$).where(V(D$.id,E)),new Response(null,{status:204})});Iw.openapi(Q_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),{vars:X}=$.req.valid("json"),G=await w.query.prompts.findFirst({where:V(D$.id,E)});if(!G)throw new U0("Prompt",E);return await w.update(D$).set({last_used_at:new Date}).where(V(D$.id,E)),$.json({rendered:V_(G.template,X??{}),prompt_id:G.id,version:G.version})});Iw.openapi(K_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),{limit:X}=$.req.valid("query");if(!await w.query.prompts.findFirst({where:V(D$.id,E)}))throw new U0("Prompt",E);let J=await w.query.prompt_history.findMany({where:V(bG.prompt_id,E),limit:X,orderBy:[x0(bG.version)]});return $.json({history:J.map(P_)})})});function Dj($){return{id:$.id,agent:$.agent,agent_version:$.agent_version??null,project_id:$.project_id??null,job_run_id:$.job_run_id??null,summary:$.summary??null,tokens_used:$.tokens_used??null,created_at:$.created_at.toISOString()}}var iA,Aj,q_,S_,k_;var Nj=R(()=>{N1();x1();y$();d$();i$();iA=new p0,Aj=U.object({id:U.string(),agent:U.string(),agent_version:U.string().nullable(),project_id:U.string().nullable(),job_run_id:U.string().nullable(),summary:U.string().nullable(),tokens_used:U.number().nullable(),created_at:U.string().datetime()}).openapi("Session"),q_=Aj.extend({events:U.array(U.object({id:U.string(),type:U.string(),priority:U.number(),data:U.string(),created_at:U.string().datetime()})),snapshot:U.string().nullable()}).openapi("SessionDetail"),S_=m({method:"get",path:"/sessions",tags:["Sessions"],summary:"List recent sessions",request:{query:U.object({agent:U.string().optional(),job_run_id:U.string().optional(),limit:U.coerce.number().int().min(1).max(100).optional().default(20)})},responses:{200:{description:"Sessions list",content:{"application/json":{schema:U.object({sessions:U.array(Aj)})}}}}}),k_=m({method:"get",path:"/sessions/{id}",tags:["Sessions"],summary:"Get session detail with events",request:{params:U.object({id:U.string()})},responses:{200:{description:"Session detail",content:{"application/json":{schema:q_}}},404:{description:"Not found"}}});iA.openapi(S_,async($)=>{let w=x(),{agent:E,job_run_id:X,limit:G}=$.req.valid("query"),J=[];if(E)J.push(V(C1.agent,E));if(X)J.push(V(C1.job_run_id,X));let A=await w.query.sessions.findMany({limit:G,orderBy:[x0(C1.created_at)],where:J.length>0?S0(...J):void 0});return $.json({sessions:A.map(Dj)})});iA.openapi(k_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=await w.query.sessions.findFirst({where:V(C1.id,E)});if(!X)throw new U0("Session",E);let G=w.$client,J=G.query(`SELECT id, type, priority, data, created_at
|
|
514
|
+
ORDER BY m.created_at DESC LIMIT ?`).all(...B)}return $.json({results:L.map(Ej)})});SX.openapi(A_,async($)=>{let w=x(),{scope:E,type:X,project_id:G,limit:J}=$.req.valid("query"),A=w.$client,D=[],N=[];if(E)D.push("scope = ?"),N.push(E);if(X)D.push("type = ?"),N.push(X);if(G)D.push("project_id = ?"),N.push(G);N.push(J);let W=D.length?`WHERE ${D.join(" AND ")}`:"",O=A.query(`SELECT ${T9} FROM memories m ${W} ORDER BY m.created_at DESC LIMIT ?`).all(...N);return $.json({memories:O.map(Ej)})});SX.openapi(D_,async($)=>{let w=x(),E=$.req.valid("json"),X=new Date,G=i();await w.insert(H1).values({id:G,title:E.title,type:E.type??"fact",content:E.content,source:E.source,scope:E.scope,project_id:E.project_id,tags:E.tags,importance:E.importance,expires_at:E.expires_at?new Date(E.expires_at):void 0,created_at:X,updated_at:X});let J=await w.query.memories.findFirst({where:V(H1.id,G)});return $.json(W_(J),201)});SX.openapi(N_,async($)=>{let w=x(),{id:E}=$.req.valid("param");if(!await w.query.memories.findFirst({where:V(H1.id,E)}))throw new U0("Memory",E);return await w.delete(H1).where(V(H1.id,E)),new Response(null,{status:204})})});function N6($){return{...$,created_at:$.created_at.toISOString(),updated_at:$.updated_at.toISOString()}}function Gj($){return{...$,tags:typeof $.tags==="string"?JSON.parse($.tags):$.tags,created_at:new Date($.created_at*1000).toISOString(),updated_at:new Date($.updated_at*1000).toISOString()}}function Aj($){return{...$,created_at:$.created_at.toISOString()}}var y1,kX,O_,U_,Y_,H_,L_,F_,j_,M_,R_,Jj,z_,T_;var Dj=R(()=>{N1();x1();X1();y$();d$();i$();y1=new p0,kX=U.object({id:U.string(),name:U.string(),description:U.string().nullable(),status:U.enum(["active","archived","paused"]),scope:U.string().nullable(),tags:U.array(U.string()).nullable(),obsidian_path:U.string().nullable(),created_at:U.string().datetime(),updated_at:U.string().datetime()}).openapi("Project"),O_=U.object({name:U.string().regex(/^[a-zA-Z0-9_-]+$/).min(1).max(100),description:U.string().optional(),status:U.enum(["active","archived","paused"]).optional().default("active"),scope:U.string().optional(),tags:U.array(U.string()).optional(),obsidian_path:U.string().optional()}).openapi("CreateProject"),U_=U.object({name:U.string().regex(/^[a-zA-Z0-9_-]+$/).min(1).max(100).optional(),description:U.string().optional(),status:U.enum(["active","archived","paused"]).optional(),scope:U.string().optional(),tags:U.array(U.string()).optional(),obsidian_path:U.string().optional()}).openapi("UpdateProject"),Y_=m({method:"get",path:"/projects",tags:["Projects"],summary:"List projects",request:{query:U.object({status:U.enum(["active","archived","paused"]).optional(),tag:U.string().optional(),limit:U.coerce.number().int().min(1).max(100).optional().default(50)})},responses:{200:{description:"Projects",content:{"application/json":{schema:U.object({projects:U.array(kX)})}}}}}),H_=m({method:"get",path:"/projects/{id}",tags:["Projects"],summary:"Get project by ID",request:{params:U.object({id:U.string()})},responses:{200:{description:"Project",content:{"application/json":{schema:kX}}}}}),L_=m({method:"post",path:"/projects",tags:["Projects"],summary:"Create project",request:{body:{content:{"application/json":{schema:O_}}}},responses:{201:{description:"Created",content:{"application/json":{schema:kX}}}}}),F_=m({method:"patch",path:"/projects/{id}",tags:["Projects"],summary:"Update project",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:U_}}}},responses:{200:{description:"Updated",content:{"application/json":{schema:kX}}}}}),j_=m({method:"delete",path:"/projects/{id}",tags:["Projects"],summary:"Delete project",request:{params:U.object({id:U.string()})},responses:{204:{description:"Deleted"}}}),M_=m({method:"get",path:"/projects/by-name/{name}",tags:["Projects"],summary:"Get project by name (case-insensitive)",request:{params:U.object({name:U.string()})},responses:{200:{description:"Project",content:{"application/json":{schema:kX}}}}}),R_=m({method:"get",path:"/projects/{id}/summary",tags:["Projects"],summary:"Get project summary with task/memory/job counts",request:{params:U.object({id:U.string()})},responses:{200:{description:"Project summary",content:{"application/json":{schema:U.object({project:kX,tasks:U.object({total:U.number(),by_status:U.record(U.number())}),memories:U.number(),jobs:U.number()})}}}}});y1.openapi(Y_,async($)=>{let w=x(),{status:E,tag:X,limit:G}=$.req.valid("query");if(X){let D=w.$client,N="SELECT DISTINCT p.* FROM projects p, json_each(p.tags) AS j WHERE j.value = ?",W=[X];if(E)N+=" AND p.status = ?",W.push(E);N+=" ORDER BY p.name ASC LIMIT ?",W.push(G);let Y=D.query(N).all(...W).map(Gj);return $.json({projects:Y})}let J=E?[V(n0.status,E)]:[],A=await w.query.projects.findMany({where:J.length>0?S0(...J):void 0,limit:G,orderBy:(D,{asc:N})=>[N(D.name)]});return $.json({projects:A.map(N6)})});y1.openapi(M_,async($)=>{let w=x(),{name:E}=$.req.valid("param"),G=w.$client.query("SELECT * FROM projects WHERE name = ? COLLATE NOCASE LIMIT 1").get(E);if(!G)throw new U0("Project",E);return $.json(Gj(G))});y1.openapi(R_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=await w.query.projects.findFirst({where:V(n0.id,E)});if(!X)throw new U0("Project",E);let G=w.$client,J=G.query("SELECT status, COUNT(*) as count FROM tasks WHERE project_id = ? GROUP BY status").all(E),A={},D=0;for(let O of J)A[O.status]=O.count,D+=O.count;let N=G.query("SELECT COUNT(*) as count FROM memories WHERE project_id = ?").get(E)?.count??0,W=G.query("SELECT COUNT(*) as count FROM jobs WHERE project_id = ?").get(E)?.count??0;return $.json({project:N6(X),tasks:{total:D,by_status:A},memories:N,jobs:W})});y1.openapi(H_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=await w.query.projects.findFirst({where:V(n0.id,E)});if(!X)throw new U0("Project",E);return $.json(N6(X))});y1.openapi(L_,async($)=>{let w=x(),E=$.req.valid("json"),X=new Date,G=i();await w.insert(n0).values({id:G,name:E.name,description:E.description,status:E.status,scope:E.scope,tags:E.tags,obsidian_path:E.obsidian_path,created_at:X,updated_at:X});let J=await w.query.projects.findFirst({where:V(n0.id,G)});if(!J)throw Error("Expected project to exist after write");return $.json(N6(J),201)});y1.openapi(F_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=$.req.valid("json");if(!await w.query.projects.findFirst({where:V(n0.id,E)}))throw new U0("Project",E);await w.update(n0).set({...X.name!==void 0?{name:X.name}:{},...X.description!==void 0?{description:X.description}:{},...X.status!==void 0?{status:X.status}:{},...X.scope!==void 0?{scope:X.scope}:{},...X.tags!==void 0?{tags:X.tags}:{},...X.obsidian_path!==void 0?{obsidian_path:X.obsidian_path}:{},updated_at:new Date}).where(V(n0.id,E));let J=await w.query.projects.findFirst({where:V(n0.id,E)});if(!J)throw Error("Expected updated to exist after write");return $.json(N6(J))});y1.openapi(j_,async($)=>{let w=x(),{id:E}=$.req.valid("param");if(!await w.query.projects.findFirst({where:V(n0.id,E)}))throw new U0("Project",E);return await w.delete(n0).where(V(n0.id,E)),new Response(null,{status:204})});Jj=U.object({id:U.string(),resource_type:U.string(),resource_id:U.string(),content:U.string(),author:U.string(),created_at:U.string().datetime()}).openapi("ProjectComment"),z_=m({method:"get",path:"/projects/{id}/comments",tags:["Projects"],summary:"List project comments",request:{params:U.object({id:U.string()})},responses:{200:{description:"Comments",content:{"application/json":{schema:U.object({comments:U.array(Jj)})}}}}}),T_=m({method:"post",path:"/projects/{id}/comments",tags:["Projects"],summary:"Add a comment to a project",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:U.object({content:U.string().min(1),author:U.string().optional().default("human")}).openapi("AddProjectComment")}}}},responses:{201:{description:"Comment added",content:{"application/json":{schema:Jj}}}}});y1.openapi(z_,async($)=>{let w=x(),{id:E}=$.req.valid("param");if(!await w.query.projects.findFirst({where:V(n0.id,E)}))throw new U0("Project",E);let G=await w.query.comments.findMany({where:S0(V(G$.resource_type,"project"),V(G$.resource_id,E)),orderBy:[x0(G$.created_at)]});return $.json({comments:G.map(Aj)})});y1.openapi(T_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),{content:X,author:G}=$.req.valid("json");if(!await w.query.projects.findFirst({where:V(n0.id,E)}))throw new U0("Project",E);let A=i(),D=new Date;await w.insert(G$).values({id:A,resource_type:"project",resource_id:E,content:X,author:G,created_at:D});let N=await w.query.comments.findFirst({where:V(G$.id,A)});if(!N)throw Error("Expected comment to exist after write");return $.json(Aj(N),201)})});function dA($){return{...$,last_used_at:$.last_used_at?.toISOString()??null,created_at:$.created_at.toISOString(),updated_at:$.updated_at.toISOString()}}function C_($,w){return $.replace(/\{\{(\w+)\}\}/g,(E,X)=>w[X]??`{{${X}}}`)}function __($){return{...$,changed_at:$.changed_at.toISOString()}}var Iw,iA,B_,Q_,I_,K_,V_,P_,q_,S_,k_,b_,Z_;var Nj=R(()=>{N1();x1();X1();y$();d$();i$();Iw=new p0,iA=U.object({id:U.string(),name:U.string(),description:U.string().nullable(),template:U.string(),is_skill:U.boolean(),skill_dir:U.string().nullable(),skill_version:U.string().nullable(),tags:U.array(U.string()).nullable(),version:U.number(),pinned:U.boolean(),last_used_at:U.string().datetime().nullable(),created_at:U.string().datetime(),updated_at:U.string().datetime()}).openapi("Prompt"),B_=U.object({name:U.string().min(1).max(200),description:U.string().optional(),template:U.string().min(1),is_skill:U.boolean().optional().default(!1),skill_dir:U.string().optional(),skill_version:U.string().optional(),tags:U.array(U.string()).optional(),pinned:U.boolean().optional().default(!1)}).openapi("CreatePrompt"),Q_=U.object({name:U.string().min(1).max(200).optional(),description:U.string().optional(),template:U.string().min(1).optional(),is_skill:U.boolean().optional(),skill_dir:U.string().optional(),skill_version:U.string().optional(),tags:U.array(U.string()).optional(),pinned:U.boolean().optional()}).openapi("UpdatePrompt"),I_=U.object({vars:U.record(U.string()).optional().default({})}).openapi("RenderPrompt"),K_=m({method:"get",path:"/prompts",tags:["Prompts"],summary:"List prompts",request:{query:U.object({is_skill:U.coerce.boolean().optional(),limit:U.coerce.number().int().min(1).max(100).optional().default(50)})},responses:{200:{description:"Prompts",content:{"application/json":{schema:U.object({prompts:U.array(iA)})}}}}}),V_=m({method:"get",path:"/prompts/{id}",tags:["Prompts"],summary:"Get prompt by ID",request:{params:U.object({id:U.string()})},responses:{200:{description:"Prompt",content:{"application/json":{schema:iA}}}}}),P_=m({method:"post",path:"/prompts",tags:["Prompts"],summary:"Create prompt",request:{body:{content:{"application/json":{schema:B_}}}},responses:{201:{description:"Created",content:{"application/json":{schema:iA}}}}}),q_=m({method:"patch",path:"/prompts/{id}",tags:["Prompts"],summary:"Update prompt (bumps version)",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:Q_}}}},responses:{200:{description:"Updated",content:{"application/json":{schema:iA}}}}}),S_=m({method:"delete",path:"/prompts/{id}",tags:["Prompts"],summary:"Delete prompt",request:{params:U.object({id:U.string()})},responses:{204:{description:"Deleted"}}}),k_=m({method:"post",path:"/prompts/{id}/render",tags:["Prompts"],summary:"Render prompt with variable interpolation",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:I_}}}},responses:{200:{description:"Rendered",content:{"application/json":{schema:U.object({rendered:U.string(),prompt_id:U.string(),version:U.number()}).openapi("RenderedPrompt")}}}}}),b_=U.object({id:U.string(),prompt_id:U.string(),version:U.number(),name:U.string(),description:U.string().nullable(),template:U.string(),tags:U.array(U.string()).nullable(),changed_by:U.string(),changed_at:U.string().datetime()}).openapi("PromptHistoryEntry"),Z_=m({method:"get",path:"/prompts/{id}/history",tags:["Prompts"],summary:"List prompt version history (newest first)",request:{params:U.object({id:U.string()}),query:U.object({limit:U.coerce.number().int().min(1).max(100).optional().default(20)})},responses:{200:{description:"History",content:{"application/json":{schema:U.object({history:U.array(b_)})}}}}});Iw.openapi(K_,async($)=>{let w=x(),{is_skill:E,limit:X}=$.req.valid("query"),G=await w.query.prompts.findMany({where:E!==void 0?V(D$.is_skill,E):void 0,limit:X,orderBy:(J,{asc:A})=>[A(J.name)]});return $.json({prompts:G.map(dA)})});Iw.openapi(V_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=await w.query.prompts.findFirst({where:V(D$.id,E)});if(!X)throw new U0("Prompt",E);return $.json(dA(X))});Iw.openapi(P_,async($)=>{let w=x(),E=$.req.valid("json"),X=new Date,G=i();await w.insert(D$).values({id:G,name:E.name,description:E.description,template:E.template,is_skill:E.is_skill,skill_dir:E.skill_dir,skill_version:E.skill_version,tags:E.tags,pinned:E.pinned,created_at:X,updated_at:X});let J=await w.query.prompts.findFirst({where:V(D$.id,G)});if(!J)throw Error("Expected prompt to exist after write");return $.json(dA(J),201)});Iw.openapi(q_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=$.req.valid("json"),G=await w.query.prompts.findFirst({where:V(D$.id,E)});if(!G)throw new U0("Prompt",E);await w.insert(ZG).values({id:i(),prompt_id:G.id,version:G.version,name:G.name,description:G.description,template:G.template,tags:G.tags,changed_by:"human",changed_at:new Date}),await w.update(D$).set({...X.name!==void 0?{name:X.name}:{},...X.description!==void 0?{description:X.description}:{},...X.template!==void 0?{template:X.template}:{},...X.is_skill!==void 0?{is_skill:X.is_skill}:{},...X.skill_dir!==void 0?{skill_dir:X.skill_dir}:{},...X.skill_version!==void 0?{skill_version:X.skill_version}:{},...X.tags!==void 0?{tags:X.tags}:{},...X.pinned!==void 0?{pinned:X.pinned}:{},version:G.version+1,updated_at:new Date}).where(V(D$.id,E));let J=await w.query.prompts.findFirst({where:V(D$.id,E)});if(!J)throw Error("Expected updated to exist after write");return $.json(dA(J))});Iw.openapi(S_,async($)=>{let w=x(),{id:E}=$.req.valid("param");if(!await w.query.prompts.findFirst({where:V(D$.id,E)}))throw new U0("Prompt",E);return await w.delete(D$).where(V(D$.id,E)),new Response(null,{status:204})});Iw.openapi(k_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),{vars:X}=$.req.valid("json"),G=await w.query.prompts.findFirst({where:V(D$.id,E)});if(!G)throw new U0("Prompt",E);return await w.update(D$).set({last_used_at:new Date}).where(V(D$.id,E)),$.json({rendered:C_(G.template,X??{}),prompt_id:G.id,version:G.version})});Iw.openapi(Z_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),{limit:X}=$.req.valid("query");if(!await w.query.prompts.findFirst({where:V(D$.id,E)}))throw new U0("Prompt",E);let J=await w.query.prompt_history.findMany({where:V(ZG.prompt_id,E),limit:X,orderBy:[x0(ZG.version)]});return $.json({history:J.map(__)})})});function Oj($){return{id:$.id,agent:$.agent,agent_version:$.agent_version??null,project_id:$.project_id??null,job_run_id:$.job_run_id??null,summary:$.summary??null,tokens_used:$.tokens_used??null,created_at:$.created_at.toISOString()}}var lA,Wj,v_,f_,x_;var Uj=R(()=>{N1();x1();y$();d$();i$();lA=new p0,Wj=U.object({id:U.string(),agent:U.string(),agent_version:U.string().nullable(),project_id:U.string().nullable(),job_run_id:U.string().nullable(),summary:U.string().nullable(),tokens_used:U.number().nullable(),created_at:U.string().datetime()}).openapi("Session"),v_=Wj.extend({events:U.array(U.object({id:U.string(),type:U.string(),priority:U.number(),data:U.string(),created_at:U.string().datetime()})),snapshot:U.string().nullable()}).openapi("SessionDetail"),f_=m({method:"get",path:"/sessions",tags:["Sessions"],summary:"List recent sessions",request:{query:U.object({agent:U.string().optional(),job_run_id:U.string().optional(),limit:U.coerce.number().int().min(1).max(100).optional().default(20)})},responses:{200:{description:"Sessions list",content:{"application/json":{schema:U.object({sessions:U.array(Wj)})}}}}}),x_=m({method:"get",path:"/sessions/{id}",tags:["Sessions"],summary:"Get session detail with events",request:{params:U.object({id:U.string()})},responses:{200:{description:"Session detail",content:{"application/json":{schema:v_}}},404:{description:"Not found"}}});lA.openapi(f_,async($)=>{let w=x(),{agent:E,job_run_id:X,limit:G}=$.req.valid("query"),J=[];if(E)J.push(V(C1.agent,E));if(X)J.push(V(C1.job_run_id,X));let A=await w.query.sessions.findMany({limit:G,orderBy:[x0(C1.created_at)],where:J.length>0?S0(...J):void 0});return $.json({sessions:A.map(Oj)})});lA.openapi(x_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=await w.query.sessions.findFirst({where:V(C1.id,E)});if(!X)throw new U0("Session",E);let G=w.$client,J=G.query(`SELECT id, type, priority, data, created_at
|
|
515
515
|
FROM session_events WHERE session_id = ?
|
|
516
|
-
ORDER BY created_at ASC`).all(E),A=G.query("SELECT xml FROM session_snapshots WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(E);return $.json({...
|
|
516
|
+
ORDER BY created_at ASC`).all(E),A=G.query("SELECT xml FROM session_snapshots WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(E);return $.json({...Oj(X),snapshot:A?.xml??null,events:J.map((D)=>({id:D.id,type:D.type,priority:D.priority,data:D.data,created_at:new Date(D.created_at*1000).toISOString()}))})})});function g_(){return x().$client}var Q9,Yj,y_;var Hj=R(()=>{N1();y$();Q9=new p0,Yj={task:"tasks",project:"projects",memory:"memories",prompt:"prompts"},y_=m({method:"get",path:"/tags",tags:["Tags"],summary:"List unique tags across resources",request:{query:U.object({resource_type:U.enum(["task","project","memory","prompt"]).optional()})},responses:{200:{description:"Unique tags with counts",content:{"application/json":{schema:U.object({tags:U.array(U.object({name:U.string(),count:U.number(),resource_type:U.string()}))})}}}}});Q9.openapi(y_,async($)=>{let{resource_type:w}=$.req.valid("query"),E=g_(),X=w?[[w,Yj[w]]]:Object.entries(Yj),G=[];for(let[J,A]of X){let D=E.query(`SELECT j.value AS tag, COUNT(*) AS count
|
|
517
517
|
FROM ${A}, json_each(${A}.tags) AS j
|
|
518
518
|
WHERE ${A}.tags IS NOT NULL
|
|
519
519
|
GROUP BY j.value
|
|
520
|
-
ORDER BY count DESC, j.value ASC`).all();for(let N of D)G.push({name:N.tag,count:N.count,resource_type:J})}return $.json({tags:G})})});function
|
|
520
|
+
ORDER BY count DESC, j.value ASC`).all();for(let N of D)G.push({name:N.tag,count:N.count,resource_type:J})}return $.json({tags:G})})});function Fj($){return{...$,created_at:$.created_at.toISOString()}}var W6,Lj,u_,h_,c_,n_;var jj=R(()=>{N1();x1();X1();nA();y$();d$();i$();W6=new p0,Lj=U.object({id:U.string(),from_task_id:U.string(),to_task_id:U.string(),link_type:F9,created_at:U.string().datetime()}).openapi("TaskLink"),u_=U.object({to_task_id:U.string(),link_type:F9}).openapi("CreateTaskLink"),h_=m({method:"get",path:"/tasks/{id}/links",tags:["Tasks"],summary:"List links for a task (both directions)",request:{params:U.object({id:U.string()})},responses:{200:{description:"Links",content:{"application/json":{schema:U.object({links:U.array(Lj)})}}}}}),c_=m({method:"post",path:"/tasks/{id}/links",tags:["Tasks"],summary:"Link this task to another task",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:u_}}}},responses:{201:{description:"Created",content:{"application/json":{schema:Lj}}}}}),n_=m({method:"delete",path:"/tasks/{id}/links/{linkId}",tags:["Tasks"],summary:"Remove a task link",request:{params:U.object({id:U.string(),linkId:U.string()})},responses:{204:{description:"Deleted"}}});W6.openapi(h_,async($)=>{let w=x(),{id:E}=$.req.valid("param");if(!await w.query.tasks.findFirst({where:V(r.id,E)}))throw new U0("Task",E);let G=await w.query.task_links.findMany({where:VJ(V(f$.from_task_id,E),V(f$.to_task_id,E))});return $.json({links:G.map(Fj)})});W6.openapi(c_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),{to_task_id:X,link_type:G}=$.req.valid("json"),[J,A]=await Promise.all([w.query.tasks.findFirst({where:V(r.id,E)}),w.query.tasks.findFirst({where:V(r.id,X)})]);if(!J)throw new U0("Task",E);if(!A)throw new U0("Task",X);if(E===X)throw new Ew("Cannot link a task to itself");if(await w.query.task_links.findFirst({where:S0(V(f$.from_task_id,E),V(f$.to_task_id,X))}))throw new Ew("Link already exists between these tasks");let N=i();await w.insert(f$).values({id:N,from_task_id:E,to_task_id:X,link_type:G,created_at:new Date});let W=await w.query.task_links.findFirst({where:V(f$.id,N)});if(!W)throw Error("Expected link to exist after write");return $.json(Fj(W),201)});W6.openapi(n_,async($)=>{let w=x(),{id:E,linkId:X}=$.req.valid("param"),G=await w.query.task_links.findFirst({where:V(f$.id,X)});if(!G||G.from_task_id!==E&&G.to_task_id!==E)throw new U0("TaskLink",X);return await w.delete(f$).where(V(f$.id,X)),new Response(null,{status:204})})});function I9($,w){return $.query(`SELECT t.id, t.title, t.status
|
|
521
521
|
FROM task_links tl
|
|
522
522
|
JOIN tasks t ON t.id = tl.from_task_id
|
|
523
523
|
WHERE tl.to_task_id = ? AND tl.link_type = 'blocks'
|
|
@@ -527,7 +527,7 @@ ${X}
|
|
|
527
527
|
FROM task_links tl
|
|
528
528
|
JOIN tasks t ON t.id = tl.to_task_id
|
|
529
529
|
WHERE tl.from_task_id = ? AND tl.link_type = 'blocked_by'
|
|
530
|
-
AND t.status NOT IN ('done', 'cancelled')`).all(w,w)}function
|
|
530
|
+
AND t.status NOT IN ('done', 'cancelled')`).all(w,w)}function Mj($,w){let E=$.query(`SELECT DISTINCT dependent_id AS id FROM (
|
|
531
531
|
SELECT tl.to_task_id AS dependent_id
|
|
532
532
|
FROM task_links tl
|
|
533
533
|
WHERE tl.from_task_id = ? AND tl.link_type = 'blocks'
|
|
@@ -535,16 +535,16 @@ ${X}
|
|
|
535
535
|
SELECT tl.from_task_id AS dependent_id
|
|
536
536
|
FROM task_links tl
|
|
537
537
|
WHERE tl.to_task_id = ? AND tl.link_type = 'blocked_by'
|
|
538
|
-
)`).all(w,w),X=[];for(let{id:G}of E)if(
|
|
538
|
+
)`).all(w,w),X=[];for(let{id:G}of E)if(I9($,G).length===0){if($.query("SELECT status FROM tasks WHERE id = ?").get(G)?.status==="blocked")$.query("UPDATE tasks SET status = 'todo', updated_at = unixepoch() WHERE id = ?").run(G),X.push(G)}return X}function Rj($,w){let E=$.query(`SELECT tl.to_task_id FROM task_links tl
|
|
539
539
|
WHERE tl.from_task_id = ? AND tl.link_type = 'subtask_of'
|
|
540
540
|
LIMIT 1`).get(w);if(!E)return null;let X=E.to_task_id,G=$.query(`SELECT
|
|
541
541
|
COUNT(*) as total,
|
|
542
542
|
SUM(CASE WHEN t.status IN ('done', 'cancelled') THEN 1 ELSE 0 END) as done
|
|
543
543
|
FROM task_links tl
|
|
544
544
|
JOIN tasks t ON t.id = tl.from_task_id
|
|
545
|
-
WHERE tl.to_task_id = ? AND tl.link_type = 'subtask_of'`).get(X);if(!G||G.total===0)return null;let J=Math.round(G.done/G.total*100);if($.query("UPDATE tasks SET progress = ?, updated_at = unixepoch() WHERE id = ?").run(J,X),G.done===G.total){let A=$.query("SELECT status FROM tasks WHERE id = ?").get(X);if(A&&!["done","cancelled","review"].includes(A.status))$.query("UPDATE tasks SET status = 'review', updated_at = unixepoch() WHERE id = ?").run(X)}return X}function dA(){return x().$client}function O6($){return{...$,due_at:$.due_at?.toISOString()??null,claim_expires_at:$.claim_expires_at?.toISOString()??null,created_at:$.created_at.toISOString(),updated_at:$.updated_at.toISOString()}}function d_($){return{...$,tags:typeof $.tags==="string"?JSON.parse($.tags):$.tags,due_at:$.due_at?new Date($.due_at*1000).toISOString():null,claim_expires_at:$.claim_expires_at?new Date($.claim_expires_at*1000).toISOString():null,created_at:new Date($.created_at*1000).toISOString(),updated_at:new Date($.updated_at*1000).toISOString()}}function Mj($){return{...$,created_at:$.created_at.toISOString()}}var j1,W6,jj,x_,y_,g_,u_,h_,c_,n_,m_,r_,p_,o_,t_,i_;var Rj=R(()=>{N1();x1();X1();hA();y$();d$();i$();j1=new p0,W6=U.object({id:U.string(),project_id:U.string().nullable(),title:U.string(),body:U.string().nullable(),status:yA,priority:G6,progress:U.number().int(),due_at:U.string().datetime().nullable(),tags:U.array(U.string()).nullable(),author:U.string(),claimed_by:U.string().nullable(),claim_expires_at:U.string().datetime().nullable(),created_at:U.string().datetime(),updated_at:U.string().datetime()}).openapi("Task"),jj=U.object({id:U.string(),resource_type:U.string(),resource_id:U.string(),content:U.string(),author:U.string(),created_at:U.string().datetime()}).openapi("Comment"),x_=U.object({title:U.string().min(1).max(500),body:U.string().optional(),project_id:U.string().optional(),status:U.enum(["todo","doing","blocked"]).optional().default("todo"),priority:G6.optional().default("normal"),due_at:U.string().datetime().optional(),tags:U.array(U.string()).optional(),author:U.string().optional().default("human")}).openapi("CreateTask"),y_=U.object({title:U.string().min(1).max(500).optional(),body:U.string().optional(),status:yA.optional(),priority:G6.optional(),due_at:U.string().datetime().optional(),tags:U.array(U.string()).optional()}).openapi("UpdateTask"),g_=m({method:"get",path:"/tasks",tags:["Tasks"],summary:"List tasks",request:{query:U.object({project_id:U.string().optional(),status:yA.optional(),tag:U.string().optional(),limit:U.coerce.number().int().min(1).max(100).optional().default(50)})},responses:{200:{description:"Task list",content:{"application/json":{schema:U.object({tasks:U.array(W6),total:U.number()})}}}}}),u_=m({method:"get",path:"/tasks/{id}",tags:["Tasks"],summary:"Get task by ID",request:{params:U.object({id:U.string()})},responses:{200:{description:"Task",content:{"application/json":{schema:W6}}}}}),h_=m({method:"post",path:"/tasks",tags:["Tasks"],summary:"Create task",request:{body:{content:{"application/json":{schema:x_}}}},responses:{201:{description:"Created",content:{"application/json":{schema:W6}}}}}),c_=m({method:"patch",path:"/tasks/{id}",tags:["Tasks"],summary:"Update task",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:y_}}}},responses:{200:{description:"Updated",content:{"application/json":{schema:W6}}}}}),n_=m({method:"delete",path:"/tasks/{id}",tags:["Tasks"],summary:"Delete task",request:{params:U.object({id:U.string()})},responses:{204:{description:"Deleted"}}}),m_=U.object({ref:U.string().describe("Temporary reference ID for dependency linking, e.g. 'T1'"),title:U.string().min(1).max(500),body:U.string().optional(),priority:G6.optional().default("normal"),depends_on:U.array(U.string()).optional().describe("Refs of tasks that block this one"),subtask_of:U.string().optional().describe("Ref of parent task")}),r_=m({method:"post",path:"/tasks/batch",tags:["Tasks"],summary:"Create multiple tasks with dependency links atomically",request:{body:{content:{"application/json":{schema:U.object({tasks:U.array(m_).min(1).max(100),project_id:U.string().optional(),author:U.string().optional().default("agent")}).openapi("BatchCreateTasks")}}}},responses:{201:{description:"Created tasks with ref\u2192id mapping",content:{"application/json":{schema:U.object({created:U.number(),mapping:U.record(U.string(),U.string())})}}}}}),p_=m({method:"post",path:"/tasks/{id}/review",tags:["Tasks"],summary:"Submit task for human review (HITL checkpoint)",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:U.object({summary:U.string().min(1)}).openapi("SubmitReview")}}}},responses:{200:{description:"Submitted",content:{"application/json":{schema:W6}}}}}),o_=m({method:"get",path:"/tasks/{id}/review",tags:["Tasks"],summary:"Poll HITL review result",request:{params:U.object({id:U.string()})},responses:{200:{description:"Review status",content:{"application/json":{schema:U.object({status:U.enum(["review","approved","changes_requested","pending"]),comment:U.string().nullable()}).openapi("ReviewStatus")}}}}}),t_=m({method:"get",path:"/tasks/{id}/comments",tags:["Tasks"],summary:"List task comments",request:{params:U.object({id:U.string()})},responses:{200:{description:"Comments",content:{"application/json":{schema:U.object({comments:U.array(jj)})}}}}}),i_=m({method:"post",path:"/tasks/{id}/comments",tags:["Tasks"],summary:"Add a comment to a task",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:U.object({content:U.string().min(1),author:U.string().optional().default("human")}).openapi("AddComment")}}}},responses:{201:{description:"Comment added",content:{"application/json":{schema:jj}}}}});j1.openapi(g_,async($)=>{let w=x(),{project_id:E,status:X,tag:G,limit:J}=$.req.valid("query");if(G){let N=dA(),W="SELECT DISTINCT t.* FROM tasks t, json_each(t.tags) AS j WHERE j.value = ?",O=[G];if(E)W+=" AND t.project_id = ?",O.push(E);if(X)W+=" AND t.status = ?",O.push(X);W+=" ORDER BY t.updated_at DESC LIMIT ?",O.push(J);let Y=N.query(W).all(...O),H=Y.map(d_);return $.json({tasks:H,total:Y.length})}let A=[];if(E)A.push(V(r.project_id,E));if(X)A.push(V(r.status,X));let D=await w.query.tasks.findMany({where:A.length>0?S0(...A):void 0,limit:J,orderBy:[x0(r.updated_at)]});return $.json({tasks:D.map(O6),total:D.length})});j1.openapi(u_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=await w.query.tasks.findFirst({where:V(r.id,E)});if(!X)throw new U0("Task",E);return $.json(O6(X))});j1.openapi(h_,async($)=>{let w=x(),E=$.req.valid("json"),X=new Date,G=i();await w.insert(r).values({id:G,title:E.title,body:E.body,project_id:E.project_id,status:E.status,priority:E.priority,...E.due_at?{due_at:new Date(E.due_at)}:{},tags:E.tags,author:E.author,created_at:X,updated_at:X});let J=await w.query.tasks.findFirst({where:V(r.id,G)});if(!J)throw Error("Expected task to exist after write");return $.json(O6(J),201)});j1.openapi(c_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=$.req.valid("json"),G=await w.query.tasks.findFirst({where:V(r.id,E)});if(!G)throw new U0("Task",E);if(X.status==="doing"&&G.status!=="doing"){let A=T9(dA(),E);if(A.length>0){let D=A.map((N)=>`[${N.id.slice(-6)}] ${N.title}`).join(", ");throw new Ew(`Cannot start: blocked by ${D}`)}}if(await w.update(r).set({...X.title!==void 0?{title:X.title}:{},...X.body!==void 0?{body:X.body}:{},...X.status!==void 0?{status:X.status}:{},...X.priority!==void 0?{priority:X.priority}:{},...X.due_at!==void 0?{due_at:new Date(X.due_at)}:{},...X.tags!==void 0?{tags:X.tags}:{},updated_at:new Date}).where(V(r.id,E)),X.status&&["done","cancelled"].includes(X.status)){let A=dA();Lj(A,E),Fj(A,E)}let J=await w.query.tasks.findFirst({where:V(r.id,E)});if(!J)throw Error("Expected updated to exist after write");return $.json(O6(J))});j1.openapi(n_,async($)=>{let w=x(),{id:E}=$.req.valid("param");if(!await w.query.tasks.findFirst({where:V(r.id,E)}))throw new U0("Task",E);return await w.delete(r).where(V(r.id,E)),new Response(null,{status:204})});j1.openapi(p_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),{summary:X}=$.req.valid("json"),G=await w.query.tasks.findFirst({where:V(r.id,E)});if(!G)throw new U0("Task",E);if(!["doing","blocked"].includes(G.status))throw new Ew(`Task must be in doing/blocked to submit for review (current: ${G.status})`);let J=new Date;await w.update(r).set({status:"review",body:X,updated_at:J}).where(V(r.id,E)),await w.insert(G$).values({id:i(),resource_type:"task",resource_id:E,content:`[review submitted] ${X}`,author:"agent",created_at:J});let A=await w.query.tasks.findFirst({where:V(r.id,E)});if(!A)throw Error("Expected updated to exist after write");return $.json(O6(A))});j1.openapi(o_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=await w.query.tasks.findFirst({where:V(r.id,E)});if(!X)throw new U0("Task",E);let G=await w.query.comments.findFirst({where:S0(V(G$.resource_type,"task"),V(G$.resource_id,E),V(G$.author,"human")),orderBy:[x0(G$.created_at)]}),A={review:"review",done:"approved",changes_requested:"changes_requested"}[X.status]??"pending";return $.json({status:A,comment:G?.content??null})});j1.openapi(t_,async($)=>{let w=x(),{id:E}=$.req.valid("param");if(!await w.query.tasks.findFirst({where:V(r.id,E)}))throw new U0("Task",E);let G=await w.query.comments.findMany({where:S0(V(G$.resource_type,"task"),V(G$.resource_id,E)),orderBy:[x0(G$.created_at)]});return $.json({comments:G.map(Mj)})});j1.openapi(i_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),{content:X,author:G}=$.req.valid("json");if(!await w.query.tasks.findFirst({where:V(r.id,E)}))throw new U0("Task",E);let A=i(),D=new Date;await w.insert(G$).values({id:A,resource_type:"task",resource_id:E,content:X,author:G,created_at:D});let N=await w.query.comments.findFirst({where:V(G$.id,A)});if(!N)throw Error("Expected comment to exist after write");return $.json(Mj(N),201)});j1.openapi(r_,async($)=>{let w=x(),{tasks:E,project_id:X,author:G}=$.req.valid("json"),J=new Date,A={},D=dA();D.exec("BEGIN");try{for(let N of E){let W=i();A[N.ref]=W,await w.insert(r).values({id:W,title:N.title,body:N.body,project_id:X,priority:N.priority,author:G,status:"todo",created_at:J,updated_at:J})}for(let N of E){let W=A[N.ref];if(N.depends_on)for(let O of N.depends_on){let Y=A[O];if(!Y)continue;await w.insert(f$).values({id:i(),from_task_id:Y,to_task_id:W,link_type:"blocks",created_at:J})}if(N.subtask_of){let O=A[N.subtask_of];if(O)await w.insert(f$).values({id:i(),from_task_id:W,to_task_id:O,link_type:"subtask_of",created_at:J}),await w.insert(f$).values({id:i(),from_task_id:O,to_task_id:W,link_type:"parent_of",created_at:J})}}D.exec("COMMIT")}catch(N){throw D.exec("ROLLBACK"),N}return $.json({created:E.length,mapping:A},201)})});function zj(){let $=O0(),w=new p0;return w.use("*",gF($.api.secret)),w.onError((E,X)=>{let G=E instanceof VX?E:null;if(G)return X.json({error:G.message,code:G.code},G.statusCode);return l_.error("Unhandled error",E),X.json({error:"Internal server error",code:"INTERNAL_ERROR"},500)}),w.route("/",U9),w.route("/",j9),w.route("/",y1),w.route("/",Iw),w.route("/",j1),w.route("/",N6),w.route("/",qX),w.route("/",iA),w.route("/",Xw),w.route("/",xA),w.route("/",z9),w.doc("/openapi.json",{openapi:"3.1.0",info:{title:"Orc API",version:"0.0.1",description:"Human + AI Orchestration Hub API"},servers:[{url:`http://${$.api.host}:${$.api.port}`,description:"Local"}]}),w.get("/docs",T3({url:"/openapi.json"})),w}var l_;var Tj=R(()=>{B3();N1();C$();x1();p$();uF();hF();cF();mF();aF();$j();Gj();Jj();Nj();Oj();Hj();Rj();l_=Z0("api")});var Q9={};Ww(Q9,{app:()=>Bj});var B9,ow,Bj;var I9=R(()=>{C$();p$();Tj();B9=Z0("api"),ow=O0(),Bj=zj();Bun.serve({port:ow.api.port,hostname:ow.api.host,fetch:Bj.fetch});B9.info(`API server running on http://${ow.api.host}:${ow.api.port}`);B9.info(`OpenAPI spec: http://${ow.api.host}:${ow.api.port}/openapi.json`);B9.info(`Swagger UI: http://${ow.api.host}:${ow.api.port}/docs`)});function S($,w,E){function X(D,N){var W;Object.defineProperty(D,"_zod",{value:D._zod??{},enumerable:!1}),(W=D._zod).traits??(W.traits=new Set),D._zod.traits.add($),w(D,N);for(let O in A.prototype)if(!(O in D))Object.defineProperty(D,O,{value:A.prototype[O].bind(D)});D._zod.constr=A,D._zod.def=N}let G=E?.Parent??Object;class J extends G{}Object.defineProperty(J,"name",{value:$});function A(D){var N;let W=E?.Parent?new J:this;X(W,D),(N=W._zod).deferred??(N.deferred=[]);for(let O of W._zod.deferred)O();return W}return Object.defineProperty(A,"init",{value:X}),Object.defineProperty(A,Symbol.hasInstance,{value:(D)=>{if(E?.Parent&&D instanceof E.Parent)return!0;return D?._zod?.traits?.has($)}}),Object.defineProperty(A,"name",{value:$}),A}function R1($){if($)Object.assign(aA,$);return aA}var zG0,TG0,iw,aA;var bX=R(()=>{zG0=Object.freeze({status:"aborted"});TG0=Symbol("zod_brand");iw=class iw extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};aA={}});var B0={};Ww(B0,{unwrapMessage:()=>H6,stringifyPrimitive:()=>w4,required:()=>fv,randomString:()=>Pv,propertyKeyTypes:()=>f9,promiseAllObject:()=>Vv,primitiveTypes:()=>hj,prefixIssues:()=>Jw,pick:()=>bv,partial:()=>vv,optionalKeys:()=>x9,omit:()=>Zv,numKeys:()=>qv,nullish:()=>F6,normalizeParams:()=>l,merge:()=>_v,jsonStringifyReplacer:()=>Z9,joinValues:()=>eA,issue:()=>g9,isPlainObject:()=>CX,isObject:()=>ZX,getSizableOrigin:()=>nj,getParsedType:()=>Sv,getLengthableOrigin:()=>M6,getEnumValues:()=>b9,getElementAtPath:()=>Kv,floatSafeRemainder:()=>C9,finalizeIssue:()=>u1,extend:()=>Cv,escapeRegex:()=>dw,esc:()=>PE,defineLazy:()=>C0,createTransparentProxy:()=>kv,clone:()=>Gw,cleanRegex:()=>j6,cleanEnum:()=>xv,captureStackTrace:()=>$4,cached:()=>L6,assignProp:()=>_9,assertNotEqual:()=>Tv,assertNever:()=>Qv,assertIs:()=>Bv,assertEqual:()=>zv,assert:()=>Iv,allowsEval:()=>v9,aborted:()=>qE,NUMBER_FORMAT_RANGES:()=>y9,Class:()=>mj,BIGINT_FORMAT_RANGES:()=>cj});function zv($){return $}function Tv($){return $}function Bv($){}function Qv($){throw Error()}function Iv($){}function b9($){let w=Object.values($).filter((X)=>typeof X==="number");return Object.entries($).filter(([X,G])=>w.indexOf(+X)===-1).map(([X,G])=>G)}function eA($,w="|"){return $.map((E)=>w4(E)).join(w)}function Z9($,w){if(typeof w==="bigint")return w.toString();return w}function L6($){return{get value(){{let E=$();return Object.defineProperty(this,"value",{value:E}),E}throw Error("cached value already set")}}}function F6($){return $===null||$===void 0}function j6($){let w=$.startsWith("^")?1:0,E=$.endsWith("$")?$.length-1:$.length;return $.slice(w,E)}function C9($,w){let E=($.toString().split(".")[1]||"").length,X=(w.toString().split(".")[1]||"").length,G=E>X?E:X,J=Number.parseInt($.toFixed(G).replace(".","")),A=Number.parseInt(w.toFixed(G).replace(".",""));return J%A/10**G}function C0($,w,E){Object.defineProperty($,w,{get(){{let G=E();return $[w]=G,G}throw Error("cached value already set")},set(G){Object.defineProperty($,w,{value:G})},configurable:!0})}function _9($,w,E){Object.defineProperty($,w,{value:E,writable:!0,enumerable:!0,configurable:!0})}function Kv($,w){if(!w)return $;return w.reduce((E,X)=>E?.[X],$)}function Vv($){let w=Object.keys($),E=w.map((X)=>$[X]);return Promise.all(E).then((X)=>{let G={};for(let J=0;J<w.length;J++)G[w[J]]=X[J];return G})}function Pv($=10){let E="";for(let X=0;X<$;X++)E+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return E}function PE($){return JSON.stringify($)}function ZX($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function CX($){if(ZX($)===!1)return!1;let w=$.constructor;if(w===void 0)return!0;let E=w.prototype;if(ZX(E)===!1)return!1;if(Object.prototype.hasOwnProperty.call(E,"isPrototypeOf")===!1)return!1;return!0}function qv($){let w=0;for(let E in $)if(Object.prototype.hasOwnProperty.call($,E))w++;return w}function dw($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Gw($,w,E){let X=new $._zod.constr(w??$._zod.def);if(!w||E?.parent)X._zod.parent=$;return X}function l($){let w=$;if(!w)return{};if(typeof w==="string")return{error:()=>w};if(w?.message!==void 0){if(w?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");w.error=w.message}if(delete w.message,typeof w.error==="string")return{...w,error:()=>w.error};return w}function kv($){let w;return new Proxy({},{get(E,X,G){return w??(w=$()),Reflect.get(w,X,G)},set(E,X,G,J){return w??(w=$()),Reflect.set(w,X,G,J)},has(E,X){return w??(w=$()),Reflect.has(w,X)},deleteProperty(E,X){return w??(w=$()),Reflect.deleteProperty(w,X)},ownKeys(E){return w??(w=$()),Reflect.ownKeys(w)},getOwnPropertyDescriptor(E,X){return w??(w=$()),Reflect.getOwnPropertyDescriptor(w,X)},defineProperty(E,X,G){return w??(w=$()),Reflect.defineProperty(w,X,G)}})}function w4($){if(typeof $==="bigint")return $.toString()+"n";if(typeof $==="string")return`"${$}"`;return`${$}`}function x9($){return Object.keys($).filter((w)=>{return $[w]._zod.optin==="optional"&&$[w]._zod.optout==="optional"})}function bv($,w){let E={},X=$._zod.def;for(let G in w){if(!(G in X.shape))throw Error(`Unrecognized key: "${G}"`);if(!w[G])continue;E[G]=X.shape[G]}return Gw($,{...$._zod.def,shape:E,checks:[]})}function Zv($,w){let E={...$._zod.def.shape},X=$._zod.def;for(let G in w){if(!(G in X.shape))throw Error(`Unrecognized key: "${G}"`);if(!w[G])continue;delete E[G]}return Gw($,{...$._zod.def,shape:E,checks:[]})}function Cv($,w){if(!CX(w))throw Error("Invalid input to extend: expected a plain object");let E={...$._zod.def,get shape(){let X={...$._zod.def.shape,...w};return _9(this,"shape",X),X},checks:[]};return Gw($,E)}function _v($,w){return Gw($,{...$._zod.def,get shape(){let E={...$._zod.def.shape,...w._zod.def.shape};return _9(this,"shape",E),E},catchall:w._zod.def.catchall,checks:[]})}function vv($,w,E){let X=w._zod.def.shape,G={...X};if(E)for(let J in E){if(!(J in X))throw Error(`Unrecognized key: "${J}"`);if(!E[J])continue;G[J]=$?new $({type:"optional",innerType:X[J]}):X[J]}else for(let J in X)G[J]=$?new $({type:"optional",innerType:X[J]}):X[J];return Gw(w,{...w._zod.def,shape:G,checks:[]})}function fv($,w,E){let X=w._zod.def.shape,G={...X};if(E)for(let J in E){if(!(J in G))throw Error(`Unrecognized key: "${J}"`);if(!E[J])continue;G[J]=new $({type:"nonoptional",innerType:X[J]})}else for(let J in X)G[J]=new $({type:"nonoptional",innerType:X[J]});return Gw(w,{...w._zod.def,shape:G,checks:[]})}function qE($,w=0){for(let E=w;E<$.issues.length;E++)if($.issues[E]?.continue!==!0)return!0;return!1}function Jw($,w){return w.map((E)=>{var X;return(X=E).path??(X.path=[]),E.path.unshift($),E})}function H6($){return typeof $==="string"?$:$?.message}function u1($,w,E){let X={...$,path:$.path??[]};if(!$.message){let G=H6($.inst?._zod.def?.error?.($))??H6(w?.error?.($))??H6(E.customError?.($))??H6(E.localeError?.($))??"Invalid input";X.message=G}if(delete X.inst,delete X.continue,!w?.reportInput)delete X.input;return X}function nj($){if($ instanceof Set)return"set";if($ instanceof Map)return"map";if($ instanceof File)return"file";return"unknown"}function M6($){if(Array.isArray($))return"array";if(typeof $==="string")return"string";return"unknown"}function g9(...$){let[w,E,X]=$;if(typeof w==="string")return{message:w,code:"custom",input:E,inst:X};return{...w}}function xv($){return Object.entries($).filter(([w,E])=>{return Number.isNaN(Number.parseInt(w,10))}).map((w)=>w[1])}class mj{constructor(...$){}}var $4,v9,Sv=($)=>{let w=typeof $;switch(w){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN($)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray($))return"array";if($===null)return"null";if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return"promise";if(typeof Map<"u"&&$ instanceof Map)return"map";if(typeof Set<"u"&&$ instanceof Set)return"set";if(typeof Date<"u"&&$ instanceof Date)return"date";if(typeof File<"u"&&$ instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${w}`)}},f9,hj,y9,cj;var Kw=R(()=>{$4=Error.captureStackTrace?Error.captureStackTrace:(...$)=>{};v9=L6(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch($){return!1}});f9=new Set(["string","number","symbol"]),hj=new Set(["string","number","bigint","boolean","symbol","undefined"]);y9={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},cj={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]}});function pj($,w=(E)=>E.message){let E={},X=[];for(let G of $.issues)if(G.path.length>0)E[G.path[0]]=E[G.path[0]]||[],E[G.path[0]].push(w(G));else X.push(w(G));return{formErrors:X,fieldErrors:E}}function oj($,w){let E=w||function(J){return J.message},X={_errors:[]},G=(J)=>{for(let A of J.issues)if(A.code==="invalid_union"&&A.errors.length)A.errors.map((D)=>G({issues:D}));else if(A.code==="invalid_key")G({issues:A.issues});else if(A.code==="invalid_element")G({issues:A.issues});else if(A.path.length===0)X._errors.push(E(A));else{let D=X,N=0;while(N<A.path.length){let W=A.path[N];if(N!==A.path.length-1)D[W]=D[W]||{_errors:[]};else D[W]=D[W]||{_errors:[]},D[W]._errors.push(E(A));D=D[W],N++}}};return G($),X}var rj=($,w)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:w,enumerable:!1}),Object.defineProperty($,"message",{get(){return JSON.stringify(w,Z9,2)},enumerable:!0}),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},E4,u9;var h9=R(()=>{bX();Kw();E4=S("$ZodError",rj),u9=S("$ZodError",rj,{Parent:Error})});var tj=($)=>(w,E,X,G)=>{let J=X?Object.assign(X,{async:!1}):{async:!1},A=w._zod.run({value:E,issues:[]},J);if(A instanceof Promise)throw new iw;if(A.issues.length){let D=new(G?.Err??$)(A.issues.map((N)=>u1(N,J,R1())));throw $4(D,G?.callee),D}return A.value},ij=($)=>async(w,E,X,G)=>{let J=X?Object.assign(X,{async:!0}):{async:!0},A=w._zod.run({value:E,issues:[]},J);if(A instanceof Promise)A=await A;if(A.issues.length){let D=new(G?.Err??$)(A.issues.map((N)=>u1(N,J,R1())));throw $4(D,G?.callee),D}return A.value},c9=($)=>(w,E,X)=>{let G=X?{...X,async:!1}:{async:!1},J=w._zod.run({value:E,issues:[]},G);if(J instanceof Promise)throw new iw;return J.issues.length?{success:!1,error:new($??E4)(J.issues.map((A)=>u1(A,G,R1())))}:{success:!0,data:J.value}},R6,n9=($)=>async(w,E,X)=>{let G=X?Object.assign(X,{async:!0}):{async:!0},J=w._zod.run({value:E,issues:[]},G);if(J instanceof Promise)J=await J;return J.issues.length?{success:!1,error:new $(J.issues.map((A)=>u1(A,G,R1())))}:{success:!0,data:J.value}},X4;var m9=R(()=>{bX();h9();Kw();R6=c9(u9),X4=n9(u9)});function GM(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}function LM($){return typeof $.precision==="number"?$.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":$.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${$.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function FM($){return new RegExp(`^${LM($)}$`)}function jM($){let w=LM({precision:$.precision}),E=["Z"];if($.local)E.push("");if($.offset)E.push("([+-]\\d{2}:\\d{2})");let X=`${w}(?:${E.join("|")})`;return new RegExp(`^${YM}T(?:${X})$`)}var dj,lj,sj,aj,ej,$M,wM,EM,r9=($)=>{if(!$)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${$}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},XM,JM,AM,DM,NM,WM,p9,OM,UM,YM="(?:(?:\\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])))",HM,MM=($)=>{let w=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${w}$`)},RM,zM,TM,BM,QM,IM;var G4=R(()=>{dj=/^[cC][^\s-]{8,}$/,lj=/^[0-9a-z]+$/,sj=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,aj=/^[0-9a-vA-V]{20}$/,ej=/^[A-Za-z0-9]{27}$/,$M=/^[a-zA-Z0-9_-]{21}$/,wM=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,EM=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,XM=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;JM=/^(?:(?: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])$/,AM=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,DM=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,NM=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,WM=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,p9=/^[A-Za-z0-9_-]*$/,OM=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,UM=/^\+(?:[0-9]){6,14}[0-9]$/,HM=new RegExp(`^${YM}$`);RM=/^\d+$/,zM=/^-?\d+(?:\.\d+)?/i,TM=/true|false/i,BM=/null/i,QM=/^[^A-Z]*$/,IM=/^[^a-z]*$/});var b$,KM,t9,i9,VM,PM,qM,SM,kM,z6,bM,ZM,CM,_M,vM,fM,xM;var J4=R(()=>{bX();G4();Kw();b$=S("$ZodCheck",($,w)=>{var E;$._zod??($._zod={}),$._zod.def=w,(E=$._zod).onattach??(E.onattach=[])}),KM={number:"number",bigint:"bigint",object:"date"},t9=S("$ZodCheckLessThan",($,w)=>{b$.init($,w);let E=KM[typeof w.value];$._zod.onattach.push((X)=>{let G=X._zod.bag,J=(w.inclusive?G.maximum:G.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(w.value<J)if(w.inclusive)G.maximum=w.value;else G.exclusiveMaximum=w.value}),$._zod.check=(X)=>{if(w.inclusive?X.value<=w.value:X.value<w.value)return;X.issues.push({origin:E,code:"too_big",maximum:w.value,input:X.value,inclusive:w.inclusive,inst:$,continue:!w.abort})}}),i9=S("$ZodCheckGreaterThan",($,w)=>{b$.init($,w);let E=KM[typeof w.value];$._zod.onattach.push((X)=>{let G=X._zod.bag,J=(w.inclusive?G.minimum:G.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(w.value>J)if(w.inclusive)G.minimum=w.value;else G.exclusiveMinimum=w.value}),$._zod.check=(X)=>{if(w.inclusive?X.value>=w.value:X.value>w.value)return;X.issues.push({origin:E,code:"too_small",minimum:w.value,input:X.value,inclusive:w.inclusive,inst:$,continue:!w.abort})}}),VM=S("$ZodCheckMultipleOf",($,w)=>{b$.init($,w),$._zod.onattach.push((E)=>{var X;(X=E._zod.bag).multipleOf??(X.multipleOf=w.value)}),$._zod.check=(E)=>{if(typeof E.value!==typeof w.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof E.value==="bigint"?E.value%w.value===BigInt(0):C9(E.value,w.value)===0)return;E.issues.push({origin:typeof E.value,code:"not_multiple_of",divisor:w.value,input:E.value,inst:$,continue:!w.abort})}}),PM=S("$ZodCheckNumberFormat",($,w)=>{b$.init($,w),w.format=w.format||"float64";let E=w.format?.includes("int"),X=E?"int":"number",[G,J]=y9[w.format];$._zod.onattach.push((A)=>{let D=A._zod.bag;if(D.format=w.format,D.minimum=G,D.maximum=J,E)D.pattern=RM}),$._zod.check=(A)=>{let D=A.value;if(E){if(!Number.isInteger(D)){A.issues.push({expected:X,format:w.format,code:"invalid_type",input:D,inst:$});return}if(!Number.isSafeInteger(D)){if(D>0)A.issues.push({input:D,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:X,continue:!w.abort});else A.issues.push({input:D,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:X,continue:!w.abort});return}}if(D<G)A.issues.push({origin:"number",input:D,code:"too_small",minimum:G,inclusive:!0,inst:$,continue:!w.abort});if(D>J)A.issues.push({origin:"number",input:D,code:"too_big",maximum:J,inst:$})}}),qM=S("$ZodCheckMaxLength",($,w)=>{var E;b$.init($,w),(E=$._zod.def).when??(E.when=(X)=>{let G=X.value;return!F6(G)&&G.length!==void 0}),$._zod.onattach.push((X)=>{let G=X._zod.bag.maximum??Number.POSITIVE_INFINITY;if(w.maximum<G)X._zod.bag.maximum=w.maximum}),$._zod.check=(X)=>{let G=X.value;if(G.length<=w.maximum)return;let A=M6(G);X.issues.push({origin:A,code:"too_big",maximum:w.maximum,inclusive:!0,input:G,inst:$,continue:!w.abort})}}),SM=S("$ZodCheckMinLength",($,w)=>{var E;b$.init($,w),(E=$._zod.def).when??(E.when=(X)=>{let G=X.value;return!F6(G)&&G.length!==void 0}),$._zod.onattach.push((X)=>{let G=X._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(w.minimum>G)X._zod.bag.minimum=w.minimum}),$._zod.check=(X)=>{let G=X.value;if(G.length>=w.minimum)return;let A=M6(G);X.issues.push({origin:A,code:"too_small",minimum:w.minimum,inclusive:!0,input:G,inst:$,continue:!w.abort})}}),kM=S("$ZodCheckLengthEquals",($,w)=>{var E;b$.init($,w),(E=$._zod.def).when??(E.when=(X)=>{let G=X.value;return!F6(G)&&G.length!==void 0}),$._zod.onattach.push((X)=>{let G=X._zod.bag;G.minimum=w.length,G.maximum=w.length,G.length=w.length}),$._zod.check=(X)=>{let G=X.value,J=G.length;if(J===w.length)return;let A=M6(G),D=J>w.length;X.issues.push({origin:A,...D?{code:"too_big",maximum:w.length}:{code:"too_small",minimum:w.length},inclusive:!0,exact:!0,input:X.value,inst:$,continue:!w.abort})}}),z6=S("$ZodCheckStringFormat",($,w)=>{var E,X;if(b$.init($,w),$._zod.onattach.push((G)=>{let J=G._zod.bag;if(J.format=w.format,w.pattern)J.patterns??(J.patterns=new Set),J.patterns.add(w.pattern)}),w.pattern)(E=$._zod).check??(E.check=(G)=>{if(w.pattern.lastIndex=0,w.pattern.test(G.value))return;G.issues.push({origin:"string",code:"invalid_format",format:w.format,input:G.value,...w.pattern?{pattern:w.pattern.toString()}:{},inst:$,continue:!w.abort})});else(X=$._zod).check??(X.check=()=>{})}),bM=S("$ZodCheckRegex",($,w)=>{z6.init($,w),$._zod.check=(E)=>{if(w.pattern.lastIndex=0,w.pattern.test(E.value))return;E.issues.push({origin:"string",code:"invalid_format",format:"regex",input:E.value,pattern:w.pattern.toString(),inst:$,continue:!w.abort})}}),ZM=S("$ZodCheckLowerCase",($,w)=>{w.pattern??(w.pattern=QM),z6.init($,w)}),CM=S("$ZodCheckUpperCase",($,w)=>{w.pattern??(w.pattern=IM),z6.init($,w)}),_M=S("$ZodCheckIncludes",($,w)=>{b$.init($,w);let E=dw(w.includes),X=new RegExp(typeof w.position==="number"?`^.{${w.position}}${E}`:E);w.pattern=X,$._zod.onattach.push((G)=>{let J=G._zod.bag;J.patterns??(J.patterns=new Set),J.patterns.add(X)}),$._zod.check=(G)=>{if(G.value.includes(w.includes,w.position))return;G.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:w.includes,input:G.value,inst:$,continue:!w.abort})}}),vM=S("$ZodCheckStartsWith",($,w)=>{b$.init($,w);let E=new RegExp(`^${dw(w.prefix)}.*`);w.pattern??(w.pattern=E),$._zod.onattach.push((X)=>{let G=X._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(E)}),$._zod.check=(X)=>{if(X.value.startsWith(w.prefix))return;X.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:w.prefix,input:X.value,inst:$,continue:!w.abort})}}),fM=S("$ZodCheckEndsWith",($,w)=>{b$.init($,w);let E=new RegExp(`.*${dw(w.suffix)}$`);w.pattern??(w.pattern=E),$._zod.onattach.push((X)=>{let G=X._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(E)}),$._zod.check=(X)=>{if(X.value.endsWith(w.suffix))return;X.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:w.suffix,input:X.value,inst:$,continue:!w.abort})}}),xM=S("$ZodCheckOverwrite",($,w)=>{b$.init($,w),$._zod.check=(E)=>{E.value=w.tx(E.value)}})});class d9{constructor($=[]){if(this.content=[],this.indent=0,this)this.args=$}indented($){this.indent+=1,$(this),this.indent-=1}write($){if(typeof $==="function"){$(this,{execution:"sync"}),$(this,{execution:"async"});return}let E=$.split(`
|
|
545
|
+
WHERE tl.to_task_id = ? AND tl.link_type = 'subtask_of'`).get(X);if(!G||G.total===0)return null;let J=Math.round(G.done/G.total*100);if($.query("UPDATE tasks SET progress = ?, updated_at = unixepoch() WHERE id = ?").run(J,X),G.done===G.total){let A=$.query("SELECT status FROM tasks WHERE id = ?").get(X);if(A&&!["done","cancelled","review"].includes(A.status))$.query("UPDATE tasks SET status = 'review', updated_at = unixepoch() WHERE id = ?").run(X)}return X}function sA(){return x().$client}function U6($){return{...$,due_at:$.due_at?.toISOString()??null,claim_expires_at:$.claim_expires_at?.toISOString()??null,created_at:$.created_at.toISOString(),updated_at:$.updated_at.toISOString()}}function Ev($){return{...$,tags:typeof $.tags==="string"?JSON.parse($.tags):$.tags,due_at:$.due_at?new Date($.due_at*1000).toISOString():null,claim_expires_at:$.claim_expires_at?new Date($.claim_expires_at*1000).toISOString():null,created_at:new Date($.created_at*1000).toISOString(),updated_at:new Date($.updated_at*1000).toISOString()}}function Tj($){return{...$,created_at:$.created_at.toISOString()}}var j1,O6,zj,m_,r_,p_,o_,t_,i_,d_,l_,s_,a_,e_,$v,wv;var Bj=R(()=>{N1();x1();X1();nA();y$();d$();i$();j1=new p0,O6=U.object({id:U.string(),project_id:U.string().nullable(),title:U.string(),body:U.string().nullable(),status:uA,priority:J6,progress:U.number().int(),due_at:U.string().datetime().nullable(),tags:U.array(U.string()).nullable(),author:U.string(),claimed_by:U.string().nullable(),claim_expires_at:U.string().datetime().nullable(),created_at:U.string().datetime(),updated_at:U.string().datetime()}).openapi("Task"),zj=U.object({id:U.string(),resource_type:U.string(),resource_id:U.string(),content:U.string(),author:U.string(),created_at:U.string().datetime()}).openapi("Comment"),m_=U.object({title:U.string().min(1).max(500),body:U.string().optional(),project_id:U.string().optional(),status:U.enum(["todo","doing","blocked"]).optional().default("todo"),priority:J6.optional().default("normal"),due_at:U.string().datetime().optional(),tags:U.array(U.string()).optional(),author:U.string().optional().default("human")}).openapi("CreateTask"),r_=U.object({title:U.string().min(1).max(500).optional(),body:U.string().optional(),status:uA.optional(),priority:J6.optional(),due_at:U.string().datetime().optional(),tags:U.array(U.string()).optional()}).openapi("UpdateTask"),p_=m({method:"get",path:"/tasks",tags:["Tasks"],summary:"List tasks",request:{query:U.object({project_id:U.string().optional(),status:uA.optional(),tag:U.string().optional(),limit:U.coerce.number().int().min(1).max(100).optional().default(50)})},responses:{200:{description:"Task list",content:{"application/json":{schema:U.object({tasks:U.array(O6),total:U.number()})}}}}}),o_=m({method:"get",path:"/tasks/{id}",tags:["Tasks"],summary:"Get task by ID",request:{params:U.object({id:U.string()})},responses:{200:{description:"Task",content:{"application/json":{schema:O6}}}}}),t_=m({method:"post",path:"/tasks",tags:["Tasks"],summary:"Create task",request:{body:{content:{"application/json":{schema:m_}}}},responses:{201:{description:"Created",content:{"application/json":{schema:O6}}}}}),i_=m({method:"patch",path:"/tasks/{id}",tags:["Tasks"],summary:"Update task",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:r_}}}},responses:{200:{description:"Updated",content:{"application/json":{schema:O6}}}}}),d_=m({method:"delete",path:"/tasks/{id}",tags:["Tasks"],summary:"Delete task",request:{params:U.object({id:U.string()})},responses:{204:{description:"Deleted"}}}),l_=U.object({ref:U.string().describe("Temporary reference ID for dependency linking, e.g. 'T1'"),title:U.string().min(1).max(500),body:U.string().optional(),priority:J6.optional().default("normal"),depends_on:U.array(U.string()).optional().describe("Refs of tasks that block this one"),subtask_of:U.string().optional().describe("Ref of parent task")}),s_=m({method:"post",path:"/tasks/batch",tags:["Tasks"],summary:"Create multiple tasks with dependency links atomically",request:{body:{content:{"application/json":{schema:U.object({tasks:U.array(l_).min(1).max(100),project_id:U.string().optional(),author:U.string().optional().default("agent")}).openapi("BatchCreateTasks")}}}},responses:{201:{description:"Created tasks with ref\u2192id mapping",content:{"application/json":{schema:U.object({created:U.number(),mapping:U.record(U.string(),U.string())})}}}}}),a_=m({method:"post",path:"/tasks/{id}/review",tags:["Tasks"],summary:"Submit task for human review (HITL checkpoint)",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:U.object({summary:U.string().min(1)}).openapi("SubmitReview")}}}},responses:{200:{description:"Submitted",content:{"application/json":{schema:O6}}}}}),e_=m({method:"get",path:"/tasks/{id}/review",tags:["Tasks"],summary:"Poll HITL review result",request:{params:U.object({id:U.string()})},responses:{200:{description:"Review status",content:{"application/json":{schema:U.object({status:U.enum(["review","approved","changes_requested","pending"]),comment:U.string().nullable()}).openapi("ReviewStatus")}}}}}),$v=m({method:"get",path:"/tasks/{id}/comments",tags:["Tasks"],summary:"List task comments",request:{params:U.object({id:U.string()})},responses:{200:{description:"Comments",content:{"application/json":{schema:U.object({comments:U.array(zj)})}}}}}),wv=m({method:"post",path:"/tasks/{id}/comments",tags:["Tasks"],summary:"Add a comment to a task",request:{params:U.object({id:U.string()}),body:{content:{"application/json":{schema:U.object({content:U.string().min(1),author:U.string().optional().default("human")}).openapi("AddComment")}}}},responses:{201:{description:"Comment added",content:{"application/json":{schema:zj}}}}});j1.openapi(p_,async($)=>{let w=x(),{project_id:E,status:X,tag:G,limit:J}=$.req.valid("query");if(G){let N=sA(),W="SELECT DISTINCT t.* FROM tasks t, json_each(t.tags) AS j WHERE j.value = ?",O=[G];if(E)W+=" AND t.project_id = ?",O.push(E);if(X)W+=" AND t.status = ?",O.push(X);W+=" ORDER BY t.updated_at DESC LIMIT ?",O.push(J);let Y=N.query(W).all(...O),H=Y.map(Ev);return $.json({tasks:H,total:Y.length})}let A=[];if(E)A.push(V(r.project_id,E));if(X)A.push(V(r.status,X));let D=await w.query.tasks.findMany({where:A.length>0?S0(...A):void 0,limit:J,orderBy:[x0(r.updated_at)]});return $.json({tasks:D.map(U6),total:D.length})});j1.openapi(o_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=await w.query.tasks.findFirst({where:V(r.id,E)});if(!X)throw new U0("Task",E);return $.json(U6(X))});j1.openapi(t_,async($)=>{let w=x(),E=$.req.valid("json"),X=new Date,G=i();await w.insert(r).values({id:G,title:E.title,body:E.body,project_id:E.project_id,status:E.status,priority:E.priority,...E.due_at?{due_at:new Date(E.due_at)}:{},tags:E.tags,author:E.author,created_at:X,updated_at:X});let J=await w.query.tasks.findFirst({where:V(r.id,G)});if(!J)throw Error("Expected task to exist after write");return $.json(U6(J),201)});j1.openapi(i_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=$.req.valid("json"),G=await w.query.tasks.findFirst({where:V(r.id,E)});if(!G)throw new U0("Task",E);if(X.status==="doing"&&G.status!=="doing"){let A=I9(sA(),E);if(A.length>0){let D=A.map((N)=>`[${N.id.slice(-6)}] ${N.title}`).join(", ");throw new Ew(`Cannot start: blocked by ${D}`)}}if(await w.update(r).set({...X.title!==void 0?{title:X.title}:{},...X.body!==void 0?{body:X.body}:{},...X.status!==void 0?{status:X.status}:{},...X.priority!==void 0?{priority:X.priority}:{},...X.due_at!==void 0?{due_at:new Date(X.due_at)}:{},...X.tags!==void 0?{tags:X.tags}:{},updated_at:new Date}).where(V(r.id,E)),X.status&&["done","cancelled"].includes(X.status)){let A=sA();Mj(A,E),Rj(A,E)}let J=await w.query.tasks.findFirst({where:V(r.id,E)});if(!J)throw Error("Expected updated to exist after write");return $.json(U6(J))});j1.openapi(d_,async($)=>{let w=x(),{id:E}=$.req.valid("param");if(!await w.query.tasks.findFirst({where:V(r.id,E)}))throw new U0("Task",E);return await w.delete(r).where(V(r.id,E)),new Response(null,{status:204})});j1.openapi(a_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),{summary:X}=$.req.valid("json"),G=await w.query.tasks.findFirst({where:V(r.id,E)});if(!G)throw new U0("Task",E);if(!["doing","blocked"].includes(G.status))throw new Ew(`Task must be in doing/blocked to submit for review (current: ${G.status})`);let J=new Date;await w.update(r).set({status:"review",body:X,updated_at:J}).where(V(r.id,E)),await w.insert(G$).values({id:i(),resource_type:"task",resource_id:E,content:`[review submitted] ${X}`,author:"agent",created_at:J});let A=await w.query.tasks.findFirst({where:V(r.id,E)});if(!A)throw Error("Expected updated to exist after write");return $.json(U6(A))});j1.openapi(e_,async($)=>{let w=x(),{id:E}=$.req.valid("param"),X=await w.query.tasks.findFirst({where:V(r.id,E)});if(!X)throw new U0("Task",E);let G=await w.query.comments.findFirst({where:S0(V(G$.resource_type,"task"),V(G$.resource_id,E),V(G$.author,"human")),orderBy:[x0(G$.created_at)]}),A={review:"review",done:"approved",changes_requested:"changes_requested"}[X.status]??"pending";return $.json({status:A,comment:G?.content??null})});j1.openapi($v,async($)=>{let w=x(),{id:E}=$.req.valid("param");if(!await w.query.tasks.findFirst({where:V(r.id,E)}))throw new U0("Task",E);let G=await w.query.comments.findMany({where:S0(V(G$.resource_type,"task"),V(G$.resource_id,E)),orderBy:[x0(G$.created_at)]});return $.json({comments:G.map(Tj)})});j1.openapi(wv,async($)=>{let w=x(),{id:E}=$.req.valid("param"),{content:X,author:G}=$.req.valid("json");if(!await w.query.tasks.findFirst({where:V(r.id,E)}))throw new U0("Task",E);let A=i(),D=new Date;await w.insert(G$).values({id:A,resource_type:"task",resource_id:E,content:X,author:G,created_at:D});let N=await w.query.comments.findFirst({where:V(G$.id,A)});if(!N)throw Error("Expected comment to exist after write");return $.json(Tj(N),201)});j1.openapi(s_,async($)=>{let w=x(),{tasks:E,project_id:X,author:G}=$.req.valid("json"),J=new Date,A={},D=sA();D.exec("BEGIN");try{for(let N of E){let W=i();A[N.ref]=W,await w.insert(r).values({id:W,title:N.title,body:N.body,project_id:X,priority:N.priority,author:G,status:"todo",created_at:J,updated_at:J})}for(let N of E){let W=A[N.ref];if(N.depends_on)for(let O of N.depends_on){let Y=A[O];if(!Y)continue;await w.insert(f$).values({id:i(),from_task_id:Y,to_task_id:W,link_type:"blocks",created_at:J})}if(N.subtask_of){let O=A[N.subtask_of];if(O)await w.insert(f$).values({id:i(),from_task_id:W,to_task_id:O,link_type:"subtask_of",created_at:J}),await w.insert(f$).values({id:i(),from_task_id:O,to_task_id:W,link_type:"parent_of",created_at:J})}}D.exec("COMMIT")}catch(N){throw D.exec("ROLLBACK"),N}return $.json({created:E.length,mapping:A},201)})});function Qj(){let $=O0(),w=new p0;return w.use("*",cF($.api.secret)),w.onError((E,X)=>{let G=E instanceof PX?E:null;if(G)return X.json({error:G.message,code:G.code},G.statusCode);return Xv.error("Unhandled error",E),X.json({error:"Internal server error",code:"INTERNAL_ERROR"},500)}),w.route("/",L9),w.route("/",z9),w.route("/",y1),w.route("/",Iw),w.route("/",j1),w.route("/",W6),w.route("/",SX),w.route("/",lA),w.route("/",Xw),w.route("/",gA),w.route("/",Q9),w.doc("/openapi.json",{openapi:"3.1.0",info:{title:"Orc API",version:lE,description:"Human + AI Orchestration Hub API"},servers:[{url:`http://${$.api.host}:${$.api.port}`,description:"Local"}]}),w.get("/docs",I3({url:"/openapi.json"})),w}var Xv;var Ij=R(()=>{K3();N1();C$();x1();p$();FJ();nF();mF();rF();oF();wj();Xj();Dj();Nj();Uj();Hj();jj();Bj();Xv=Z0("api")});var V9={};Ww(V9,{app:()=>Kj});var K9,ow,Kj;var P9=R(()=>{C$();p$();Ij();K9=Z0("api"),ow=O0(),Kj=Qj();Bun.serve({port:ow.api.port,hostname:ow.api.host,fetch:Kj.fetch});K9.info(`API server running on http://${ow.api.host}:${ow.api.port}`);K9.info(`OpenAPI spec: http://${ow.api.host}:${ow.api.port}/openapi.json`);K9.info(`Swagger UI: http://${ow.api.host}:${ow.api.port}/docs`)});function S($,w,E){function X(D,N){var W;Object.defineProperty(D,"_zod",{value:D._zod??{},enumerable:!1}),(W=D._zod).traits??(W.traits=new Set),D._zod.traits.add($),w(D,N);for(let O in A.prototype)if(!(O in D))Object.defineProperty(D,O,{value:A.prototype[O].bind(D)});D._zod.constr=A,D._zod.def=N}let G=E?.Parent??Object;class J extends G{}Object.defineProperty(J,"name",{value:$});function A(D){var N;let W=E?.Parent?new J:this;X(W,D),(N=W._zod).deferred??(N.deferred=[]);for(let O of W._zod.deferred)O();return W}return Object.defineProperty(A,"init",{value:X}),Object.defineProperty(A,Symbol.hasInstance,{value:(D)=>{if(E?.Parent&&D instanceof E.Parent)return!0;return D?._zod?.traits?.has($)}}),Object.defineProperty(A,"name",{value:$}),A}function R1($){if($)Object.assign($4,$);return $4}var PG0,qG0,iw,$4;var ZX=R(()=>{PG0=Object.freeze({status:"aborted"});qG0=Symbol("zod_brand");iw=class iw extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};$4={}});var B0={};Ww(B0,{unwrapMessage:()=>L6,stringifyPrimitive:()=>X4,required:()=>nv,randomString:()=>_v,propertyKeyTypes:()=>g9,promiseAllObject:()=>Cv,primitiveTypes:()=>mj,prefixIssues:()=>Jw,pick:()=>yv,partial:()=>cv,optionalKeys:()=>u9,omit:()=>gv,numKeys:()=>vv,nullish:()=>j6,normalizeParams:()=>l,merge:()=>hv,jsonStringifyReplacer:()=>v9,joinValues:()=>w4,issue:()=>c9,isPlainObject:()=>_X,isObject:()=>CX,getSizableOrigin:()=>pj,getParsedType:()=>fv,getLengthableOrigin:()=>R6,getEnumValues:()=>_9,getElementAtPath:()=>Zv,floatSafeRemainder:()=>f9,finalizeIssue:()=>u1,extend:()=>uv,escapeRegex:()=>dw,esc:()=>PE,defineLazy:()=>C0,createTransparentProxy:()=>xv,clone:()=>Gw,cleanRegex:()=>M6,cleanEnum:()=>mv,captureStackTrace:()=>E4,cached:()=>F6,assignProp:()=>x9,assertNotEqual:()=>qv,assertNever:()=>kv,assertIs:()=>Sv,assertEqual:()=>Pv,assert:()=>bv,allowsEval:()=>y9,aborted:()=>qE,NUMBER_FORMAT_RANGES:()=>h9,Class:()=>oj,BIGINT_FORMAT_RANGES:()=>rj});function Pv($){return $}function qv($){return $}function Sv($){}function kv($){throw Error()}function bv($){}function _9($){let w=Object.values($).filter((X)=>typeof X==="number");return Object.entries($).filter(([X,G])=>w.indexOf(+X)===-1).map(([X,G])=>G)}function w4($,w="|"){return $.map((E)=>X4(E)).join(w)}function v9($,w){if(typeof w==="bigint")return w.toString();return w}function F6($){return{get value(){{let E=$();return Object.defineProperty(this,"value",{value:E}),E}throw Error("cached value already set")}}}function j6($){return $===null||$===void 0}function M6($){let w=$.startsWith("^")?1:0,E=$.endsWith("$")?$.length-1:$.length;return $.slice(w,E)}function f9($,w){let E=($.toString().split(".")[1]||"").length,X=(w.toString().split(".")[1]||"").length,G=E>X?E:X,J=Number.parseInt($.toFixed(G).replace(".","")),A=Number.parseInt(w.toFixed(G).replace(".",""));return J%A/10**G}function C0($,w,E){Object.defineProperty($,w,{get(){{let G=E();return $[w]=G,G}throw Error("cached value already set")},set(G){Object.defineProperty($,w,{value:G})},configurable:!0})}function x9($,w,E){Object.defineProperty($,w,{value:E,writable:!0,enumerable:!0,configurable:!0})}function Zv($,w){if(!w)return $;return w.reduce((E,X)=>E?.[X],$)}function Cv($){let w=Object.keys($),E=w.map((X)=>$[X]);return Promise.all(E).then((X)=>{let G={};for(let J=0;J<w.length;J++)G[w[J]]=X[J];return G})}function _v($=10){let E="";for(let X=0;X<$;X++)E+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return E}function PE($){return JSON.stringify($)}function CX($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function _X($){if(CX($)===!1)return!1;let w=$.constructor;if(w===void 0)return!0;let E=w.prototype;if(CX(E)===!1)return!1;if(Object.prototype.hasOwnProperty.call(E,"isPrototypeOf")===!1)return!1;return!0}function vv($){let w=0;for(let E in $)if(Object.prototype.hasOwnProperty.call($,E))w++;return w}function dw($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Gw($,w,E){let X=new $._zod.constr(w??$._zod.def);if(!w||E?.parent)X._zod.parent=$;return X}function l($){let w=$;if(!w)return{};if(typeof w==="string")return{error:()=>w};if(w?.message!==void 0){if(w?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");w.error=w.message}if(delete w.message,typeof w.error==="string")return{...w,error:()=>w.error};return w}function xv($){let w;return new Proxy({},{get(E,X,G){return w??(w=$()),Reflect.get(w,X,G)},set(E,X,G,J){return w??(w=$()),Reflect.set(w,X,G,J)},has(E,X){return w??(w=$()),Reflect.has(w,X)},deleteProperty(E,X){return w??(w=$()),Reflect.deleteProperty(w,X)},ownKeys(E){return w??(w=$()),Reflect.ownKeys(w)},getOwnPropertyDescriptor(E,X){return w??(w=$()),Reflect.getOwnPropertyDescriptor(w,X)},defineProperty(E,X,G){return w??(w=$()),Reflect.defineProperty(w,X,G)}})}function X4($){if(typeof $==="bigint")return $.toString()+"n";if(typeof $==="string")return`"${$}"`;return`${$}`}function u9($){return Object.keys($).filter((w)=>{return $[w]._zod.optin==="optional"&&$[w]._zod.optout==="optional"})}function yv($,w){let E={},X=$._zod.def;for(let G in w){if(!(G in X.shape))throw Error(`Unrecognized key: "${G}"`);if(!w[G])continue;E[G]=X.shape[G]}return Gw($,{...$._zod.def,shape:E,checks:[]})}function gv($,w){let E={...$._zod.def.shape},X=$._zod.def;for(let G in w){if(!(G in X.shape))throw Error(`Unrecognized key: "${G}"`);if(!w[G])continue;delete E[G]}return Gw($,{...$._zod.def,shape:E,checks:[]})}function uv($,w){if(!_X(w))throw Error("Invalid input to extend: expected a plain object");let E={...$._zod.def,get shape(){let X={...$._zod.def.shape,...w};return x9(this,"shape",X),X},checks:[]};return Gw($,E)}function hv($,w){return Gw($,{...$._zod.def,get shape(){let E={...$._zod.def.shape,...w._zod.def.shape};return x9(this,"shape",E),E},catchall:w._zod.def.catchall,checks:[]})}function cv($,w,E){let X=w._zod.def.shape,G={...X};if(E)for(let J in E){if(!(J in X))throw Error(`Unrecognized key: "${J}"`);if(!E[J])continue;G[J]=$?new $({type:"optional",innerType:X[J]}):X[J]}else for(let J in X)G[J]=$?new $({type:"optional",innerType:X[J]}):X[J];return Gw(w,{...w._zod.def,shape:G,checks:[]})}function nv($,w,E){let X=w._zod.def.shape,G={...X};if(E)for(let J in E){if(!(J in G))throw Error(`Unrecognized key: "${J}"`);if(!E[J])continue;G[J]=new $({type:"nonoptional",innerType:X[J]})}else for(let J in X)G[J]=new $({type:"nonoptional",innerType:X[J]});return Gw(w,{...w._zod.def,shape:G,checks:[]})}function qE($,w=0){for(let E=w;E<$.issues.length;E++)if($.issues[E]?.continue!==!0)return!0;return!1}function Jw($,w){return w.map((E)=>{var X;return(X=E).path??(X.path=[]),E.path.unshift($),E})}function L6($){return typeof $==="string"?$:$?.message}function u1($,w,E){let X={...$,path:$.path??[]};if(!$.message){let G=L6($.inst?._zod.def?.error?.($))??L6(w?.error?.($))??L6(E.customError?.($))??L6(E.localeError?.($))??"Invalid input";X.message=G}if(delete X.inst,delete X.continue,!w?.reportInput)delete X.input;return X}function pj($){if($ instanceof Set)return"set";if($ instanceof Map)return"map";if($ instanceof File)return"file";return"unknown"}function R6($){if(Array.isArray($))return"array";if(typeof $==="string")return"string";return"unknown"}function c9(...$){let[w,E,X]=$;if(typeof w==="string")return{message:w,code:"custom",input:E,inst:X};return{...w}}function mv($){return Object.entries($).filter(([w,E])=>{return Number.isNaN(Number.parseInt(w,10))}).map((w)=>w[1])}class oj{constructor(...$){}}var E4,y9,fv=($)=>{let w=typeof $;switch(w){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN($)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray($))return"array";if($===null)return"null";if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return"promise";if(typeof Map<"u"&&$ instanceof Map)return"map";if(typeof Set<"u"&&$ instanceof Set)return"set";if(typeof Date<"u"&&$ instanceof Date)return"date";if(typeof File<"u"&&$ instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${w}`)}},g9,mj,h9,rj;var Kw=R(()=>{E4=Error.captureStackTrace?Error.captureStackTrace:(...$)=>{};y9=F6(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch($){return!1}});g9=new Set(["string","number","symbol"]),mj=new Set(["string","number","bigint","boolean","symbol","undefined"]);h9={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},rj={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]}});function ij($,w=(E)=>E.message){let E={},X=[];for(let G of $.issues)if(G.path.length>0)E[G.path[0]]=E[G.path[0]]||[],E[G.path[0]].push(w(G));else X.push(w(G));return{formErrors:X,fieldErrors:E}}function dj($,w){let E=w||function(J){return J.message},X={_errors:[]},G=(J)=>{for(let A of J.issues)if(A.code==="invalid_union"&&A.errors.length)A.errors.map((D)=>G({issues:D}));else if(A.code==="invalid_key")G({issues:A.issues});else if(A.code==="invalid_element")G({issues:A.issues});else if(A.path.length===0)X._errors.push(E(A));else{let D=X,N=0;while(N<A.path.length){let W=A.path[N];if(N!==A.path.length-1)D[W]=D[W]||{_errors:[]};else D[W]=D[W]||{_errors:[]},D[W]._errors.push(E(A));D=D[W],N++}}};return G($),X}var tj=($,w)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:w,enumerable:!1}),Object.defineProperty($,"message",{get(){return JSON.stringify(w,v9,2)},enumerable:!0}),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},G4,n9;var m9=R(()=>{ZX();Kw();G4=S("$ZodError",tj),n9=S("$ZodError",tj,{Parent:Error})});var lj=($)=>(w,E,X,G)=>{let J=X?Object.assign(X,{async:!1}):{async:!1},A=w._zod.run({value:E,issues:[]},J);if(A instanceof Promise)throw new iw;if(A.issues.length){let D=new(G?.Err??$)(A.issues.map((N)=>u1(N,J,R1())));throw E4(D,G?.callee),D}return A.value},sj=($)=>async(w,E,X,G)=>{let J=X?Object.assign(X,{async:!0}):{async:!0},A=w._zod.run({value:E,issues:[]},J);if(A instanceof Promise)A=await A;if(A.issues.length){let D=new(G?.Err??$)(A.issues.map((N)=>u1(N,J,R1())));throw E4(D,G?.callee),D}return A.value},r9=($)=>(w,E,X)=>{let G=X?{...X,async:!1}:{async:!1},J=w._zod.run({value:E,issues:[]},G);if(J instanceof Promise)throw new iw;return J.issues.length?{success:!1,error:new($??G4)(J.issues.map((A)=>u1(A,G,R1())))}:{success:!0,data:J.value}},z6,p9=($)=>async(w,E,X)=>{let G=X?Object.assign(X,{async:!0}):{async:!0},J=w._zod.run({value:E,issues:[]},G);if(J instanceof Promise)J=await J;return J.issues.length?{success:!1,error:new $(J.issues.map((A)=>u1(A,G,R1())))}:{success:!0,data:J.value}},J4;var o9=R(()=>{ZX();m9();Kw();z6=r9(n9),J4=p9(n9)});function DM(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}function MM($){return typeof $.precision==="number"?$.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":$.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${$.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function RM($){return new RegExp(`^${MM($)}$`)}function zM($){let w=MM({precision:$.precision}),E=["Z"];if($.local)E.push("");if($.offset)E.push("([+-]\\d{2}:\\d{2})");let X=`${w}(?:${E.join("|")})`;return new RegExp(`^${FM}T(?:${X})$`)}var aj,ej,$M,wM,EM,XM,GM,JM,t9=($)=>{if(!$)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${$}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},AM,NM,WM,OM,UM,YM,i9,HM,LM,FM="(?:(?:\\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])))",jM,TM=($)=>{let w=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${w}$`)},BM,QM,IM,KM,VM,PM;var A4=R(()=>{aj=/^[cC][^\s-]{8,}$/,ej=/^[0-9a-z]+$/,$M=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,wM=/^[0-9a-vA-V]{20}$/,EM=/^[A-Za-z0-9]{27}$/,XM=/^[a-zA-Z0-9_-]{21}$/,GM=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,JM=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,AM=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;NM=/^(?:(?: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])$/,WM=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,OM=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,UM=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,YM=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,i9=/^[A-Za-z0-9_-]*$/,HM=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,LM=/^\+(?:[0-9]){6,14}[0-9]$/,jM=new RegExp(`^${FM}$`);BM=/^\d+$/,QM=/^-?\d+(?:\.\d+)?/i,IM=/true|false/i,KM=/null/i,VM=/^[^A-Z]*$/,PM=/^[^a-z]*$/});var b$,qM,l9,s9,SM,kM,bM,ZM,CM,T6,_M,vM,fM,xM,yM,gM,uM;var D4=R(()=>{ZX();A4();Kw();b$=S("$ZodCheck",($,w)=>{var E;$._zod??($._zod={}),$._zod.def=w,(E=$._zod).onattach??(E.onattach=[])}),qM={number:"number",bigint:"bigint",object:"date"},l9=S("$ZodCheckLessThan",($,w)=>{b$.init($,w);let E=qM[typeof w.value];$._zod.onattach.push((X)=>{let G=X._zod.bag,J=(w.inclusive?G.maximum:G.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(w.value<J)if(w.inclusive)G.maximum=w.value;else G.exclusiveMaximum=w.value}),$._zod.check=(X)=>{if(w.inclusive?X.value<=w.value:X.value<w.value)return;X.issues.push({origin:E,code:"too_big",maximum:w.value,input:X.value,inclusive:w.inclusive,inst:$,continue:!w.abort})}}),s9=S("$ZodCheckGreaterThan",($,w)=>{b$.init($,w);let E=qM[typeof w.value];$._zod.onattach.push((X)=>{let G=X._zod.bag,J=(w.inclusive?G.minimum:G.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(w.value>J)if(w.inclusive)G.minimum=w.value;else G.exclusiveMinimum=w.value}),$._zod.check=(X)=>{if(w.inclusive?X.value>=w.value:X.value>w.value)return;X.issues.push({origin:E,code:"too_small",minimum:w.value,input:X.value,inclusive:w.inclusive,inst:$,continue:!w.abort})}}),SM=S("$ZodCheckMultipleOf",($,w)=>{b$.init($,w),$._zod.onattach.push((E)=>{var X;(X=E._zod.bag).multipleOf??(X.multipleOf=w.value)}),$._zod.check=(E)=>{if(typeof E.value!==typeof w.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof E.value==="bigint"?E.value%w.value===BigInt(0):f9(E.value,w.value)===0)return;E.issues.push({origin:typeof E.value,code:"not_multiple_of",divisor:w.value,input:E.value,inst:$,continue:!w.abort})}}),kM=S("$ZodCheckNumberFormat",($,w)=>{b$.init($,w),w.format=w.format||"float64";let E=w.format?.includes("int"),X=E?"int":"number",[G,J]=h9[w.format];$._zod.onattach.push((A)=>{let D=A._zod.bag;if(D.format=w.format,D.minimum=G,D.maximum=J,E)D.pattern=BM}),$._zod.check=(A)=>{let D=A.value;if(E){if(!Number.isInteger(D)){A.issues.push({expected:X,format:w.format,code:"invalid_type",input:D,inst:$});return}if(!Number.isSafeInteger(D)){if(D>0)A.issues.push({input:D,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:X,continue:!w.abort});else A.issues.push({input:D,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:X,continue:!w.abort});return}}if(D<G)A.issues.push({origin:"number",input:D,code:"too_small",minimum:G,inclusive:!0,inst:$,continue:!w.abort});if(D>J)A.issues.push({origin:"number",input:D,code:"too_big",maximum:J,inst:$})}}),bM=S("$ZodCheckMaxLength",($,w)=>{var E;b$.init($,w),(E=$._zod.def).when??(E.when=(X)=>{let G=X.value;return!j6(G)&&G.length!==void 0}),$._zod.onattach.push((X)=>{let G=X._zod.bag.maximum??Number.POSITIVE_INFINITY;if(w.maximum<G)X._zod.bag.maximum=w.maximum}),$._zod.check=(X)=>{let G=X.value;if(G.length<=w.maximum)return;let A=R6(G);X.issues.push({origin:A,code:"too_big",maximum:w.maximum,inclusive:!0,input:G,inst:$,continue:!w.abort})}}),ZM=S("$ZodCheckMinLength",($,w)=>{var E;b$.init($,w),(E=$._zod.def).when??(E.when=(X)=>{let G=X.value;return!j6(G)&&G.length!==void 0}),$._zod.onattach.push((X)=>{let G=X._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(w.minimum>G)X._zod.bag.minimum=w.minimum}),$._zod.check=(X)=>{let G=X.value;if(G.length>=w.minimum)return;let A=R6(G);X.issues.push({origin:A,code:"too_small",minimum:w.minimum,inclusive:!0,input:G,inst:$,continue:!w.abort})}}),CM=S("$ZodCheckLengthEquals",($,w)=>{var E;b$.init($,w),(E=$._zod.def).when??(E.when=(X)=>{let G=X.value;return!j6(G)&&G.length!==void 0}),$._zod.onattach.push((X)=>{let G=X._zod.bag;G.minimum=w.length,G.maximum=w.length,G.length=w.length}),$._zod.check=(X)=>{let G=X.value,J=G.length;if(J===w.length)return;let A=R6(G),D=J>w.length;X.issues.push({origin:A,...D?{code:"too_big",maximum:w.length}:{code:"too_small",minimum:w.length},inclusive:!0,exact:!0,input:X.value,inst:$,continue:!w.abort})}}),T6=S("$ZodCheckStringFormat",($,w)=>{var E,X;if(b$.init($,w),$._zod.onattach.push((G)=>{let J=G._zod.bag;if(J.format=w.format,w.pattern)J.patterns??(J.patterns=new Set),J.patterns.add(w.pattern)}),w.pattern)(E=$._zod).check??(E.check=(G)=>{if(w.pattern.lastIndex=0,w.pattern.test(G.value))return;G.issues.push({origin:"string",code:"invalid_format",format:w.format,input:G.value,...w.pattern?{pattern:w.pattern.toString()}:{},inst:$,continue:!w.abort})});else(X=$._zod).check??(X.check=()=>{})}),_M=S("$ZodCheckRegex",($,w)=>{T6.init($,w),$._zod.check=(E)=>{if(w.pattern.lastIndex=0,w.pattern.test(E.value))return;E.issues.push({origin:"string",code:"invalid_format",format:"regex",input:E.value,pattern:w.pattern.toString(),inst:$,continue:!w.abort})}}),vM=S("$ZodCheckLowerCase",($,w)=>{w.pattern??(w.pattern=VM),T6.init($,w)}),fM=S("$ZodCheckUpperCase",($,w)=>{w.pattern??(w.pattern=PM),T6.init($,w)}),xM=S("$ZodCheckIncludes",($,w)=>{b$.init($,w);let E=dw(w.includes),X=new RegExp(typeof w.position==="number"?`^.{${w.position}}${E}`:E);w.pattern=X,$._zod.onattach.push((G)=>{let J=G._zod.bag;J.patterns??(J.patterns=new Set),J.patterns.add(X)}),$._zod.check=(G)=>{if(G.value.includes(w.includes,w.position))return;G.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:w.includes,input:G.value,inst:$,continue:!w.abort})}}),yM=S("$ZodCheckStartsWith",($,w)=>{b$.init($,w);let E=new RegExp(`^${dw(w.prefix)}.*`);w.pattern??(w.pattern=E),$._zod.onattach.push((X)=>{let G=X._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(E)}),$._zod.check=(X)=>{if(X.value.startsWith(w.prefix))return;X.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:w.prefix,input:X.value,inst:$,continue:!w.abort})}}),gM=S("$ZodCheckEndsWith",($,w)=>{b$.init($,w);let E=new RegExp(`.*${dw(w.suffix)}$`);w.pattern??(w.pattern=E),$._zod.onattach.push((X)=>{let G=X._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(E)}),$._zod.check=(X)=>{if(X.value.endsWith(w.suffix))return;X.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:w.suffix,input:X.value,inst:$,continue:!w.abort})}}),uM=S("$ZodCheckOverwrite",($,w)=>{b$.init($,w),$._zod.check=(E)=>{E.value=w.tx(E.value)}})});class a9{constructor($=[]){if(this.content=[],this.indent=0,this)this.args=$}indented($){this.indent+=1,$(this),this.indent-=1}write($){if(typeof $==="function"){$(this,{execution:"sync"}),$(this,{execution:"async"});return}let E=$.split(`
|
|
546
546
|
`).filter((J)=>J),X=Math.min(...E.map((J)=>J.length-J.trimStart().length)),G=E.map((J)=>J.slice(X)).map((J)=>" ".repeat(this.indent*2)+J);for(let J of G)this.content.push(J)}compile(){let $=Function,w=this?.args,X=[...(this?.content??[""]).map((G)=>` ${G}`)];return new $(...w,X.join(`
|
|
547
|
-
`))}}var gM;var l9=R(()=>{gM={major:4,minor:0,patch:0}});function HR($){if($==="")return!0;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}function gv($){if(!p9.test($))return!1;let w=$.replace(/[-_]/g,(X)=>X==="-"?"+":"/"),E=w.padEnd(Math.ceil(w.length/4)*4,"=");return HR(E)}function uv($,w=null){try{let E=$.split(".");if(E.length!==3)return!1;let[X]=E;if(!X)return!1;let G=JSON.parse(atob(X));if("typ"in G&&G?.typ!=="JWT")return!1;if(!G.alg)return!1;if(w&&(!("alg"in G)||G.alg!==w))return!1;return!0}catch{return!1}}function uM($,w,E){if($.issues.length)w.issues.push(...Jw(E,$.issues));w.value[E]=$.value}function A4($,w,E){if($.issues.length)w.issues.push(...Jw(E,$.issues));w.value[E]=$.value}function hM($,w,E,X){if($.issues.length)if(X[E]===void 0)if(E in X)w.value[E]=void 0;else w.value[E]=$.value;else w.issues.push(...Jw(E,$.issues));else if($.value===void 0){if(E in X)w.value[E]=void 0}else w.value[E]=$.value}function cM($,w,E,X){for(let G of $)if(G.issues.length===0)return w.value=G.value,w;return w.issues.push({code:"invalid_union",input:w.value,inst:E,errors:$.map((G)=>G.issues.map((J)=>u1(J,X,R1())))}),w}function s9($,w){if($===w)return{valid:!0,data:$};if($ instanceof Date&&w instanceof Date&&+$===+w)return{valid:!0,data:$};if(CX($)&&CX(w)){let E=Object.keys(w),X=Object.keys($).filter((J)=>E.indexOf(J)!==-1),G={...$,...w};for(let J of X){let A=s9($[J],w[J]);if(!A.valid)return{valid:!1,mergeErrorPath:[J,...A.mergeErrorPath]};G[J]=A.data}return{valid:!0,data:G}}if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return{valid:!1,mergeErrorPath:[]};let E=[];for(let X=0;X<$.length;X++){let G=$[X],J=w[X],A=s9(G,J);if(!A.valid)return{valid:!1,mergeErrorPath:[X,...A.mergeErrorPath]};E.push(A.data)}return{valid:!0,data:E}}return{valid:!1,mergeErrorPath:[]}}function nM($,w,E){if(w.issues.length)$.issues.push(...w.issues);if(E.issues.length)$.issues.push(...E.issues);if(qE($))return $;let X=s9(w.value,E.value);if(!X.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(X.mergeErrorPath)}`);return $.value=X.data,$}function mM($,w){if($.value===void 0)$.value=w.defaultValue;return $}function rM($,w){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:w});return $}function pM($,w,E){if(qE($))return $;return w.out._zod.run({value:$.value,issues:$.issues},E)}function oM($){return $.value=Object.freeze($.value),$}function tM($,w,E,X){if(!$){let G={code:"custom",input:E,inst:X,path:[...X._zod.def.path??[]],continue:!X._zod.def.abort};if(X._zod.def.params)G.params=X._zod.def.params;w.issues.push(g9(G))}}var _0,D4,u0,iM,dM,lM,sM,aM,eM,$R,wR,ER,XR,GR,JR,AR,DR,NR,WR,OR,UR,YR,LR,FR,jR,MR,a9,RR,zR,TR,BR,QR,IR,KR,e9,VR,PR,qR,SR,kR,bR,ZR,CR,_R,vR,fR,xR,yR,gR,uR;var hR=R(()=>{J4();bX();m9();G4();Kw();l9();Kw();_0=S("$ZodType",($,w)=>{var E;$??($={}),$._zod.def=w,$._zod.bag=$._zod.bag||{},$._zod.version=gM;let X=[...$._zod.def.checks??[]];if($._zod.traits.has("$ZodCheck"))X.unshift($);for(let G of X)for(let J of G._zod.onattach)J($);if(X.length===0)(E=$._zod).deferred??(E.deferred=[]),$._zod.deferred?.push(()=>{$._zod.run=$._zod.parse});else{let G=(J,A,D)=>{let N=qE(J),W;for(let O of A){if(O._zod.def.when){if(!O._zod.def.when(J))continue}else if(N)continue;let Y=J.issues.length,H=O._zod.check(J);if(H instanceof Promise&&D?.async===!1)throw new iw;if(W||H instanceof Promise)W=(W??Promise.resolve()).then(async()=>{if(await H,J.issues.length===Y)return;if(!N)N=qE(J,Y)});else{if(J.issues.length===Y)continue;if(!N)N=qE(J,Y)}}if(W)return W.then(()=>{return J});return J};$._zod.run=(J,A)=>{let D=$._zod.parse(J,A);if(D instanceof Promise){if(A.async===!1)throw new iw;return D.then((N)=>G(N,X,A))}return G(D,X,A)}}$["~standard"]={validate:(G)=>{try{let J=R6($,G);return J.success?{value:J.data}:{issues:J.error?.issues}}catch(J){return X4($,G).then((A)=>A.success?{value:A.data}:{issues:A.error?.issues})}},vendor:"zod",version:1}}),D4=S("$ZodString",($,w)=>{_0.init($,w),$._zod.pattern=[...$?._zod.bag?.patterns??[]].pop()??MM($._zod.bag),$._zod.parse=(E,X)=>{if(w.coerce)try{E.value=String(E.value)}catch(G){}if(typeof E.value==="string")return E;return E.issues.push({expected:"string",code:"invalid_type",input:E.value,inst:$}),E}}),u0=S("$ZodStringFormat",($,w)=>{z6.init($,w),D4.init($,w)}),iM=S("$ZodGUID",($,w)=>{w.pattern??(w.pattern=EM),u0.init($,w)}),dM=S("$ZodUUID",($,w)=>{if(w.version){let X={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[w.version];if(X===void 0)throw Error(`Invalid UUID version: "${w.version}"`);w.pattern??(w.pattern=r9(X))}else w.pattern??(w.pattern=r9());u0.init($,w)}),lM=S("$ZodEmail",($,w)=>{w.pattern??(w.pattern=XM),u0.init($,w)}),sM=S("$ZodURL",($,w)=>{u0.init($,w),$._zod.check=(E)=>{try{let X=E.value,G=new URL(X),J=G.href;if(w.hostname){if(w.hostname.lastIndex=0,!w.hostname.test(G.hostname))E.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:OM.source,input:E.value,inst:$,continue:!w.abort})}if(w.protocol){if(w.protocol.lastIndex=0,!w.protocol.test(G.protocol.endsWith(":")?G.protocol.slice(0,-1):G.protocol))E.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:w.protocol.source,input:E.value,inst:$,continue:!w.abort})}if(!X.endsWith("/")&&J.endsWith("/"))E.value=J.slice(0,-1);else E.value=J;return}catch(X){E.issues.push({code:"invalid_format",format:"url",input:E.value,inst:$,continue:!w.abort})}}}),aM=S("$ZodEmoji",($,w)=>{w.pattern??(w.pattern=GM()),u0.init($,w)}),eM=S("$ZodNanoID",($,w)=>{w.pattern??(w.pattern=$M),u0.init($,w)}),$R=S("$ZodCUID",($,w)=>{w.pattern??(w.pattern=dj),u0.init($,w)}),wR=S("$ZodCUID2",($,w)=>{w.pattern??(w.pattern=lj),u0.init($,w)}),ER=S("$ZodULID",($,w)=>{w.pattern??(w.pattern=sj),u0.init($,w)}),XR=S("$ZodXID",($,w)=>{w.pattern??(w.pattern=aj),u0.init($,w)}),GR=S("$ZodKSUID",($,w)=>{w.pattern??(w.pattern=ej),u0.init($,w)}),JR=S("$ZodISODateTime",($,w)=>{w.pattern??(w.pattern=jM(w)),u0.init($,w)}),AR=S("$ZodISODate",($,w)=>{w.pattern??(w.pattern=HM),u0.init($,w)}),DR=S("$ZodISOTime",($,w)=>{w.pattern??(w.pattern=FM(w)),u0.init($,w)}),NR=S("$ZodISODuration",($,w)=>{w.pattern??(w.pattern=wM),u0.init($,w)}),WR=S("$ZodIPv4",($,w)=>{w.pattern??(w.pattern=JM),u0.init($,w),$._zod.onattach.push((E)=>{let X=E._zod.bag;X.format="ipv4"})}),OR=S("$ZodIPv6",($,w)=>{w.pattern??(w.pattern=AM),u0.init($,w),$._zod.onattach.push((E)=>{let X=E._zod.bag;X.format="ipv6"}),$._zod.check=(E)=>{try{new URL(`http://[${E.value}]`)}catch{E.issues.push({code:"invalid_format",format:"ipv6",input:E.value,inst:$,continue:!w.abort})}}}),UR=S("$ZodCIDRv4",($,w)=>{w.pattern??(w.pattern=DM),u0.init($,w)}),YR=S("$ZodCIDRv6",($,w)=>{w.pattern??(w.pattern=NM),u0.init($,w),$._zod.check=(E)=>{let[X,G]=E.value.split("/");try{if(!G)throw Error();let J=Number(G);if(`${J}`!==G)throw Error();if(J<0||J>128)throw Error();new URL(`http://[${X}]`)}catch{E.issues.push({code:"invalid_format",format:"cidrv6",input:E.value,inst:$,continue:!w.abort})}}});LR=S("$ZodBase64",($,w)=>{w.pattern??(w.pattern=WM),u0.init($,w),$._zod.onattach.push((E)=>{E._zod.bag.contentEncoding="base64"}),$._zod.check=(E)=>{if(HR(E.value))return;E.issues.push({code:"invalid_format",format:"base64",input:E.value,inst:$,continue:!w.abort})}});FR=S("$ZodBase64URL",($,w)=>{w.pattern??(w.pattern=p9),u0.init($,w),$._zod.onattach.push((E)=>{E._zod.bag.contentEncoding="base64url"}),$._zod.check=(E)=>{if(gv(E.value))return;E.issues.push({code:"invalid_format",format:"base64url",input:E.value,inst:$,continue:!w.abort})}}),jR=S("$ZodE164",($,w)=>{w.pattern??(w.pattern=UM),u0.init($,w)});MR=S("$ZodJWT",($,w)=>{u0.init($,w),$._zod.check=(E)=>{if(uv(E.value,w.alg))return;E.issues.push({code:"invalid_format",format:"jwt",input:E.value,inst:$,continue:!w.abort})}}),a9=S("$ZodNumber",($,w)=>{_0.init($,w),$._zod.pattern=$._zod.bag.pattern??zM,$._zod.parse=(E,X)=>{if(w.coerce)try{E.value=Number(E.value)}catch(A){}let G=E.value;if(typeof G==="number"&&!Number.isNaN(G)&&Number.isFinite(G))return E;let J=typeof G==="number"?Number.isNaN(G)?"NaN":!Number.isFinite(G)?"Infinity":void 0:void 0;return E.issues.push({expected:"number",code:"invalid_type",input:G,inst:$,...J?{received:J}:{}}),E}}),RR=S("$ZodNumber",($,w)=>{PM.init($,w),a9.init($,w)}),zR=S("$ZodBoolean",($,w)=>{_0.init($,w),$._zod.pattern=TM,$._zod.parse=(E,X)=>{if(w.coerce)try{E.value=Boolean(E.value)}catch(J){}let G=E.value;if(typeof G==="boolean")return E;return E.issues.push({expected:"boolean",code:"invalid_type",input:G,inst:$}),E}}),TR=S("$ZodNull",($,w)=>{_0.init($,w),$._zod.pattern=BM,$._zod.values=new Set([null]),$._zod.parse=(E,X)=>{let G=E.value;if(G===null)return E;return E.issues.push({expected:"null",code:"invalid_type",input:G,inst:$}),E}}),BR=S("$ZodUnknown",($,w)=>{_0.init($,w),$._zod.parse=(E)=>E}),QR=S("$ZodNever",($,w)=>{_0.init($,w),$._zod.parse=(E,X)=>{return E.issues.push({expected:"never",code:"invalid_type",input:E.value,inst:$}),E}});IR=S("$ZodArray",($,w)=>{_0.init($,w),$._zod.parse=(E,X)=>{let G=E.value;if(!Array.isArray(G))return E.issues.push({expected:"array",code:"invalid_type",input:G,inst:$}),E;E.value=Array(G.length);let J=[];for(let A=0;A<G.length;A++){let D=G[A],N=w.element._zod.run({value:D,issues:[]},X);if(N instanceof Promise)J.push(N.then((W)=>uM(W,E,A)));else uM(N,E,A)}if(J.length)return Promise.all(J).then(()=>E);return E}});KR=S("$ZodObject",($,w)=>{_0.init($,w);let E=L6(()=>{let Y=Object.keys(w.shape);for(let L of Y)if(!(w.shape[L]instanceof _0))throw Error(`Invalid element at key "${L}": expected a Zod schema`);let H=x9(w.shape);return{shape:w.shape,keys:Y,keySet:new Set(Y),numKeys:Y.length,optionalKeys:new Set(H)}});C0($._zod,"propValues",()=>{let Y=w.shape,H={};for(let L in Y){let F=Y[L]._zod;if(F.values){H[L]??(H[L]=new Set);for(let j of F.values)H[L].add(j)}}return H});let X=(Y)=>{let H=new d9(["shape","payload","ctx"]),L=E.value,F=(B)=>{let Q=PE(B);return`shape[${Q}]._zod.run({ value: input[${Q}], issues: [] }, ctx)`};H.write("const input = payload.value;");let j=Object.create(null),M=0;for(let B of L.keys)j[B]=`key_${M++}`;H.write("const newResult = {}");for(let B of L.keys)if(L.optionalKeys.has(B)){let Q=j[B];H.write(`const ${Q} = ${F(B)};`);let k=PE(B);H.write(`
|
|
547
|
+
`))}}var cM;var e9=R(()=>{cM={major:4,minor:0,patch:0}});function jR($){if($==="")return!0;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}function pv($){if(!i9.test($))return!1;let w=$.replace(/[-_]/g,(X)=>X==="-"?"+":"/"),E=w.padEnd(Math.ceil(w.length/4)*4,"=");return jR(E)}function ov($,w=null){try{let E=$.split(".");if(E.length!==3)return!1;let[X]=E;if(!X)return!1;let G=JSON.parse(atob(X));if("typ"in G&&G?.typ!=="JWT")return!1;if(!G.alg)return!1;if(w&&(!("alg"in G)||G.alg!==w))return!1;return!0}catch{return!1}}function nM($,w,E){if($.issues.length)w.issues.push(...Jw(E,$.issues));w.value[E]=$.value}function N4($,w,E){if($.issues.length)w.issues.push(...Jw(E,$.issues));w.value[E]=$.value}function mM($,w,E,X){if($.issues.length)if(X[E]===void 0)if(E in X)w.value[E]=void 0;else w.value[E]=$.value;else w.issues.push(...Jw(E,$.issues));else if($.value===void 0){if(E in X)w.value[E]=void 0}else w.value[E]=$.value}function rM($,w,E,X){for(let G of $)if(G.issues.length===0)return w.value=G.value,w;return w.issues.push({code:"invalid_union",input:w.value,inst:E,errors:$.map((G)=>G.issues.map((J)=>u1(J,X,R1())))}),w}function $5($,w){if($===w)return{valid:!0,data:$};if($ instanceof Date&&w instanceof Date&&+$===+w)return{valid:!0,data:$};if(_X($)&&_X(w)){let E=Object.keys(w),X=Object.keys($).filter((J)=>E.indexOf(J)!==-1),G={...$,...w};for(let J of X){let A=$5($[J],w[J]);if(!A.valid)return{valid:!1,mergeErrorPath:[J,...A.mergeErrorPath]};G[J]=A.data}return{valid:!0,data:G}}if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return{valid:!1,mergeErrorPath:[]};let E=[];for(let X=0;X<$.length;X++){let G=$[X],J=w[X],A=$5(G,J);if(!A.valid)return{valid:!1,mergeErrorPath:[X,...A.mergeErrorPath]};E.push(A.data)}return{valid:!0,data:E}}return{valid:!1,mergeErrorPath:[]}}function pM($,w,E){if(w.issues.length)$.issues.push(...w.issues);if(E.issues.length)$.issues.push(...E.issues);if(qE($))return $;let X=$5(w.value,E.value);if(!X.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(X.mergeErrorPath)}`);return $.value=X.data,$}function oM($,w){if($.value===void 0)$.value=w.defaultValue;return $}function tM($,w){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:w});return $}function iM($,w,E){if(qE($))return $;return w.out._zod.run({value:$.value,issues:$.issues},E)}function dM($){return $.value=Object.freeze($.value),$}function lM($,w,E,X){if(!$){let G={code:"custom",input:E,inst:X,path:[...X._zod.def.path??[]],continue:!X._zod.def.abort};if(X._zod.def.params)G.params=X._zod.def.params;w.issues.push(c9(G))}}var _0,W4,u0,sM,aM,eM,$R,wR,ER,XR,GR,JR,AR,DR,NR,WR,OR,UR,YR,HR,LR,FR,MR,RR,zR,TR,w5,BR,QR,IR,KR,VR,PR,qR,E5,SR,kR,bR,ZR,CR,_R,vR,fR,xR,yR,gR,uR,hR,cR,nR;var mR=R(()=>{D4();ZX();o9();A4();Kw();e9();Kw();_0=S("$ZodType",($,w)=>{var E;$??($={}),$._zod.def=w,$._zod.bag=$._zod.bag||{},$._zod.version=cM;let X=[...$._zod.def.checks??[]];if($._zod.traits.has("$ZodCheck"))X.unshift($);for(let G of X)for(let J of G._zod.onattach)J($);if(X.length===0)(E=$._zod).deferred??(E.deferred=[]),$._zod.deferred?.push(()=>{$._zod.run=$._zod.parse});else{let G=(J,A,D)=>{let N=qE(J),W;for(let O of A){if(O._zod.def.when){if(!O._zod.def.when(J))continue}else if(N)continue;let Y=J.issues.length,H=O._zod.check(J);if(H instanceof Promise&&D?.async===!1)throw new iw;if(W||H instanceof Promise)W=(W??Promise.resolve()).then(async()=>{if(await H,J.issues.length===Y)return;if(!N)N=qE(J,Y)});else{if(J.issues.length===Y)continue;if(!N)N=qE(J,Y)}}if(W)return W.then(()=>{return J});return J};$._zod.run=(J,A)=>{let D=$._zod.parse(J,A);if(D instanceof Promise){if(A.async===!1)throw new iw;return D.then((N)=>G(N,X,A))}return G(D,X,A)}}$["~standard"]={validate:(G)=>{try{let J=z6($,G);return J.success?{value:J.data}:{issues:J.error?.issues}}catch(J){return J4($,G).then((A)=>A.success?{value:A.data}:{issues:A.error?.issues})}},vendor:"zod",version:1}}),W4=S("$ZodString",($,w)=>{_0.init($,w),$._zod.pattern=[...$?._zod.bag?.patterns??[]].pop()??TM($._zod.bag),$._zod.parse=(E,X)=>{if(w.coerce)try{E.value=String(E.value)}catch(G){}if(typeof E.value==="string")return E;return E.issues.push({expected:"string",code:"invalid_type",input:E.value,inst:$}),E}}),u0=S("$ZodStringFormat",($,w)=>{T6.init($,w),W4.init($,w)}),sM=S("$ZodGUID",($,w)=>{w.pattern??(w.pattern=JM),u0.init($,w)}),aM=S("$ZodUUID",($,w)=>{if(w.version){let X={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[w.version];if(X===void 0)throw Error(`Invalid UUID version: "${w.version}"`);w.pattern??(w.pattern=t9(X))}else w.pattern??(w.pattern=t9());u0.init($,w)}),eM=S("$ZodEmail",($,w)=>{w.pattern??(w.pattern=AM),u0.init($,w)}),$R=S("$ZodURL",($,w)=>{u0.init($,w),$._zod.check=(E)=>{try{let X=E.value,G=new URL(X),J=G.href;if(w.hostname){if(w.hostname.lastIndex=0,!w.hostname.test(G.hostname))E.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:HM.source,input:E.value,inst:$,continue:!w.abort})}if(w.protocol){if(w.protocol.lastIndex=0,!w.protocol.test(G.protocol.endsWith(":")?G.protocol.slice(0,-1):G.protocol))E.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:w.protocol.source,input:E.value,inst:$,continue:!w.abort})}if(!X.endsWith("/")&&J.endsWith("/"))E.value=J.slice(0,-1);else E.value=J;return}catch(X){E.issues.push({code:"invalid_format",format:"url",input:E.value,inst:$,continue:!w.abort})}}}),wR=S("$ZodEmoji",($,w)=>{w.pattern??(w.pattern=DM()),u0.init($,w)}),ER=S("$ZodNanoID",($,w)=>{w.pattern??(w.pattern=XM),u0.init($,w)}),XR=S("$ZodCUID",($,w)=>{w.pattern??(w.pattern=aj),u0.init($,w)}),GR=S("$ZodCUID2",($,w)=>{w.pattern??(w.pattern=ej),u0.init($,w)}),JR=S("$ZodULID",($,w)=>{w.pattern??(w.pattern=$M),u0.init($,w)}),AR=S("$ZodXID",($,w)=>{w.pattern??(w.pattern=wM),u0.init($,w)}),DR=S("$ZodKSUID",($,w)=>{w.pattern??(w.pattern=EM),u0.init($,w)}),NR=S("$ZodISODateTime",($,w)=>{w.pattern??(w.pattern=zM(w)),u0.init($,w)}),WR=S("$ZodISODate",($,w)=>{w.pattern??(w.pattern=jM),u0.init($,w)}),OR=S("$ZodISOTime",($,w)=>{w.pattern??(w.pattern=RM(w)),u0.init($,w)}),UR=S("$ZodISODuration",($,w)=>{w.pattern??(w.pattern=GM),u0.init($,w)}),YR=S("$ZodIPv4",($,w)=>{w.pattern??(w.pattern=NM),u0.init($,w),$._zod.onattach.push((E)=>{let X=E._zod.bag;X.format="ipv4"})}),HR=S("$ZodIPv6",($,w)=>{w.pattern??(w.pattern=WM),u0.init($,w),$._zod.onattach.push((E)=>{let X=E._zod.bag;X.format="ipv6"}),$._zod.check=(E)=>{try{new URL(`http://[${E.value}]`)}catch{E.issues.push({code:"invalid_format",format:"ipv6",input:E.value,inst:$,continue:!w.abort})}}}),LR=S("$ZodCIDRv4",($,w)=>{w.pattern??(w.pattern=OM),u0.init($,w)}),FR=S("$ZodCIDRv6",($,w)=>{w.pattern??(w.pattern=UM),u0.init($,w),$._zod.check=(E)=>{let[X,G]=E.value.split("/");try{if(!G)throw Error();let J=Number(G);if(`${J}`!==G)throw Error();if(J<0||J>128)throw Error();new URL(`http://[${X}]`)}catch{E.issues.push({code:"invalid_format",format:"cidrv6",input:E.value,inst:$,continue:!w.abort})}}});MR=S("$ZodBase64",($,w)=>{w.pattern??(w.pattern=YM),u0.init($,w),$._zod.onattach.push((E)=>{E._zod.bag.contentEncoding="base64"}),$._zod.check=(E)=>{if(jR(E.value))return;E.issues.push({code:"invalid_format",format:"base64",input:E.value,inst:$,continue:!w.abort})}});RR=S("$ZodBase64URL",($,w)=>{w.pattern??(w.pattern=i9),u0.init($,w),$._zod.onattach.push((E)=>{E._zod.bag.contentEncoding="base64url"}),$._zod.check=(E)=>{if(pv(E.value))return;E.issues.push({code:"invalid_format",format:"base64url",input:E.value,inst:$,continue:!w.abort})}}),zR=S("$ZodE164",($,w)=>{w.pattern??(w.pattern=LM),u0.init($,w)});TR=S("$ZodJWT",($,w)=>{u0.init($,w),$._zod.check=(E)=>{if(ov(E.value,w.alg))return;E.issues.push({code:"invalid_format",format:"jwt",input:E.value,inst:$,continue:!w.abort})}}),w5=S("$ZodNumber",($,w)=>{_0.init($,w),$._zod.pattern=$._zod.bag.pattern??QM,$._zod.parse=(E,X)=>{if(w.coerce)try{E.value=Number(E.value)}catch(A){}let G=E.value;if(typeof G==="number"&&!Number.isNaN(G)&&Number.isFinite(G))return E;let J=typeof G==="number"?Number.isNaN(G)?"NaN":!Number.isFinite(G)?"Infinity":void 0:void 0;return E.issues.push({expected:"number",code:"invalid_type",input:G,inst:$,...J?{received:J}:{}}),E}}),BR=S("$ZodNumber",($,w)=>{kM.init($,w),w5.init($,w)}),QR=S("$ZodBoolean",($,w)=>{_0.init($,w),$._zod.pattern=IM,$._zod.parse=(E,X)=>{if(w.coerce)try{E.value=Boolean(E.value)}catch(J){}let G=E.value;if(typeof G==="boolean")return E;return E.issues.push({expected:"boolean",code:"invalid_type",input:G,inst:$}),E}}),IR=S("$ZodNull",($,w)=>{_0.init($,w),$._zod.pattern=KM,$._zod.values=new Set([null]),$._zod.parse=(E,X)=>{let G=E.value;if(G===null)return E;return E.issues.push({expected:"null",code:"invalid_type",input:G,inst:$}),E}}),KR=S("$ZodUnknown",($,w)=>{_0.init($,w),$._zod.parse=(E)=>E}),VR=S("$ZodNever",($,w)=>{_0.init($,w),$._zod.parse=(E,X)=>{return E.issues.push({expected:"never",code:"invalid_type",input:E.value,inst:$}),E}});PR=S("$ZodArray",($,w)=>{_0.init($,w),$._zod.parse=(E,X)=>{let G=E.value;if(!Array.isArray(G))return E.issues.push({expected:"array",code:"invalid_type",input:G,inst:$}),E;E.value=Array(G.length);let J=[];for(let A=0;A<G.length;A++){let D=G[A],N=w.element._zod.run({value:D,issues:[]},X);if(N instanceof Promise)J.push(N.then((W)=>nM(W,E,A)));else nM(N,E,A)}if(J.length)return Promise.all(J).then(()=>E);return E}});qR=S("$ZodObject",($,w)=>{_0.init($,w);let E=F6(()=>{let Y=Object.keys(w.shape);for(let L of Y)if(!(w.shape[L]instanceof _0))throw Error(`Invalid element at key "${L}": expected a Zod schema`);let H=u9(w.shape);return{shape:w.shape,keys:Y,keySet:new Set(Y),numKeys:Y.length,optionalKeys:new Set(H)}});C0($._zod,"propValues",()=>{let Y=w.shape,H={};for(let L in Y){let F=Y[L]._zod;if(F.values){H[L]??(H[L]=new Set);for(let j of F.values)H[L].add(j)}}return H});let X=(Y)=>{let H=new a9(["shape","payload","ctx"]),L=E.value,F=(B)=>{let Q=PE(B);return`shape[${Q}]._zod.run({ value: input[${Q}], issues: [] }, ctx)`};H.write("const input = payload.value;");let j=Object.create(null),M=0;for(let B of L.keys)j[B]=`key_${M++}`;H.write("const newResult = {}");for(let B of L.keys)if(L.optionalKeys.has(B)){let Q=j[B];H.write(`const ${Q} = ${F(B)};`);let k=PE(B);H.write(`
|
|
548
548
|
if (${Q}.issues.length) {
|
|
549
549
|
if (input[${k}] === undefined) {
|
|
550
550
|
if (${k} in input) {
|
|
@@ -567,27 +567,27 @@ ${X}
|
|
|
567
567
|
if (${Q}.issues.length) payload.issues = payload.issues.concat(${Q}.issues.map(iss => ({
|
|
568
568
|
...iss,
|
|
569
569
|
path: iss.path ? [${PE(B)}, ...iss.path] : [${PE(B)}]
|
|
570
|
-
})));`),H.write(`newResult[${PE(B)}] = ${Q}.value`)}H.write("payload.value = newResult;"),H.write("return payload;");let z=H.compile();return(B,Q)=>z(Y,B,Q)},G,J=ZX,A=!aA.jitless,N=A&&v9.value,W=w.catchall,O;$._zod.parse=(Y,H)=>{O??(O=E.value);let L=Y.value;if(!J(L))return Y.issues.push({expected:"object",code:"invalid_type",input:L,inst:$}),Y;let F=[];if(A&&N&&H?.async===!1&&H.jitless!==!0){if(!G)G=X(w.shape);Y=G(Y,H)}else{Y.value={};let Q=O.shape;for(let k of O.keys){let v=Q[k],C=v._zod.run({value:L[k],issues:[]},H),n=v._zod.optin==="optional"&&v._zod.optout==="optional";if(C instanceof Promise)F.push(C.then((T0)=>n?hM(T0,Y,k,L):A4(T0,Y,k)));else if(n)hM(C,Y,k,L);else A4(C,Y,k)}}if(!W)return F.length?Promise.all(F).then(()=>Y):Y;let j=[],M=O.keySet,z=W._zod,B=z.def.type;for(let Q of Object.keys(L)){if(M.has(Q))continue;if(B==="never"){j.push(Q);continue}let k=z.run({value:L[Q],issues:[]},H);if(k instanceof Promise)F.push(k.then((v)=>A4(v,Y,Q)));else A4(k,Y,Q)}if(j.length)Y.issues.push({code:"unrecognized_keys",keys:j,input:L,inst:$});if(!F.length)return Y;return Promise.all(F).then(()=>{return Y})}});e9=S("$ZodUnion",($,w)=>{_0.init($,w),C0($._zod,"optin",()=>w.options.some((E)=>E._zod.optin==="optional")?"optional":void 0),C0($._zod,"optout",()=>w.options.some((E)=>E._zod.optout==="optional")?"optional":void 0),C0($._zod,"values",()=>{if(w.options.every((E)=>E._zod.values))return new Set(w.options.flatMap((E)=>Array.from(E._zod.values)));return}),C0($._zod,"pattern",()=>{if(w.options.every((E)=>E._zod.pattern)){let E=w.options.map((X)=>X._zod.pattern);return new RegExp(`^(${E.map((X)=>j6(X.source)).join("|")})$`)}return}),$._zod.parse=(E,X)=>{let G=!1,J=[];for(let A of w.options){let D=A._zod.run({value:E.value,issues:[]},X);if(D instanceof Promise)J.push(D),G=!0;else{if(D.issues.length===0)return D;J.push(D)}}if(!G)return cM(J,E,$,X);return Promise.all(J).then((A)=>{return cM(A,E,$,X)})}}),VR=S("$ZodDiscriminatedUnion",($,w)=>{e9.init($,w);let E=$._zod.parse;C0($._zod,"propValues",()=>{let G={};for(let J of w.options){let A=J._zod.propValues;if(!A||Object.keys(A).length===0)throw Error(`Invalid discriminated union option at index "${w.options.indexOf(J)}"`);for(let[D,N]of Object.entries(A)){if(!G[D])G[D]=new Set;for(let W of N)G[D].add(W)}}return G});let X=L6(()=>{let G=w.options,J=new Map;for(let A of G){let D=A._zod.propValues[w.discriminator];if(!D||D.size===0)throw Error(`Invalid discriminated union option at index "${w.options.indexOf(A)}"`);for(let N of D){if(J.has(N))throw Error(`Duplicate discriminator value "${String(N)}"`);J.set(N,A)}}return J});$._zod.parse=(G,J)=>{let A=G.value;if(!ZX(A))return G.issues.push({code:"invalid_type",expected:"object",input:A,inst:$}),G;let D=X.value.get(A?.[w.discriminator]);if(D)return D._zod.run(G,J);if(w.unionFallback)return E(G,J);return G.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:A,path:[w.discriminator],inst:$}),G}}),PR=S("$ZodIntersection",($,w)=>{_0.init($,w),$._zod.parse=(E,X)=>{let G=E.value,J=w.left._zod.run({value:G,issues:[]},X),A=w.right._zod.run({value:G,issues:[]},X);if(J instanceof Promise||A instanceof Promise)return Promise.all([J,A]).then(([N,W])=>{return nM(E,N,W)});return nM(E,J,A)}});qR=S("$ZodRecord",($,w)=>{_0.init($,w),$._zod.parse=(E,X)=>{let G=E.value;if(!CX(G))return E.issues.push({expected:"record",code:"invalid_type",input:G,inst:$}),E;let J=[];if(w.keyType._zod.values){let A=w.keyType._zod.values;E.value={};for(let N of A)if(typeof N==="string"||typeof N==="number"||typeof N==="symbol"){let W=w.valueType._zod.run({value:G[N],issues:[]},X);if(W instanceof Promise)J.push(W.then((O)=>{if(O.issues.length)E.issues.push(...Jw(N,O.issues));E.value[N]=O.value}));else{if(W.issues.length)E.issues.push(...Jw(N,W.issues));E.value[N]=W.value}}let D;for(let N in G)if(!A.has(N))D=D??[],D.push(N);if(D&&D.length>0)E.issues.push({code:"unrecognized_keys",input:G,inst:$,keys:D})}else{E.value={};for(let A of Reflect.ownKeys(G)){if(A==="__proto__")continue;let D=w.keyType._zod.run({value:A,issues:[]},X);if(D instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(D.issues.length){E.issues.push({origin:"record",code:"invalid_key",issues:D.issues.map((W)=>u1(W,X,R1())),input:A,path:[A],inst:$}),E.value[D.value]=D.value;continue}let N=w.valueType._zod.run({value:G[A],issues:[]},X);if(N instanceof Promise)J.push(N.then((W)=>{if(W.issues.length)E.issues.push(...Jw(A,W.issues));E.value[D.value]=W.value}));else{if(N.issues.length)E.issues.push(...Jw(A,N.issues));E.value[D.value]=N.value}}}if(J.length)return Promise.all(J).then(()=>E);return E}}),SR=S("$ZodEnum",($,w)=>{_0.init($,w);let E=b9(w.entries);$._zod.values=new Set(E),$._zod.pattern=new RegExp(`^(${E.filter((X)=>f9.has(typeof X)).map((X)=>typeof X==="string"?dw(X):X.toString()).join("|")})$`),$._zod.parse=(X,G)=>{let J=X.value;if($._zod.values.has(J))return X;return X.issues.push({code:"invalid_value",values:E,input:J,inst:$}),X}}),kR=S("$ZodLiteral",($,w)=>{_0.init($,w),$._zod.values=new Set(w.values),$._zod.pattern=new RegExp(`^(${w.values.map((E)=>typeof E==="string"?dw(E):E?E.toString():String(E)).join("|")})$`),$._zod.parse=(E,X)=>{let G=E.value;if($._zod.values.has(G))return E;return E.issues.push({code:"invalid_value",values:w.values,input:G,inst:$}),E}}),bR=S("$ZodTransform",($,w)=>{_0.init($,w),$._zod.parse=(E,X)=>{let G=w.transform(E.value,E);if(X.async)return(G instanceof Promise?G:Promise.resolve(G)).then((A)=>{return E.value=A,E});if(G instanceof Promise)throw new iw;return E.value=G,E}}),ZR=S("$ZodOptional",($,w)=>{_0.init($,w),$._zod.optin="optional",$._zod.optout="optional",C0($._zod,"values",()=>{return w.innerType._zod.values?new Set([...w.innerType._zod.values,void 0]):void 0}),C0($._zod,"pattern",()=>{let E=w.innerType._zod.pattern;return E?new RegExp(`^(${j6(E.source)})?$`):void 0}),$._zod.parse=(E,X)=>{if(w.innerType._zod.optin==="optional")return w.innerType._zod.run(E,X);if(E.value===void 0)return E;return w.innerType._zod.run(E,X)}}),CR=S("$ZodNullable",($,w)=>{_0.init($,w),C0($._zod,"optin",()=>w.innerType._zod.optin),C0($._zod,"optout",()=>w.innerType._zod.optout),C0($._zod,"pattern",()=>{let E=w.innerType._zod.pattern;return E?new RegExp(`^(${j6(E.source)}|null)$`):void 0}),C0($._zod,"values",()=>{return w.innerType._zod.values?new Set([...w.innerType._zod.values,null]):void 0}),$._zod.parse=(E,X)=>{if(E.value===null)return E;return w.innerType._zod.run(E,X)}}),_R=S("$ZodDefault",($,w)=>{_0.init($,w),$._zod.optin="optional",C0($._zod,"values",()=>w.innerType._zod.values),$._zod.parse=(E,X)=>{if(E.value===void 0)return E.value=w.defaultValue,E;let G=w.innerType._zod.run(E,X);if(G instanceof Promise)return G.then((J)=>mM(J,w));return mM(G,w)}});vR=S("$ZodPrefault",($,w)=>{_0.init($,w),$._zod.optin="optional",C0($._zod,"values",()=>w.innerType._zod.values),$._zod.parse=(E,X)=>{if(E.value===void 0)E.value=w.defaultValue;return w.innerType._zod.run(E,X)}}),fR=S("$ZodNonOptional",($,w)=>{_0.init($,w),C0($._zod,"values",()=>{let E=w.innerType._zod.values;return E?new Set([...E].filter((X)=>X!==void 0)):void 0}),$._zod.parse=(E,X)=>{let G=w.innerType._zod.run(E,X);if(G instanceof Promise)return G.then((J)=>rM(J,$));return rM(G,$)}});xR=S("$ZodCatch",($,w)=>{_0.init($,w),$._zod.optin="optional",C0($._zod,"optout",()=>w.innerType._zod.optout),C0($._zod,"values",()=>w.innerType._zod.values),$._zod.parse=(E,X)=>{let G=w.innerType._zod.run(E,X);if(G instanceof Promise)return G.then((J)=>{if(E.value=J.value,J.issues.length)E.value=w.catchValue({...E,error:{issues:J.issues.map((A)=>u1(A,X,R1()))},input:E.value}),E.issues=[];return E});if(E.value=G.value,G.issues.length)E.value=w.catchValue({...E,error:{issues:G.issues.map((J)=>u1(J,X,R1()))},input:E.value}),E.issues=[];return E}}),yR=S("$ZodPipe",($,w)=>{_0.init($,w),C0($._zod,"values",()=>w.in._zod.values),C0($._zod,"optin",()=>w.in._zod.optin),C0($._zod,"optout",()=>w.out._zod.optout),$._zod.parse=(E,X)=>{let G=w.in._zod.run(E,X);if(G instanceof Promise)return G.then((J)=>pM(J,w,X));return pM(G,w,X)}});gR=S("$ZodReadonly",($,w)=>{_0.init($,w),C0($._zod,"propValues",()=>w.innerType._zod.propValues),C0($._zod,"values",()=>w.innerType._zod.values),C0($._zod,"optin",()=>w.innerType._zod.optin),C0($._zod,"optout",()=>w.innerType._zod.optout),$._zod.parse=(E,X)=>{let G=w.innerType._zod.run(E,X);if(G instanceof Promise)return G.then(oM);return oM(G)}});uR=S("$ZodCustom",($,w)=>{b$.init($,w),_0.init($,w),$._zod.parse=(E,X)=>{return E},$._zod.check=(E)=>{let X=E.value,G=w.fn(X);if(G instanceof Promise)return G.then((J)=>tM(J,E,X,$));tM(G,E,X,$);return}})});function $5(){return{localeError:cv()}}var hv=($)=>{let w=typeof $;switch(w){case"number":return Number.isNaN($)?"NaN":"number";case"object":{if(Array.isArray($))return"array";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return w},cv=()=>{let $={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function w(X){return $[X]??null}let E={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return(X)=>{switch(X.code){case"invalid_type":return`Invalid input: expected ${X.expected}, received ${hv(X.input)}`;case"invalid_value":if(X.values.length===1)return`Invalid input: expected ${w4(X.values[0])}`;return`Invalid option: expected one of ${eA(X.values,"|")}`;case"too_big":{let G=X.inclusive?"<=":"<",J=w(X.origin);if(J)return`Too big: expected ${X.origin??"value"} to have ${G}${X.maximum.toString()} ${J.unit??"elements"}`;return`Too big: expected ${X.origin??"value"} to be ${G}${X.maximum.toString()}`}case"too_small":{let G=X.inclusive?">=":">",J=w(X.origin);if(J)return`Too small: expected ${X.origin} to have ${G}${X.minimum.toString()} ${J.unit}`;return`Too small: expected ${X.origin} to be ${G}${X.minimum.toString()}`}case"invalid_format":{let G=X;if(G.format==="starts_with")return`Invalid string: must start with "${G.prefix}"`;if(G.format==="ends_with")return`Invalid string: must end with "${G.suffix}"`;if(G.format==="includes")return`Invalid string: must include "${G.includes}"`;if(G.format==="regex")return`Invalid string: must match pattern ${G.pattern}`;return`Invalid ${E[G.format]??X.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${X.divisor}`;case"unrecognized_keys":return`Unrecognized key${X.keys.length>1?"s":""}: ${eA(X.keys,", ")}`;case"invalid_key":return`Invalid key in ${X.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${X.origin}`;default:return"Invalid input"}}};var cR=R(()=>{Kw()});var N4=()=>{};class nR{constructor(){this._map=new Map,this._idmap=new Map}add($,...w){let E=w[0];if(this._map.set($,E),E&&typeof E==="object"&&"id"in E){if(this._idmap.has(E.id))throw Error(`ID ${E.id} already exists in the registry`);this._idmap.set(E.id,$)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove($){let w=this._map.get($);if(w&&typeof w==="object"&&"id"in w)this._idmap.delete(w.id);return this._map.delete($),this}get($){let w=$._zod.parent;if(w){let E={...this.get(w)??{}};return delete E.id,{...E,...this._map.get($)}}return this._map.get($)}has($){return this._map.has($)}}function nv(){return new nR}var vG0,fG0,T6;var mR=R(()=>{vG0=Symbol("ZodOutput"),fG0=Symbol("ZodInput");T6=nv()});function rR($,w){return new $({type:"string",...l(w)})}function pR($,w){return new $({type:"string",format:"email",check:"string_format",abort:!1,...l(w)})}function E5($,w){return new $({type:"string",format:"guid",check:"string_format",abort:!1,...l(w)})}function oR($,w){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,...l(w)})}function tR($,w){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...l(w)})}function iR($,w){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...l(w)})}function dR($,w){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...l(w)})}function lR($,w){return new $({type:"string",format:"url",check:"string_format",abort:!1,...l(w)})}function sR($,w){return new $({type:"string",format:"emoji",check:"string_format",abort:!1,...l(w)})}function aR($,w){return new $({type:"string",format:"nanoid",check:"string_format",abort:!1,...l(w)})}function eR($,w){return new $({type:"string",format:"cuid",check:"string_format",abort:!1,...l(w)})}function $z($,w){return new $({type:"string",format:"cuid2",check:"string_format",abort:!1,...l(w)})}function wz($,w){return new $({type:"string",format:"ulid",check:"string_format",abort:!1,...l(w)})}function Ez($,w){return new $({type:"string",format:"xid",check:"string_format",abort:!1,...l(w)})}function Xz($,w){return new $({type:"string",format:"ksuid",check:"string_format",abort:!1,...l(w)})}function Gz($,w){return new $({type:"string",format:"ipv4",check:"string_format",abort:!1,...l(w)})}function Jz($,w){return new $({type:"string",format:"ipv6",check:"string_format",abort:!1,...l(w)})}function Az($,w){return new $({type:"string",format:"cidrv4",check:"string_format",abort:!1,...l(w)})}function Dz($,w){return new $({type:"string",format:"cidrv6",check:"string_format",abort:!1,...l(w)})}function Nz($,w){return new $({type:"string",format:"base64",check:"string_format",abort:!1,...l(w)})}function Wz($,w){return new $({type:"string",format:"base64url",check:"string_format",abort:!1,...l(w)})}function Oz($,w){return new $({type:"string",format:"e164",check:"string_format",abort:!1,...l(w)})}function Uz($,w){return new $({type:"string",format:"jwt",check:"string_format",abort:!1,...l(w)})}function Yz($,w){return new $({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...l(w)})}function Hz($,w){return new $({type:"string",format:"date",check:"string_format",...l(w)})}function Lz($,w){return new $({type:"string",format:"time",check:"string_format",precision:null,...l(w)})}function Fz($,w){return new $({type:"string",format:"duration",check:"string_format",...l(w)})}function jz($,w){return new $({type:"number",checks:[],...l(w)})}function Mz($,w){return new $({type:"number",check:"number_format",abort:!1,format:"safeint",...l(w)})}function Rz($,w){return new $({type:"boolean",...l(w)})}function zz($,w){return new $({type:"null",...l(w)})}function Tz($){return new $({type:"unknown"})}function Bz($,w){return new $({type:"never",...l(w)})}function W4($,w){return new t9({check:"less_than",...l(w),value:$,inclusive:!1})}function B6($,w){return new t9({check:"less_than",...l(w),value:$,inclusive:!0})}function O4($,w){return new i9({check:"greater_than",...l(w),value:$,inclusive:!1})}function Q6($,w){return new i9({check:"greater_than",...l(w),value:$,inclusive:!0})}function U4($,w){return new VM({check:"multiple_of",...l(w),value:$})}function Y4($,w){return new qM({check:"max_length",...l(w),maximum:$})}function _X($,w){return new SM({check:"min_length",...l(w),minimum:$})}function H4($,w){return new kM({check:"length_equals",...l(w),length:$})}function X5($,w){return new bM({check:"string_format",format:"regex",...l(w),pattern:$})}function G5($){return new ZM({check:"string_format",format:"lowercase",...l($)})}function J5($){return new CM({check:"string_format",format:"uppercase",...l($)})}function A5($,w){return new _M({check:"string_format",format:"includes",...l(w),includes:$})}function D5($,w){return new vM({check:"string_format",format:"starts_with",...l(w),prefix:$})}function N5($,w){return new fM({check:"string_format",format:"ends_with",...l(w),suffix:$})}function SE($){return new xM({check:"overwrite",tx:$})}function W5($){return SE((w)=>w.normalize($))}function O5(){return SE(($)=>$.trim())}function U5(){return SE(($)=>$.toLowerCase())}function Y5(){return SE(($)=>$.toUpperCase())}function Qz($,w,E){return new $({type:"array",element:w,...l(E)})}function Iz($,w,E){let X=l(E);return X.abort??(X.abort=!0),new $({type:"custom",check:"custom",fn:w,...X})}function Kz($,w,E){return new $({type:"custom",check:"custom",fn:w,...l(E)})}var Vz=R(()=>{J4();Kw()});var Pz=()=>{};var qz=()=>{};var Sz=()=>{};var z1=R(()=>{Kw();G4();N4();Sz();bX();m9();h9();hR();J4();l9();mR();Pz();Vz();qz()});var kz=R(()=>{z1()});var bz=()=>{};var Zz=()=>{};var Cz=()=>{};var _z=()=>{};var vz=R(()=>{z1();N4();Cz();_z();kz();bz();Zz()});var fz=R(()=>{vz()});var xz=R(()=>{fz()});function fX($){return!!$._zod}function lw($,w){if(fX($))return R6($,w);return $.safeParse(w)}function L4($){if(!$)return;let w;if(fX($))w=$._zod?.def?.shape;else w=$.shape;if(!w)return;if(typeof w==="function")try{return w()}catch{return}return w}function yz($){if(fX($)){let J=$._zod?.def;if(J){if(J.value!==void 0)return J.value;if(Array.isArray(J.values)&&J.values.length>0)return J.values[0]}}let E=$._def;if(E){if(E.value!==void 0)return E.value;if(Array.isArray(E.values)&&E.values.length>0)return E.values[0]}let X=$.value;if(X!==void 0)return X;return}var F4=R(()=>{xz()});var H5=R(()=>{z1()});var I6={};Ww(I6,{time:()=>j5,duration:()=>M5,datetime:()=>L5,date:()=>F5,ZodISOTime:()=>hz,ZodISODuration:()=>cz,ZodISODateTime:()=>gz,ZodISODate:()=>uz});function L5($){return Yz(gz,$)}function F5($){return Hz(uz,$)}function j5($){return Lz(hz,$)}function M5($){return Fz(cz,$)}var gz,uz,hz,cz;var R5=R(()=>{z1();z5();gz=S("ZodISODateTime",($,w)=>{JR.init($,w),o0.init($,w)});uz=S("ZodISODate",($,w)=>{AR.init($,w),o0.init($,w)});hz=S("ZodISOTime",($,w)=>{DR.init($,w),o0.init($,w)});cz=S("ZodISODuration",($,w)=>{NR.init($,w),o0.init($,w)})});var nz=($,w)=>{E4.init($,w),$.name="ZodError",Object.defineProperties($,{format:{value:(E)=>oj($,E)},flatten:{value:(E)=>pj($,E)},addIssue:{value:(E)=>$.issues.push(E)},addIssues:{value:(E)=>$.issues.push(...E)},isEmpty:{get(){return $.issues.length===0}}})},V60,K6;var T5=R(()=>{z1();z1();V60=S("ZodError",nz),K6=S("ZodError",nz,{Parent:Error})});var mz,rz,pz,oz;var B5=R(()=>{z1();T5();mz=tj(K6),rz=ij(K6),pz=c9(K6),oz=n9(K6)});function P($){return rR(ev,$)}function q0($){return jz(sz,$)}function iz($){return Mz(Mf,$)}function F$($){return Rz(Rf,$)}function K5($){return zz(zf,$)}function t0(){return Tz(Tf)}function Qf($){return Bz(Bf,$)}function j0($,w){return Qz(If,$,w)}function u($,w){let E={type:"object",get shape(){return B0.assignProp(this,"shape",{...$}),this.shape},...B0.normalizeParams(w)};return new az(E)}function h$($,w){return new az({type:"object",get shape(){return B0.assignProp(this,"shape",{...$}),this.shape},catchall:t0(),...B0.normalizeParams(w)})}function v0($,w){return new ez({type:"union",options:$,...B0.normalizeParams(w)})}function V5($,w,E){return new Kf({type:"union",options:w,discriminator:$,...B0.normalizeParams(E)})}function M4($,w){return new Vf({type:"intersection",left:$,right:w})}function i0($,w,E){return new Pf({type:"record",keyType:$,valueType:w,...B0.normalizeParams(E)})}function a$($,w){let E=Array.isArray($)?Object.fromEntries($.map((X)=>[X,X])):$;return new Q5({type:"enum",entries:E,...B0.normalizeParams(w)})}function p($,w){return new qf({type:"literal",values:Array.isArray($)?$:[$],...B0.normalizeParams(w)})}function $T($){return new Sf({type:"transform",transform:$})}function a0($){return new wT({type:"optional",innerType:$})}function dz($){return new kf({type:"nullable",innerType:$})}function Zf($,w){return new bf({type:"default",innerType:$,get defaultValue(){return typeof w==="function"?w():w}})}function _f($,w){return new Cf({type:"prefault",innerType:$,get defaultValue(){return typeof w==="function"?w():w}})}function vf($,w){return new ET({type:"nonoptional",innerType:$,...B0.normalizeParams(w)})}function xf($,w){return new ff({type:"catch",innerType:$,catchValue:typeof w==="function"?w:()=>w})}function I5($,w){return new yf({type:"pipe",in:$,out:w})}function uf($){return new gf({type:"readonly",innerType:$})}function hf($){let w=new b$({check:"custom"});return w._zod.check=$,w}function GT($,w){return Iz(XT,$??(()=>!0),w)}function cf($,w={}){return Kz(XT,$,w)}function nf($){let w=hf((E)=>{return E.addIssue=(X)=>{if(typeof X==="string")E.issues.push(B0.issue(X,E.value,w._zod.def));else{let G=X;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=E.value),G.inst??(G.inst=w),G.continue??(G.continue=!w._zod.def.abort),E.issues.push(B0.issue(G))}},$(E.value,E)});return w}function P5($,w){return I5($T($),w)}var e0,lz,ev,o0,$f,tz,j4,wf,Ef,Xf,Gf,Jf,Af,Df,Nf,Wf,Of,Uf,Yf,Hf,Lf,Ff,jf,sz,Mf,Rf,zf,Tf,Bf,If,az,ez,Kf,Vf,Pf,Q5,qf,Sf,wT,kf,bf,Cf,ET,ff,yf,gf,XT;var z5=R(()=>{z1();z1();H5();R5();B5();e0=S("ZodType",($,w)=>{return _0.init($,w),$.def=w,Object.defineProperty($,"_def",{value:w}),$.check=(...E)=>{return $.clone({...w,checks:[...w.checks??[],...E.map((X)=>typeof X==="function"?{_zod:{check:X,def:{check:"custom"},onattach:[]}}:X)]})},$.clone=(E,X)=>Gw($,E,X),$.brand=()=>$,$.register=(E,X)=>{return E.add($,X),$},$.parse=(E,X)=>mz($,E,X,{callee:$.parse}),$.safeParse=(E,X)=>pz($,E,X),$.parseAsync=async(E,X)=>rz($,E,X,{callee:$.parseAsync}),$.safeParseAsync=async(E,X)=>oz($,E,X),$.spa=$.safeParseAsync,$.refine=(E,X)=>$.check(cf(E,X)),$.superRefine=(E)=>$.check(nf(E)),$.overwrite=(E)=>$.check(SE(E)),$.optional=()=>a0($),$.nullable=()=>dz($),$.nullish=()=>a0(dz($)),$.nonoptional=(E)=>vf($,E),$.array=()=>j0($),$.or=(E)=>v0([$,E]),$.and=(E)=>M4($,E),$.transform=(E)=>I5($,$T(E)),$.default=(E)=>Zf($,E),$.prefault=(E)=>_f($,E),$.catch=(E)=>xf($,E),$.pipe=(E)=>I5($,E),$.readonly=()=>uf($),$.describe=(E)=>{let X=$.clone();return T6.add(X,{description:E}),X},Object.defineProperty($,"description",{get(){return T6.get($)?.description},configurable:!0}),$.meta=(...E)=>{if(E.length===0)return T6.get($);let X=$.clone();return T6.add(X,E[0]),X},$.isOptional=()=>$.safeParse(void 0).success,$.isNullable=()=>$.safeParse(null).success,$}),lz=S("_ZodString",($,w)=>{D4.init($,w),e0.init($,w);let E=$._zod.bag;$.format=E.format??null,$.minLength=E.minimum??null,$.maxLength=E.maximum??null,$.regex=(...X)=>$.check(X5(...X)),$.includes=(...X)=>$.check(A5(...X)),$.startsWith=(...X)=>$.check(D5(...X)),$.endsWith=(...X)=>$.check(N5(...X)),$.min=(...X)=>$.check(_X(...X)),$.max=(...X)=>$.check(Y4(...X)),$.length=(...X)=>$.check(H4(...X)),$.nonempty=(...X)=>$.check(_X(1,...X)),$.lowercase=(X)=>$.check(G5(X)),$.uppercase=(X)=>$.check(J5(X)),$.trim=()=>$.check(O5()),$.normalize=(...X)=>$.check(W5(...X)),$.toLowerCase=()=>$.check(U5()),$.toUpperCase=()=>$.check(Y5())}),ev=S("ZodString",($,w)=>{D4.init($,w),lz.init($,w),$.email=(E)=>$.check(pR($f,E)),$.url=(E)=>$.check(lR(wf,E)),$.jwt=(E)=>$.check(Uz(jf,E)),$.emoji=(E)=>$.check(sR(Ef,E)),$.guid=(E)=>$.check(E5(tz,E)),$.uuid=(E)=>$.check(oR(j4,E)),$.uuidv4=(E)=>$.check(tR(j4,E)),$.uuidv6=(E)=>$.check(iR(j4,E)),$.uuidv7=(E)=>$.check(dR(j4,E)),$.nanoid=(E)=>$.check(aR(Xf,E)),$.guid=(E)=>$.check(E5(tz,E)),$.cuid=(E)=>$.check(eR(Gf,E)),$.cuid2=(E)=>$.check($z(Jf,E)),$.ulid=(E)=>$.check(wz(Af,E)),$.base64=(E)=>$.check(Nz(Hf,E)),$.base64url=(E)=>$.check(Wz(Lf,E)),$.xid=(E)=>$.check(Ez(Df,E)),$.ksuid=(E)=>$.check(Xz(Nf,E)),$.ipv4=(E)=>$.check(Gz(Wf,E)),$.ipv6=(E)=>$.check(Jz(Of,E)),$.cidrv4=(E)=>$.check(Az(Uf,E)),$.cidrv6=(E)=>$.check(Dz(Yf,E)),$.e164=(E)=>$.check(Oz(Ff,E)),$.datetime=(E)=>$.check(L5(E)),$.date=(E)=>$.check(F5(E)),$.time=(E)=>$.check(j5(E)),$.duration=(E)=>$.check(M5(E))});o0=S("ZodStringFormat",($,w)=>{u0.init($,w),lz.init($,w)}),$f=S("ZodEmail",($,w)=>{lM.init($,w),o0.init($,w)}),tz=S("ZodGUID",($,w)=>{iM.init($,w),o0.init($,w)}),j4=S("ZodUUID",($,w)=>{dM.init($,w),o0.init($,w)}),wf=S("ZodURL",($,w)=>{sM.init($,w),o0.init($,w)}),Ef=S("ZodEmoji",($,w)=>{aM.init($,w),o0.init($,w)}),Xf=S("ZodNanoID",($,w)=>{eM.init($,w),o0.init($,w)}),Gf=S("ZodCUID",($,w)=>{$R.init($,w),o0.init($,w)}),Jf=S("ZodCUID2",($,w)=>{wR.init($,w),o0.init($,w)}),Af=S("ZodULID",($,w)=>{ER.init($,w),o0.init($,w)}),Df=S("ZodXID",($,w)=>{XR.init($,w),o0.init($,w)}),Nf=S("ZodKSUID",($,w)=>{GR.init($,w),o0.init($,w)}),Wf=S("ZodIPv4",($,w)=>{WR.init($,w),o0.init($,w)}),Of=S("ZodIPv6",($,w)=>{OR.init($,w),o0.init($,w)}),Uf=S("ZodCIDRv4",($,w)=>{UR.init($,w),o0.init($,w)}),Yf=S("ZodCIDRv6",($,w)=>{YR.init($,w),o0.init($,w)}),Hf=S("ZodBase64",($,w)=>{LR.init($,w),o0.init($,w)}),Lf=S("ZodBase64URL",($,w)=>{FR.init($,w),o0.init($,w)}),Ff=S("ZodE164",($,w)=>{jR.init($,w),o0.init($,w)}),jf=S("ZodJWT",($,w)=>{MR.init($,w),o0.init($,w)}),sz=S("ZodNumber",($,w)=>{a9.init($,w),e0.init($,w),$.gt=(X,G)=>$.check(O4(X,G)),$.gte=(X,G)=>$.check(Q6(X,G)),$.min=(X,G)=>$.check(Q6(X,G)),$.lt=(X,G)=>$.check(W4(X,G)),$.lte=(X,G)=>$.check(B6(X,G)),$.max=(X,G)=>$.check(B6(X,G)),$.int=(X)=>$.check(iz(X)),$.safe=(X)=>$.check(iz(X)),$.positive=(X)=>$.check(O4(0,X)),$.nonnegative=(X)=>$.check(Q6(0,X)),$.negative=(X)=>$.check(W4(0,X)),$.nonpositive=(X)=>$.check(B6(0,X)),$.multipleOf=(X,G)=>$.check(U4(X,G)),$.step=(X,G)=>$.check(U4(X,G)),$.finite=()=>$;let E=$._zod.bag;$.minValue=Math.max(E.minimum??Number.NEGATIVE_INFINITY,E.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,$.maxValue=Math.min(E.maximum??Number.POSITIVE_INFINITY,E.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,$.isInt=(E.format??"").includes("int")||Number.isSafeInteger(E.multipleOf??0.5),$.isFinite=!0,$.format=E.format??null});Mf=S("ZodNumberFormat",($,w)=>{RR.init($,w),sz.init($,w)});Rf=S("ZodBoolean",($,w)=>{zR.init($,w),e0.init($,w)});zf=S("ZodNull",($,w)=>{TR.init($,w),e0.init($,w)});Tf=S("ZodUnknown",($,w)=>{BR.init($,w),e0.init($,w)});Bf=S("ZodNever",($,w)=>{QR.init($,w),e0.init($,w)});If=S("ZodArray",($,w)=>{IR.init($,w),e0.init($,w),$.element=w.element,$.min=(E,X)=>$.check(_X(E,X)),$.nonempty=(E)=>$.check(_X(1,E)),$.max=(E,X)=>$.check(Y4(E,X)),$.length=(E,X)=>$.check(H4(E,X)),$.unwrap=()=>$.element});az=S("ZodObject",($,w)=>{KR.init($,w),e0.init($,w),B0.defineLazy($,"shape",()=>w.shape),$.keyof=()=>a$(Object.keys($._zod.def.shape)),$.catchall=(E)=>$.clone({...$._zod.def,catchall:E}),$.passthrough=()=>$.clone({...$._zod.def,catchall:t0()}),$.loose=()=>$.clone({...$._zod.def,catchall:t0()}),$.strict=()=>$.clone({...$._zod.def,catchall:Qf()}),$.strip=()=>$.clone({...$._zod.def,catchall:void 0}),$.extend=(E)=>{return B0.extend($,E)},$.merge=(E)=>B0.merge($,E),$.pick=(E)=>B0.pick($,E),$.omit=(E)=>B0.omit($,E),$.partial=(...E)=>B0.partial(wT,$,E[0]),$.required=(...E)=>B0.required(ET,$,E[0])});ez=S("ZodUnion",($,w)=>{e9.init($,w),e0.init($,w),$.options=w.options});Kf=S("ZodDiscriminatedUnion",($,w)=>{ez.init($,w),VR.init($,w)});Vf=S("ZodIntersection",($,w)=>{PR.init($,w),e0.init($,w)});Pf=S("ZodRecord",($,w)=>{qR.init($,w),e0.init($,w),$.keyType=w.keyType,$.valueType=w.valueType});Q5=S("ZodEnum",($,w)=>{SR.init($,w),e0.init($,w),$.enum=w.entries,$.options=Object.values(w.entries);let E=new Set(Object.keys(w.entries));$.extract=(X,G)=>{let J={};for(let A of X)if(E.has(A))J[A]=w.entries[A];else throw Error(`Key ${A} not found in enum`);return new Q5({...w,checks:[],...B0.normalizeParams(G),entries:J})},$.exclude=(X,G)=>{let J={...w.entries};for(let A of X)if(E.has(A))delete J[A];else throw Error(`Key ${A} not found in enum`);return new Q5({...w,checks:[],...B0.normalizeParams(G),entries:J})}});qf=S("ZodLiteral",($,w)=>{kR.init($,w),e0.init($,w),$.values=new Set(w.values),Object.defineProperty($,"value",{get(){if(w.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return w.values[0]}})});Sf=S("ZodTransform",($,w)=>{bR.init($,w),e0.init($,w),$._zod.parse=(E,X)=>{E.addIssue=(J)=>{if(typeof J==="string")E.issues.push(B0.issue(J,E.value,w));else{let A=J;if(A.fatal)A.continue=!1;A.code??(A.code="custom"),A.input??(A.input=E.value),A.inst??(A.inst=$),A.continue??(A.continue=!0),E.issues.push(B0.issue(A))}};let G=w.transform(E.value,E);if(G instanceof Promise)return G.then((J)=>{return E.value=J,E});return E.value=G,E}});wT=S("ZodOptional",($,w)=>{ZR.init($,w),e0.init($,w),$.unwrap=()=>$._zod.def.innerType});kf=S("ZodNullable",($,w)=>{CR.init($,w),e0.init($,w),$.unwrap=()=>$._zod.def.innerType});bf=S("ZodDefault",($,w)=>{_R.init($,w),e0.init($,w),$.unwrap=()=>$._zod.def.innerType,$.removeDefault=$.unwrap});Cf=S("ZodPrefault",($,w)=>{vR.init($,w),e0.init($,w),$.unwrap=()=>$._zod.def.innerType});ET=S("ZodNonOptional",($,w)=>{fR.init($,w),e0.init($,w),$.unwrap=()=>$._zod.def.innerType});ff=S("ZodCatch",($,w)=>{xR.init($,w),e0.init($,w),$.unwrap=()=>$._zod.def.innerType,$.removeCatch=$.unwrap});yf=S("ZodPipe",($,w)=>{yR.init($,w),e0.init($,w),$.in=w.in,$.out=w.out});gf=S("ZodReadonly",($,w)=>{gR.init($,w),e0.init($,w)});XT=S("ZodCustom",($,w)=>{uR.init($,w),e0.init($,w)})});var JT=()=>{};var AT=()=>{};var DT=R(()=>{z1();z1();cR();N4();R5();AT();z5();H5();T5();B5();JT();R1($5())});var NT=R(()=>{DT()});var WT=R(()=>{NT()});var q5="2025-11-25",OT,sw="io.modelcontextprotocol/related-task",z4="2.0",T$,UT,YT,TJ0,pf,of,S5,W1,V6,HT=($)=>V6.safeParse($).success,B$,T1,B1,Q$,T4,LT,k5=($)=>LT.safeParse($).success,FT,jT=($)=>FT.safeParse($).success,b5,P6=($)=>b5.safeParse($).success,L0,Z5,MT=($)=>Z5.safeParse($).success,RT,BJ0,B4,tf,Q4,df,q6,xX,zT,lf,sf,af,ef,$x,wx,C5,Ex,Xx,_5,I4,Gx,Jx,K4,Ax,S6,k6,Dx,b6,yX,Nx,Z6,V4,P4,q4,QJ0,S4,k4,b4,TT,BT,QT,v5,IT,C6,gX,KT,Wx,Ox,Ux,Yx,Hx,f5,Lx,Fx,jx,Mx,Rx,zx,Tx,Bx,Qx,Ix,Kx,Vx,Px,qx,Sx,kx,x5,y5,g5,bx,Zx,Cx,u5,_x,vx,fx,xx,yx,VT,h5,gx,Z4,IJ0,ux,_6,hx,KJ0,v6,cx,c5,nx,mx,rx,px,ox,tx,ix,R4,dx,lx,sx,f6,n5,ax,ex,$y,wy,Ey,Xy,Gy,Jy,Ay,Dy,Ny,Wy,Oy,Uy,Yy,Hy,Ly,Fy,uX,jy,My,Ry,zy,Ty,By,Qy,m5,Iy,VJ0,PJ0,qJ0,SJ0,kJ0,bJ0,A0,PT;var hX=R(()=>{WT();OT=[q5,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],T$=GT(($)=>$!==null&&(typeof $==="object"||typeof $==="function")),UT=v0([P(),q0().int()]),YT=P(),TJ0=h$({ttl:v0([q0(),K5()]).optional(),pollInterval:q0().optional()}),pf=u({ttl:q0().optional()}),of=u({taskId:P()}),S5=h$({progressToken:UT.optional(),[sw]:of.optional()}),W1=u({_meta:S5.optional()}),V6=W1.extend({task:pf.optional()}),B$=u({method:P(),params:W1.loose().optional()}),T1=u({_meta:S5.optional()}),B1=u({method:P(),params:T1.loose().optional()}),Q$=h$({_meta:S5.optional()}),T4=v0([P(),q0().int()]),LT=u({jsonrpc:p(z4),id:T4,...B$.shape}).strict(),FT=u({jsonrpc:p(z4),...B1.shape}).strict(),b5=u({jsonrpc:p(z4),id:T4,result:Q$}).strict();(function($){$[$.ConnectionClosed=-32000]="ConnectionClosed",$[$.RequestTimeout=-32001]="RequestTimeout",$[$.ParseError=-32700]="ParseError",$[$.InvalidRequest=-32600]="InvalidRequest",$[$.MethodNotFound=-32601]="MethodNotFound",$[$.InvalidParams=-32602]="InvalidParams",$[$.InternalError=-32603]="InternalError",$[$.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(L0||(L0={}));Z5=u({jsonrpc:p(z4),id:T4.optional(),error:u({code:q0().int(),message:P(),data:t0().optional()})}).strict(),RT=v0([LT,FT,b5,Z5]),BJ0=v0([b5,Z5]),B4=Q$.strict(),tf=T1.extend({requestId:T4.optional(),reason:P().optional()}),Q4=B1.extend({method:p("notifications/cancelled"),params:tf}),df=u({src:P(),mimeType:P().optional(),sizes:j0(P()).optional(),theme:a$(["light","dark"]).optional()}),q6=u({icons:j0(df).optional()}),xX=u({name:P(),title:P().optional()}),zT=xX.extend({...xX.shape,...q6.shape,version:P(),websiteUrl:P().optional(),description:P().optional()}),lf=M4(u({applyDefaults:F$().optional()}),i0(P(),t0())),sf=P5(($)=>{if($&&typeof $==="object"&&!Array.isArray($)){if(Object.keys($).length===0)return{form:{}}}return $},M4(u({form:lf.optional(),url:T$.optional()}),i0(P(),t0()).optional())),af=h$({list:T$.optional(),cancel:T$.optional(),requests:h$({sampling:h$({createMessage:T$.optional()}).optional(),elicitation:h$({create:T$.optional()}).optional()}).optional()}),ef=h$({list:T$.optional(),cancel:T$.optional(),requests:h$({tools:h$({call:T$.optional()}).optional()}).optional()}),$x=u({experimental:i0(P(),T$).optional(),sampling:u({context:T$.optional(),tools:T$.optional()}).optional(),elicitation:sf.optional(),roots:u({listChanged:F$().optional()}).optional(),tasks:af.optional()}),wx=W1.extend({protocolVersion:P(),capabilities:$x,clientInfo:zT}),C5=B$.extend({method:p("initialize"),params:wx}),Ex=u({experimental:i0(P(),T$).optional(),logging:T$.optional(),completions:T$.optional(),prompts:u({listChanged:F$().optional()}).optional(),resources:u({subscribe:F$().optional(),listChanged:F$().optional()}).optional(),tools:u({listChanged:F$().optional()}).optional(),tasks:ef.optional()}),Xx=Q$.extend({protocolVersion:P(),capabilities:Ex,serverInfo:zT,instructions:P().optional()}),_5=B1.extend({method:p("notifications/initialized"),params:T1.optional()}),I4=B$.extend({method:p("ping"),params:W1.optional()}),Gx=u({progress:q0(),total:a0(q0()),message:a0(P())}),Jx=u({...T1.shape,...Gx.shape,progressToken:UT}),K4=B1.extend({method:p("notifications/progress"),params:Jx}),Ax=W1.extend({cursor:YT.optional()}),S6=B$.extend({params:Ax.optional()}),k6=Q$.extend({nextCursor:YT.optional()}),Dx=a$(["working","input_required","completed","failed","cancelled"]),b6=u({taskId:P(),status:Dx,ttl:v0([q0(),K5()]),createdAt:P(),lastUpdatedAt:P(),pollInterval:a0(q0()),statusMessage:a0(P())}),yX=Q$.extend({task:b6}),Nx=T1.merge(b6),Z6=B1.extend({method:p("notifications/tasks/status"),params:Nx}),V4=B$.extend({method:p("tasks/get"),params:W1.extend({taskId:P()})}),P4=Q$.merge(b6),q4=B$.extend({method:p("tasks/result"),params:W1.extend({taskId:P()})}),QJ0=Q$.loose(),S4=S6.extend({method:p("tasks/list")}),k4=k6.extend({tasks:j0(b6)}),b4=B$.extend({method:p("tasks/cancel"),params:W1.extend({taskId:P()})}),TT=Q$.merge(b6),BT=u({uri:P(),mimeType:a0(P()),_meta:i0(P(),t0()).optional()}),QT=BT.extend({text:P()}),v5=P().refine(($)=>{try{return atob($),!0}catch{return!1}},{message:"Invalid Base64 string"}),IT=BT.extend({blob:v5}),C6=a$(["user","assistant"]),gX=u({audience:j0(C6).optional(),priority:q0().min(0).max(1).optional(),lastModified:I6.datetime({offset:!0}).optional()}),KT=u({...xX.shape,...q6.shape,uri:P(),description:a0(P()),mimeType:a0(P()),annotations:gX.optional(),_meta:a0(h$({}))}),Wx=u({...xX.shape,...q6.shape,uriTemplate:P(),description:a0(P()),mimeType:a0(P()),annotations:gX.optional(),_meta:a0(h$({}))}),Ox=S6.extend({method:p("resources/list")}),Ux=k6.extend({resources:j0(KT)}),Yx=S6.extend({method:p("resources/templates/list")}),Hx=k6.extend({resourceTemplates:j0(Wx)}),f5=W1.extend({uri:P()}),Lx=f5,Fx=B$.extend({method:p("resources/read"),params:Lx}),jx=Q$.extend({contents:j0(v0([QT,IT]))}),Mx=B1.extend({method:p("notifications/resources/list_changed"),params:T1.optional()}),Rx=f5,zx=B$.extend({method:p("resources/subscribe"),params:Rx}),Tx=f5,Bx=B$.extend({method:p("resources/unsubscribe"),params:Tx}),Qx=T1.extend({uri:P()}),Ix=B1.extend({method:p("notifications/resources/updated"),params:Qx}),Kx=u({name:P(),description:a0(P()),required:a0(F$())}),Vx=u({...xX.shape,...q6.shape,description:a0(P()),arguments:a0(j0(Kx)),_meta:a0(h$({}))}),Px=S6.extend({method:p("prompts/list")}),qx=k6.extend({prompts:j0(Vx)}),Sx=W1.extend({name:P(),arguments:i0(P(),P()).optional()}),kx=B$.extend({method:p("prompts/get"),params:Sx}),x5=u({type:p("text"),text:P(),annotations:gX.optional(),_meta:i0(P(),t0()).optional()}),y5=u({type:p("image"),data:v5,mimeType:P(),annotations:gX.optional(),_meta:i0(P(),t0()).optional()}),g5=u({type:p("audio"),data:v5,mimeType:P(),annotations:gX.optional(),_meta:i0(P(),t0()).optional()}),bx=u({type:p("tool_use"),name:P(),id:P(),input:i0(P(),t0()),_meta:i0(P(),t0()).optional()}),Zx=u({type:p("resource"),resource:v0([QT,IT]),annotations:gX.optional(),_meta:i0(P(),t0()).optional()}),Cx=KT.extend({type:p("resource_link")}),u5=v0([x5,y5,g5,Cx,Zx]),_x=u({role:C6,content:u5}),vx=Q$.extend({description:P().optional(),messages:j0(_x)}),fx=B1.extend({method:p("notifications/prompts/list_changed"),params:T1.optional()}),xx=u({title:P().optional(),readOnlyHint:F$().optional(),destructiveHint:F$().optional(),idempotentHint:F$().optional(),openWorldHint:F$().optional()}),yx=u({taskSupport:a$(["required","optional","forbidden"]).optional()}),VT=u({...xX.shape,...q6.shape,description:P().optional(),inputSchema:u({type:p("object"),properties:i0(P(),T$).optional(),required:j0(P()).optional()}).catchall(t0()),outputSchema:u({type:p("object"),properties:i0(P(),T$).optional(),required:j0(P()).optional()}).catchall(t0()).optional(),annotations:xx.optional(),execution:yx.optional(),_meta:i0(P(),t0()).optional()}),h5=S6.extend({method:p("tools/list")}),gx=k6.extend({tools:j0(VT)}),Z4=Q$.extend({content:j0(u5).default([]),structuredContent:i0(P(),t0()).optional(),isError:F$().optional()}),IJ0=Z4.or(Q$.extend({toolResult:t0()})),ux=V6.extend({name:P(),arguments:i0(P(),t0()).optional()}),_6=B$.extend({method:p("tools/call"),params:ux}),hx=B1.extend({method:p("notifications/tools/list_changed"),params:T1.optional()}),KJ0=u({autoRefresh:F$().default(!0),debounceMs:q0().int().nonnegative().default(300)}),v6=a$(["debug","info","notice","warning","error","critical","alert","emergency"]),cx=W1.extend({level:v6}),c5=B$.extend({method:p("logging/setLevel"),params:cx}),nx=T1.extend({level:v6,logger:P().optional(),data:t0()}),mx=B1.extend({method:p("notifications/message"),params:nx}),rx=u({name:P().optional()}),px=u({hints:j0(rx).optional(),costPriority:q0().min(0).max(1).optional(),speedPriority:q0().min(0).max(1).optional(),intelligencePriority:q0().min(0).max(1).optional()}),ox=u({mode:a$(["auto","required","none"]).optional()}),tx=u({type:p("tool_result"),toolUseId:P().describe("The unique identifier for the corresponding tool call."),content:j0(u5).default([]),structuredContent:u({}).loose().optional(),isError:F$().optional(),_meta:i0(P(),t0()).optional()}),ix=V5("type",[x5,y5,g5]),R4=V5("type",[x5,y5,g5,bx,tx]),dx=u({role:C6,content:v0([R4,j0(R4)]),_meta:i0(P(),t0()).optional()}),lx=V6.extend({messages:j0(dx),modelPreferences:px.optional(),systemPrompt:P().optional(),includeContext:a$(["none","thisServer","allServers"]).optional(),temperature:q0().optional(),maxTokens:q0().int(),stopSequences:j0(P()).optional(),metadata:T$.optional(),tools:j0(VT).optional(),toolChoice:ox.optional()}),sx=B$.extend({method:p("sampling/createMessage"),params:lx}),f6=Q$.extend({model:P(),stopReason:a0(a$(["endTurn","stopSequence","maxTokens"]).or(P())),role:C6,content:ix}),n5=Q$.extend({model:P(),stopReason:a0(a$(["endTurn","stopSequence","maxTokens","toolUse"]).or(P())),role:C6,content:v0([R4,j0(R4)])}),ax=u({type:p("boolean"),title:P().optional(),description:P().optional(),default:F$().optional()}),ex=u({type:p("string"),title:P().optional(),description:P().optional(),minLength:q0().optional(),maxLength:q0().optional(),format:a$(["email","uri","date","date-time"]).optional(),default:P().optional()}),$y=u({type:a$(["number","integer"]),title:P().optional(),description:P().optional(),minimum:q0().optional(),maximum:q0().optional(),default:q0().optional()}),wy=u({type:p("string"),title:P().optional(),description:P().optional(),enum:j0(P()),default:P().optional()}),Ey=u({type:p("string"),title:P().optional(),description:P().optional(),oneOf:j0(u({const:P(),title:P()})),default:P().optional()}),Xy=u({type:p("string"),title:P().optional(),description:P().optional(),enum:j0(P()),enumNames:j0(P()).optional(),default:P().optional()}),Gy=v0([wy,Ey]),Jy=u({type:p("array"),title:P().optional(),description:P().optional(),minItems:q0().optional(),maxItems:q0().optional(),items:u({type:p("string"),enum:j0(P())}),default:j0(P()).optional()}),Ay=u({type:p("array"),title:P().optional(),description:P().optional(),minItems:q0().optional(),maxItems:q0().optional(),items:u({anyOf:j0(u({const:P(),title:P()}))}),default:j0(P()).optional()}),Dy=v0([Jy,Ay]),Ny=v0([Xy,Gy,Dy]),Wy=v0([Ny,ax,ex,$y]),Oy=V6.extend({mode:p("form").optional(),message:P(),requestedSchema:u({type:p("object"),properties:i0(P(),Wy),required:j0(P()).optional()})}),Uy=V6.extend({mode:p("url"),message:P(),elicitationId:P(),url:P().url()}),Yy=v0([Oy,Uy]),Hy=B$.extend({method:p("elicitation/create"),params:Yy}),Ly=T1.extend({elicitationId:P()}),Fy=B1.extend({method:p("notifications/elicitation/complete"),params:Ly}),uX=Q$.extend({action:a$(["accept","decline","cancel"]),content:P5(($)=>$===null?void 0:$,i0(P(),v0([P(),q0(),F$(),j0(P())])).optional())}),jy=u({type:p("ref/resource"),uri:P()}),My=u({type:p("ref/prompt"),name:P()}),Ry=W1.extend({ref:v0([My,jy]),argument:u({name:P(),value:P()}),context:u({arguments:i0(P(),P()).optional()}).optional()}),zy=B$.extend({method:p("completion/complete"),params:Ry}),Ty=Q$.extend({completion:h$({values:j0(P()).max(100),total:a0(q0().int()),hasMore:a0(F$())})}),By=u({uri:P().startsWith("file://"),name:P().optional(),_meta:i0(P(),t0()).optional()}),Qy=B$.extend({method:p("roots/list"),params:W1.optional()}),m5=Q$.extend({roots:j0(By)}),Iy=B1.extend({method:p("notifications/roots/list_changed"),params:T1.optional()}),VJ0=v0([I4,C5,zy,c5,kx,Px,Ox,Yx,Fx,zx,Bx,_6,h5,V4,q4,S4,b4]),PJ0=v0([Q4,K4,_5,Iy,Z6]),qJ0=v0([B4,f6,n5,uX,m5,P4,k4,yX]),SJ0=v0([I4,sx,Hy,Qy,V4,q4,S4,b4]),kJ0=v0([Q4,K4,mx,Ix,Mx,hx,fx,Z6,Fy]),bJ0=v0([B4,Xx,Ty,vx,qx,Ux,Hx,jx,Z4,gx,P4,k4,yX]);A0=class A0 extends Error{constructor($,w,E){super(`MCP error ${$}: ${w}`);this.code=$,this.data=E,this.name="McpError"}static fromError($,w,E){if($===L0.UrlElicitationRequired&&E){let X=E;if(X.elicitations)return new PT(X.elicitations,w)}return new A0($,w,E)}};PT=class PT extends A0{constructor($,w=`URL elicitation${$.length>1?"s":""} required`){super(L0.UrlElicitationRequired,w,{elicitations:$})}get elicitations(){return this.data?.elicitations??[]}}});function aw($){return $==="completed"||$==="failed"||$==="cancelled"}var Ky;var C4=R(()=>{Ky=Symbol("Let zodToJsonSchema decide on which parser to use")});var r5=R(()=>{C4()});var Q1=()=>{};var p5=R(()=>{N$()});var o5=()=>{};var _4=R(()=>{N$()});var t5=R(()=>{N$()});var i5=()=>{};var d5=R(()=>{N$()});var l5=R(()=>{N$();Q1()});var s5=R(()=>{N$()});var WA0;var v4=R(()=>{WA0=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});var f4=R(()=>{N$();v4();_4();Q1()});var a5=R(()=>{N$();f4();Q1()});var e5=R(()=>{Q1()});var x4=R(()=>{N$()});var $W=R(()=>{N$();x4()});var wW=()=>{};var EW=R(()=>{N$()});var XW=R(()=>{N$();Q1()});var GW=R(()=>{N$()});var JW=R(()=>{N$()});var AW=R(()=>{N$()});var DW=R(()=>{N$()});var NW=R(()=>{Q1()});var WW=R(()=>{Q1()});var OW=R(()=>{N$()});var UW=R(()=>{Q1();p5();o5();_4();t5();i5();d5();l5();s5();a5();e5();$W();wW();EW();XW();GW();JW();f4();AW();v4();DW();NW();x4();WW();OW()});var N$=R(()=>{C4();UW();Q1()});var qT=()=>{};var YW=R(()=>{N$();r5();Q1()});var ST=R(()=>{YW();C4();r5();N$();qT();Q1();p5();o5();_4();t5();i5();d5();l5();s5();a5();e5();$W();wW();EW();XW();GW();JW();OW();f4();AW();v4();DW();NW();x4();WW();UW();YW()});function HW($){let E=L4($)?.method;if(!E)throw Error("Schema is missing a method literal");let X=yz(E);if(typeof X!=="string")throw Error("Schema method literal must be a string");return X}function LW($,w){let E=lw($,w);if(!E.success)throw E.error;return E.data}var kT=R(()=>{F4();ST()});class FW{constructor($){if(this._options=$,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Q4,(w)=>{this._oncancel(w)}),this.setNotificationHandler(K4,(w)=>{this._onprogress(w)}),this.setRequestHandler(I4,(w)=>({})),this._taskStore=$?.taskStore,this._taskMessageQueue=$?.taskMessageQueue,this._taskStore)this.setRequestHandler(V4,async(w,E)=>{let X=await this._taskStore.getTask(w.params.taskId,E.sessionId);if(!X)throw new A0(L0.InvalidParams,"Failed to retrieve task: Task not found");return{...X}}),this.setRequestHandler(q4,async(w,E)=>{let X=async()=>{let G=w.params.taskId;if(this._taskMessageQueue){let A;while(A=await this._taskMessageQueue.dequeue(G,E.sessionId)){if(A.type==="response"||A.type==="error"){let D=A.message,N=D.id,W=this._requestResolvers.get(N);if(W)if(this._requestResolvers.delete(N),A.type==="response")W(D);else{let O=D,Y=new A0(O.error.code,O.error.message,O.error.data);W(Y)}else{let O=A.type==="response"?"Response":"Error";this._onerror(Error(`${O} handler missing for request ${N}`))}continue}await this._transport?.send(A.message,{relatedRequestId:E.requestId})}}let J=await this._taskStore.getTask(G,E.sessionId);if(!J)throw new A0(L0.InvalidParams,`Task not found: ${G}`);if(!aw(J.status))return await this._waitForTaskUpdate(G,E.signal),await X();if(aw(J.status)){let A=await this._taskStore.getTaskResult(G,E.sessionId);return this._clearTaskQueue(G),{...A,_meta:{...A._meta,[sw]:{taskId:G}}}}return await X()};return await X()}),this.setRequestHandler(S4,async(w,E)=>{try{let{tasks:X,nextCursor:G}=await this._taskStore.listTasks(w.params?.cursor,E.sessionId);return{tasks:X,nextCursor:G,_meta:{}}}catch(X){throw new A0(L0.InvalidParams,`Failed to list tasks: ${X instanceof Error?X.message:String(X)}`)}}),this.setRequestHandler(b4,async(w,E)=>{try{let X=await this._taskStore.getTask(w.params.taskId,E.sessionId);if(!X)throw new A0(L0.InvalidParams,`Task not found: ${w.params.taskId}`);if(aw(X.status))throw new A0(L0.InvalidParams,`Cannot cancel task in terminal status: ${X.status}`);await this._taskStore.updateTaskStatus(w.params.taskId,"cancelled","Client cancelled task execution.",E.sessionId),this._clearTaskQueue(w.params.taskId);let G=await this._taskStore.getTask(w.params.taskId,E.sessionId);if(!G)throw new A0(L0.InvalidParams,`Task not found after cancellation: ${w.params.taskId}`);return{_meta:{},...G}}catch(X){if(X instanceof A0)throw X;throw new A0(L0.InvalidRequest,`Failed to cancel task: ${X instanceof Error?X.message:String(X)}`)}})}async _oncancel($){if(!$.params.requestId)return;this._requestHandlerAbortControllers.get($.params.requestId)?.abort($.params.reason)}_setupTimeout($,w,E,X,G=!1){this._timeoutInfo.set($,{timeoutId:setTimeout(X,w),startTime:Date.now(),timeout:w,maxTotalTimeout:E,resetTimeoutOnProgress:G,onTimeout:X})}_resetTimeout($){let w=this._timeoutInfo.get($);if(!w)return!1;let E=Date.now()-w.startTime;if(w.maxTotalTimeout&&E>=w.maxTotalTimeout)throw this._timeoutInfo.delete($),A0.fromError(L0.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:w.maxTotalTimeout,totalElapsed:E});return clearTimeout(w.timeoutId),w.timeoutId=setTimeout(w.onTimeout,w.timeout),!0}_cleanupTimeout($){let w=this._timeoutInfo.get($);if(w)clearTimeout(w.timeoutId),this._timeoutInfo.delete($)}async connect($){if(this._transport)throw Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=$;let w=this.transport?.onclose;this._transport.onclose=()=>{w?.(),this._onclose()};let E=this.transport?.onerror;this._transport.onerror=(G)=>{E?.(G),this._onerror(G)};let X=this._transport?.onmessage;this._transport.onmessage=(G,J)=>{if(X?.(G,J),P6(G)||MT(G))this._onresponse(G);else if(k5(G))this._onrequest(G,J);else if(jT(G))this._onnotification(G);else this._onerror(Error(`Unknown message type: ${JSON.stringify(G)}`))},await this._transport.start()}_onclose(){let $=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let E of this._requestHandlerAbortControllers.values())E.abort();this._requestHandlerAbortControllers.clear();let w=A0.fromError(L0.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let E of $.values())E(w)}_onerror($){this.onerror?.($)}_onnotification($){let w=this._notificationHandlers.get($.method)??this.fallbackNotificationHandler;if(w===void 0)return;Promise.resolve().then(()=>w($)).catch((E)=>this._onerror(Error(`Uncaught error in notification handler: ${E}`)))}_onrequest($,w){let E=this._requestHandlers.get($.method)??this.fallbackRequestHandler,X=this._transport,G=$.params?._meta?.[sw]?.taskId;if(E===void 0){let W={jsonrpc:"2.0",id:$.id,error:{code:L0.MethodNotFound,message:"Method not found"}};if(G&&this._taskMessageQueue)this._enqueueTaskMessage(G,{type:"error",message:W,timestamp:Date.now()},X?.sessionId).catch((O)=>this._onerror(Error(`Failed to enqueue error response: ${O}`)));else X?.send(W).catch((O)=>this._onerror(Error(`Failed to send an error response: ${O}`)));return}let J=new AbortController;this._requestHandlerAbortControllers.set($.id,J);let A=HT($.params)?$.params.task:void 0,D=this._taskStore?this.requestTaskStore($,X?.sessionId):void 0,N={signal:J.signal,sessionId:X?.sessionId,_meta:$.params?._meta,sendNotification:async(W)=>{if(J.signal.aborted)return;let O={relatedRequestId:$.id};if(G)O.relatedTask={taskId:G};await this.notification(W,O)},sendRequest:async(W,O,Y)=>{if(J.signal.aborted)throw new A0(L0.ConnectionClosed,"Request was cancelled");let H={...Y,relatedRequestId:$.id};if(G&&!H.relatedTask)H.relatedTask={taskId:G};let L=H.relatedTask?.taskId??G;if(L&&D)await D.updateTaskStatus(L,"input_required");return await this.request(W,O,H)},authInfo:w?.authInfo,requestId:$.id,requestInfo:w?.requestInfo,taskId:G,taskStore:D,taskRequestedTtl:A?.ttl,closeSSEStream:w?.closeSSEStream,closeStandaloneSSEStream:w?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(A)this.assertTaskHandlerCapability($.method)}).then(()=>E($,N)).then(async(W)=>{if(J.signal.aborted)return;let O={result:W,jsonrpc:"2.0",id:$.id};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"response",message:O,timestamp:Date.now()},X?.sessionId);else await X?.send(O)},async(W)=>{if(J.signal.aborted)return;let O={jsonrpc:"2.0",id:$.id,error:{code:Number.isSafeInteger(W.code)?W.code:L0.InternalError,message:W.message??"Internal error",...W.data!==void 0&&{data:W.data}}};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"error",message:O,timestamp:Date.now()},X?.sessionId);else await X?.send(O)}).catch((W)=>this._onerror(Error(`Failed to send response: ${W}`))).finally(()=>{this._requestHandlerAbortControllers.delete($.id)})}_onprogress($){let{progressToken:w,...E}=$.params,X=Number(w),G=this._progressHandlers.get(X);if(!G){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify($)}`));return}let J=this._responseHandlers.get(X),A=this._timeoutInfo.get(X);if(A&&J&&A.resetTimeoutOnProgress)try{this._resetTimeout(X)}catch(D){this._responseHandlers.delete(X),this._progressHandlers.delete(X),this._cleanupTimeout(X),J(D);return}G(E)}_onresponse($){let w=Number($.id),E=this._requestResolvers.get(w);if(E){if(this._requestResolvers.delete(w),P6($))E($);else{let J=new A0($.error.code,$.error.message,$.error.data);E(J)}return}let X=this._responseHandlers.get(w);if(X===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify($)}`));return}this._responseHandlers.delete(w),this._cleanupTimeout(w);let G=!1;if(P6($)&&$.result&&typeof $.result==="object"){let J=$.result;if(J.task&&typeof J.task==="object"){let A=J.task;if(typeof A.taskId==="string")G=!0,this._taskProgressTokens.set(A.taskId,w)}}if(!G)this._progressHandlers.delete(w);if(P6($))X($);else{let J=A0.fromError($.error.code,$.error.message,$.error.data);X(J)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream($,w,E){let{task:X}=E??{};if(!X){try{yield{type:"result",result:await this.request($,w,E)}}catch(J){yield{type:"error",error:J instanceof A0?J:new A0(L0.InternalError,String(J))}}return}let G;try{let J=await this.request($,yX,E);if(J.task)G=J.task.taskId,yield{type:"taskCreated",task:J.task};else throw new A0(L0.InternalError,"Task creation did not return a task");while(!0){let A=await this.getTask({taskId:G},E);if(yield{type:"taskStatus",task:A},aw(A.status)){if(A.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:G},w,E)};else if(A.status==="failed")yield{type:"error",error:new A0(L0.InternalError,`Task ${G} failed`)};else if(A.status==="cancelled")yield{type:"error",error:new A0(L0.InternalError,`Task ${G} was cancelled`)};return}if(A.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:G},w,E)};return}let D=A.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((N)=>setTimeout(N,D)),E?.signal?.throwIfAborted()}}catch(J){yield{type:"error",error:J instanceof A0?J:new A0(L0.InternalError,String(J))}}}request($,w,E){let{relatedRequestId:X,resumptionToken:G,onresumptiontoken:J,task:A,relatedTask:D}=E??{};return new Promise((N,W)=>{let O=(z)=>{W(z)};if(!this._transport){O(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod($.method),A)this.assertTaskCapability($.method)}catch(z){O(z);return}E?.signal?.throwIfAborted();let Y=this._requestMessageId++,H={...$,jsonrpc:"2.0",id:Y};if(E?.onprogress)this._progressHandlers.set(Y,E.onprogress),H.params={...$.params,_meta:{...$.params?._meta||{},progressToken:Y}};if(A)H.params={...H.params,task:A};if(D)H.params={...H.params,_meta:{...H.params?._meta||{},[sw]:D}};let L=(z)=>{this._responseHandlers.delete(Y),this._progressHandlers.delete(Y),this._cleanupTimeout(Y),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:Y,reason:String(z)}},{relatedRequestId:X,resumptionToken:G,onresumptiontoken:J}).catch((Q)=>this._onerror(Error(`Failed to send cancellation: ${Q}`)));let B=z instanceof A0?z:new A0(L0.RequestTimeout,String(z));W(B)};this._responseHandlers.set(Y,(z)=>{if(E?.signal?.aborted)return;if(z instanceof Error)return W(z);try{let B=lw(w,z.result);if(!B.success)W(B.error);else N(B.data)}catch(B){W(B)}}),E?.signal?.addEventListener("abort",()=>{L(E?.signal?.reason)});let F=E?.timeout??by,j=()=>L(A0.fromError(L0.RequestTimeout,"Request timed out",{timeout:F}));this._setupTimeout(Y,F,E?.maxTotalTimeout,j,E?.resetTimeoutOnProgress??!1);let M=D?.taskId;if(M){let z=(B)=>{let Q=this._responseHandlers.get(Y);if(Q)Q(B);else this._onerror(Error(`Response handler missing for side-channeled request ${Y}`))};this._requestResolvers.set(Y,z),this._enqueueTaskMessage(M,{type:"request",message:H,timestamp:Date.now()}).catch((B)=>{this._cleanupTimeout(Y),W(B)})}else this._transport.send(H,{relatedRequestId:X,resumptionToken:G,onresumptiontoken:J}).catch((z)=>{this._cleanupTimeout(Y),W(z)})})}async getTask($,w){return this.request({method:"tasks/get",params:$},P4,w)}async getTaskResult($,w,E){return this.request({method:"tasks/result",params:$},w,E)}async listTasks($,w){return this.request({method:"tasks/list",params:$},k4,w)}async cancelTask($,w){return this.request({method:"tasks/cancel",params:$},TT,w)}async notification($,w){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability($.method);let E=w?.relatedTask?.taskId;if(E){let A={...$,jsonrpc:"2.0",params:{...$.params,_meta:{...$.params?._meta||{},[sw]:w.relatedTask}}};await this._enqueueTaskMessage(E,{type:"notification",message:A,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes($.method)&&!$.params&&!w?.relatedRequestId&&!w?.relatedTask){if(this._pendingDebouncedNotifications.has($.method))return;this._pendingDebouncedNotifications.add($.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete($.method),!this._transport)return;let A={...$,jsonrpc:"2.0"};if(w?.relatedTask)A={...A,params:{...A.params,_meta:{...A.params?._meta||{},[sw]:w.relatedTask}}};this._transport?.send(A,w).catch((D)=>this._onerror(D))});return}let J={...$,jsonrpc:"2.0"};if(w?.relatedTask)J={...J,params:{...J.params,_meta:{...J.params?._meta||{},[sw]:w.relatedTask}}};await this._transport.send(J,w)}setRequestHandler($,w){let E=HW($);this.assertRequestHandlerCapability(E),this._requestHandlers.set(E,(X,G)=>{let J=LW($,X);return Promise.resolve(w(J,G))})}removeRequestHandler($){this._requestHandlers.delete($)}assertCanSetRequestHandler($){if(this._requestHandlers.has($))throw Error(`A request handler for ${$} already exists, which would be overridden`)}setNotificationHandler($,w){let E=HW($);this._notificationHandlers.set(E,(X)=>{let G=LW($,X);return Promise.resolve(w(G))})}removeNotificationHandler($){this._notificationHandlers.delete($)}_cleanupTaskProgressHandler($){let w=this._taskProgressTokens.get($);if(w!==void 0)this._progressHandlers.delete(w),this._taskProgressTokens.delete($)}async _enqueueTaskMessage($,w,E){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let X=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue($,w,E,X)}async _clearTaskQueue($,w){if(this._taskMessageQueue){let E=await this._taskMessageQueue.dequeueAll($,w);for(let X of E)if(X.type==="request"&&k5(X.message)){let G=X.message.id,J=this._requestResolvers.get(G);if(J)J(new A0(L0.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(G);else this._onerror(Error(`Resolver missing for request ${G} during task ${$} cleanup`))}}}async _waitForTaskUpdate($,w){let E=this._options?.defaultTaskPollInterval??1000;try{let X=await this._taskStore?.getTask($);if(X?.pollInterval)E=X.pollInterval}catch{}return new Promise((X,G)=>{if(w.aborted){G(new A0(L0.InvalidRequest,"Request cancelled"));return}let J=setTimeout(X,E);w.addEventListener("abort",()=>{clearTimeout(J),G(new A0(L0.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore($,w){let E=this._taskStore;if(!E)throw Error("No task store configured");return{createTask:async(X)=>{if(!$)throw Error("No request provided");return await E.createTask(X,$.id,{method:$.method,params:$.params},w)},getTask:async(X)=>{let G=await E.getTask(X,w);if(!G)throw new A0(L0.InvalidParams,"Failed to retrieve task: Task not found");return G},storeTaskResult:async(X,G,J)=>{await E.storeTaskResult(X,G,J,w);let A=await E.getTask(X,w);if(A){let D=Z6.parse({method:"notifications/tasks/status",params:A});if(await this.notification(D),aw(A.status))this._cleanupTaskProgressHandler(X)}},getTaskResult:(X)=>{return E.getTaskResult(X,w)},updateTaskStatus:async(X,G,J)=>{let A=await E.getTask(X,w);if(!A)throw new A0(L0.InvalidParams,`Task "${X}" not found - it may have been cleaned up`);if(aw(A.status))throw new A0(L0.InvalidParams,`Cannot update task "${X}" from terminal status "${A.status}" to "${G}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await E.updateTaskStatus(X,G,J,w);let D=await E.getTask(X,w);if(D){let N=Z6.parse({method:"notifications/tasks/status",params:D});if(await this.notification(N),aw(D.status))this._cleanupTaskProgressHandler(X)}},listTasks:(X)=>{return E.listTasks(X,w)}}}}function bT($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function ZT($,w){let E={...$};for(let X in w){let G=X,J=w[G];if(J===void 0)continue;let A=E[G];if(bT(A)&&bT(J))E[G]={...A,...J};else E[G]=J}return E}var by=60000;var CT=R(()=>{F4();hX();kT()});var g6=Z((fT)=>{Object.defineProperty(fT,"__esModule",{value:!0});fT.regexpCode=fT.getEsmExportName=fT.getProperty=fT.safeStringify=fT.stringify=fT.strConcat=fT.addCodeArg=fT.str=fT._=fT.nil=fT._Code=fT.Name=fT.IDENTIFIER=fT._CodeOrName=void 0;class y4{}fT._CodeOrName=y4;fT.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class cX extends y4{constructor($){super();if(!fT.IDENTIFIER.test($))throw Error("CodeGen: name must be a valid identifier");this.str=$}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}fT.Name=cX;class h1 extends y4{constructor($){super();this._items=typeof $==="string"?[$]:$}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let $=this._items[0];return $===""||$==='""'}get str(){var $;return($=this._str)!==null&&$!==void 0?$:this._str=this._items.reduce((w,E)=>`${w}${E}`,"")}get names(){var $;return($=this._names)!==null&&$!==void 0?$:this._names=this._items.reduce((w,E)=>{if(E instanceof cX)w[E.str]=(w[E.str]||0)+1;return w},{})}}fT._Code=h1;fT.nil=new h1("");function _T($,...w){let E=[$[0]],X=0;while(X<w.length)MW(E,w[X]),E.push($[++X]);return new h1(E)}fT._=_T;var jW=new h1("+");function vT($,...w){let E=[y6($[0])],X=0;while(X<w.length)E.push(jW),MW(E,w[X]),E.push(jW,y6($[++X]));return Zy(E),new h1(E)}fT.str=vT;function MW($,w){if(w instanceof h1)$.push(...w._items);else if(w instanceof cX)$.push(w);else $.push(vy(w))}fT.addCodeArg=MW;function Zy($){let w=1;while(w<$.length-1){if($[w]===jW){let E=Cy($[w-1],$[w+1]);if(E!==void 0){$.splice(w-1,3,E);continue}$[w++]="+"}w++}}function Cy($,w){if(w==='""')return $;if($==='""')return w;if(typeof $=="string"){if(w instanceof cX||$[$.length-1]!=='"')return;if(typeof w!="string")return`${$.slice(0,-1)}${w}"`;if(w[0]==='"')return $.slice(0,-1)+w.slice(1);return}if(typeof w=="string"&&w[0]==='"'&&!($ instanceof cX))return`"${$}${w.slice(1)}`;return}function _y($,w){return w.emptyStr()?$:$.emptyStr()?w:vT`${$}${w}`}fT.strConcat=_y;function vy($){return typeof $=="number"||typeof $=="boolean"||$===null?$:y6(Array.isArray($)?$.join(","):$)}function fy($){return new h1(y6($))}fT.stringify=fy;function y6($){return JSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}fT.safeStringify=y6;function xy($){return typeof $=="string"&&fT.IDENTIFIER.test($)?new h1(`.${$}`):_T`[${$}]`}fT.getProperty=xy;function yy($){if(typeof $=="string"&&fT.IDENTIFIER.test($))return new h1(`${$}`);throw Error(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}fT.getEsmExportName=yy;function gy($){return new h1($.toString())}fT.regexpCode=gy});var BW=Z((uT)=>{Object.defineProperty(uT,"__esModule",{value:!0});uT.ValueScope=uT.ValueScopeName=uT.Scope=uT.varKinds=uT.UsedValueState=void 0;var e$=g6();class yT extends Error{constructor($){super(`CodeGen: "code" for ${$} not defined`);this.value=$.value}}var u4;(function($){$[$.Started=0]="Started",$[$.Completed=1]="Completed"})(u4||(uT.UsedValueState=u4={}));uT.varKinds={const:new e$.Name("const"),let:new e$.Name("let"),var:new e$.Name("var")};class zW{constructor({prefixes:$,parent:w}={}){this._names={},this._prefixes=$,this._parent=w}toName($){return $ instanceof e$.Name?$:this.name($)}name($){return new e$.Name(this._newName($))}_newName($){let w=this._names[$]||this._nameGroup($);return`${$}${w.index++}`}_nameGroup($){var w,E;if(((E=(w=this._parent)===null||w===void 0?void 0:w._prefixes)===null||E===void 0?void 0:E.has($))||this._prefixes&&!this._prefixes.has($))throw Error(`CodeGen: prefix "${$}" is not allowed in this scope`);return this._names[$]={prefix:$,index:0}}}uT.Scope=zW;class TW extends e$.Name{constructor($,w){super(w);this.prefix=$}setValue($,{property:w,itemIndex:E}){this.value=$,this.scopePath=e$._`.${new e$.Name(w)}[${E}]`}}uT.ValueScopeName=TW;var sy=e$._`\n`;class gT extends zW{constructor($){super($);this._values={},this._scope=$.scope,this.opts={...$,_n:$.lines?sy:e$.nil}}get(){return this._scope}name($){return new TW($,this._newName($))}value($,w){var E;if(w.ref===void 0)throw Error("CodeGen: ref must be passed in value");let X=this.toName($),{prefix:G}=X,J=(E=w.key)!==null&&E!==void 0?E:w.ref,A=this._values[G];if(A){let W=A.get(J);if(W)return W}else A=this._values[G]=new Map;A.set(J,X);let D=this._scope[G]||(this._scope[G]=[]),N=D.length;return D[N]=w.ref,X.setValue(w,{property:G,itemIndex:N}),X}getValue($,w){let E=this._values[$];if(!E)return;return E.get(w)}scopeRefs($,w=this._values){return this._reduceValues(w,(E)=>{if(E.scopePath===void 0)throw Error(`CodeGen: name "${E}" has no value`);return e$._`${$}${E.scopePath}`})}scopeCode($=this._values,w,E){return this._reduceValues($,(X)=>{if(X.value===void 0)throw Error(`CodeGen: name "${X}" has no value`);return X.value.code},w,E)}_reduceValues($,w,E={},X){let G=e$.nil;for(let J in $){let A=$[J];if(!A)continue;let D=E[J]=E[J]||new Map;A.forEach((N)=>{if(D.has(N))return;D.set(N,u4.Started);let W=w(N);if(W){let O=this.opts.es5?uT.varKinds.var:uT.varKinds.const;G=e$._`${G}${O} ${N} = ${W};${this.opts._n}`}else if(W=X===null||X===void 0?void 0:X(N))G=e$._`${G}${W}${this.opts._n}`;else throw new yT(N);D.set(N,u4.Completed)})}return G}}uT.ValueScope=gT});var W0=Z(($1)=>{Object.defineProperty($1,"__esModule",{value:!0});$1.or=$1.and=$1.not=$1.CodeGen=$1.operators=$1.varKinds=$1.ValueScopeName=$1.ValueScope=$1.Scope=$1.Name=$1.regexpCode=$1.stringify=$1.getProperty=$1.nil=$1.strConcat=$1.str=$1._=void 0;var M0=g6(),c1=BW(),ew=g6();Object.defineProperty($1,"_",{enumerable:!0,get:function(){return ew._}});Object.defineProperty($1,"str",{enumerable:!0,get:function(){return ew.str}});Object.defineProperty($1,"strConcat",{enumerable:!0,get:function(){return ew.strConcat}});Object.defineProperty($1,"nil",{enumerable:!0,get:function(){return ew.nil}});Object.defineProperty($1,"getProperty",{enumerable:!0,get:function(){return ew.getProperty}});Object.defineProperty($1,"stringify",{enumerable:!0,get:function(){return ew.stringify}});Object.defineProperty($1,"regexpCode",{enumerable:!0,get:function(){return ew.regexpCode}});Object.defineProperty($1,"Name",{enumerable:!0,get:function(){return ew.Name}});var p4=BW();Object.defineProperty($1,"Scope",{enumerable:!0,get:function(){return p4.Scope}});Object.defineProperty($1,"ValueScope",{enumerable:!0,get:function(){return p4.ValueScope}});Object.defineProperty($1,"ValueScopeName",{enumerable:!0,get:function(){return p4.ValueScopeName}});Object.defineProperty($1,"varKinds",{enumerable:!0,get:function(){return p4.varKinds}});$1.operators={GT:new M0._Code(">"),GTE:new M0._Code(">="),LT:new M0._Code("<"),LTE:new M0._Code("<="),EQ:new M0._Code("==="),NEQ:new M0._Code("!=="),NOT:new M0._Code("!"),OR:new M0._Code("||"),AND:new M0._Code("&&"),ADD:new M0._Code("+")};class $E{optimizeNodes(){return this}optimizeNames($,w){return this}}class cT extends $E{constructor($,w,E){super();this.varKind=$,this.name=w,this.rhs=E}render({es5:$,_n:w}){let E=$?c1.varKinds.var:this.varKind,X=this.rhs===void 0?"":` = ${this.rhs}`;return`${E} ${this.name}${X};`+w}optimizeNames($,w){if(!$[this.name.str])return;if(this.rhs)this.rhs=mX(this.rhs,$,w);return this}get names(){return this.rhs instanceof M0._CodeOrName?this.rhs.names:{}}}class KW extends $E{constructor($,w,E){super();this.lhs=$,this.rhs=w,this.sideEffects=E}render({_n:$}){return`${this.lhs} = ${this.rhs};`+$}optimizeNames($,w){if(this.lhs instanceof M0.Name&&!$[this.lhs.str]&&!this.sideEffects)return;return this.rhs=mX(this.rhs,$,w),this}get names(){let $=this.lhs instanceof M0.Name?{}:{...this.lhs.names};return r4($,this.rhs)}}class nT extends KW{constructor($,w,E,X){super($,E,X);this.op=w}render({_n:$}){return`${this.lhs} ${this.op}= ${this.rhs};`+$}}class mT extends $E{constructor($){super();this.label=$,this.names={}}render({_n:$}){return`${this.label}:`+$}}class rT extends $E{constructor($){super();this.label=$,this.names={}}render({_n:$}){return`break${this.label?` ${this.label}`:""};`+$}}class pT extends $E{constructor($){super();this.error=$}render({_n:$}){return`throw ${this.error};`+$}get names(){return this.error.names}}class oT extends $E{constructor($){super();this.code=$}render({_n:$}){return`${this.code};`+$}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames($,w){return this.code=mX(this.code,$,w),this}get names(){return this.code instanceof M0._CodeOrName?this.code.names:{}}}class o4 extends $E{constructor($=[]){super();this.nodes=$}render($){return this.nodes.reduce((w,E)=>w+E.render($),"")}optimizeNodes(){let{nodes:$}=this,w=$.length;while(w--){let E=$[w].optimizeNodes();if(Array.isArray(E))$.splice(w,1,...E);else if(E)$[w]=E;else $.splice(w,1)}return $.length>0?this:void 0}optimizeNames($,w){let{nodes:E}=this,X=E.length;while(X--){let G=E[X];if(G.optimizeNames($,w))continue;wg($,G.names),E.splice(X,1)}return E.length>0?this:void 0}get names(){return this.nodes.reduce(($,w)=>kE($,w.names),{})}}class wE extends o4{render($){return"{"+$._n+super.render($)+"}"+$._n}}class tT extends o4{}class u6 extends wE{}u6.kind="else";class Pw extends wE{constructor($,w){super(w);this.condition=$}render($){let w=`if(${this.condition})`+super.render($);if(this.else)w+="else "+this.else.render($);return w}optimizeNodes(){super.optimizeNodes();let $=this.condition;if($===!0)return this.nodes;let w=this.else;if(w){let E=w.optimizeNodes();w=this.else=Array.isArray(E)?new u6(E):E}if(w){if($===!1)return w instanceof Pw?w:w.nodes;if(this.nodes.length)return this;return new Pw(aT($),w instanceof Pw?[w]:w.nodes)}if($===!1||!this.nodes.length)return;return this}optimizeNames($,w){var E;if(this.else=(E=this.else)===null||E===void 0?void 0:E.optimizeNames($,w),!(super.optimizeNames($,w)||this.else))return;return this.condition=mX(this.condition,$,w),this}get names(){let $=super.names;if(r4($,this.condition),this.else)kE($,this.else.names);return $}}Pw.kind="if";class nX extends wE{}nX.kind="for";class iT extends nX{constructor($){super();this.iteration=$}render($){return`for(${this.iteration})`+super.render($)}optimizeNames($,w){if(!super.optimizeNames($,w))return;return this.iteration=mX(this.iteration,$,w),this}get names(){return kE(super.names,this.iteration.names)}}class dT extends nX{constructor($,w,E,X){super();this.varKind=$,this.name=w,this.from=E,this.to=X}render($){let w=$.es5?c1.varKinds.var:this.varKind,{name:E,from:X,to:G}=this;return`for(${w} ${E}=${X}; ${E}<${G}; ${E}++)`+super.render($)}get names(){let $=r4(super.names,this.from);return r4($,this.to)}}class QW extends nX{constructor($,w,E,X){super();this.loop=$,this.varKind=w,this.name=E,this.iterable=X}render($){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render($)}optimizeNames($,w){if(!super.optimizeNames($,w))return;return this.iterable=mX(this.iterable,$,w),this}get names(){return kE(super.names,this.iterable.names)}}class h4 extends wE{constructor($,w,E){super();this.name=$,this.args=w,this.async=E}render($){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render($)}}h4.kind="func";class c4 extends o4{render($){return"return "+super.render($)}}c4.kind="return";class lT extends wE{render($){let w="try"+super.render($);if(this.catch)w+=this.catch.render($);if(this.finally)w+=this.finally.render($);return w}optimizeNodes(){var $,w;return super.optimizeNodes(),($=this.catch)===null||$===void 0||$.optimizeNodes(),(w=this.finally)===null||w===void 0||w.optimizeNodes(),this}optimizeNames($,w){var E,X;return super.optimizeNames($,w),(E=this.catch)===null||E===void 0||E.optimizeNames($,w),(X=this.finally)===null||X===void 0||X.optimizeNames($,w),this}get names(){let $=super.names;if(this.catch)kE($,this.catch.names);if(this.finally)kE($,this.finally.names);return $}}class n4 extends wE{constructor($){super();this.error=$}render($){return`catch(${this.error})`+super.render($)}}n4.kind="catch";class m4 extends wE{render($){return"finally"+super.render($)}}m4.kind="finally";class sT{constructor($,w={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...w,_n:w.lines?`
|
|
571
|
-
`:""},this._extScope=$,this._scope=new c1.Scope({parent:$}),this._nodes=[new tT]}toString(){return this._root.render(this.opts)}name($){return this._scope.name($)}scopeName($){return this._extScope.name($)}scopeValue($,w){let E=this._extScope.value($,w);return(this._values[E.prefix]||(this._values[E.prefix]=new Set)).add(E),E}getScopeValue($,w){return this._extScope.getValue($,w)}scopeRefs($){return this._extScope.scopeRefs($,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def($,w,E,X){let G=this._scope.toName(w);if(E!==void 0&&X)this._constants[G.str]=E;return this._leafNode(new cT($,G,E)),G}const($,w,E){return this._def(c1.varKinds.const,$,w,E)}let($,w,E){return this._def(c1.varKinds.let,$,w,E)}var($,w,E){return this._def(c1.varKinds.var,$,w,E)}assign($,w,E){return this._leafNode(new KW($,w,E))}add($,w){return this._leafNode(new nT($,$1.operators.ADD,w))}code($){if(typeof $=="function")$();else if($!==M0.nil)this._leafNode(new oT($));return this}object(...$){let w=["{"];for(let[E,X]of $){if(w.length>1)w.push(",");if(w.push(E),E!==X||this.opts.es5)w.push(":"),(0,M0.addCodeArg)(w,X)}return w.push("}"),new M0._Code(w)}if($,w,E){if(this._blockNode(new Pw($)),w&&E)this.code(w).else().code(E).endIf();else if(w)this.code(w).endIf();else if(E)throw Error('CodeGen: "else" body without "then" body');return this}elseIf($){return this._elseNode(new Pw($))}else(){return this._elseNode(new u6)}endIf(){return this._endBlockNode(Pw,u6)}_for($,w){if(this._blockNode($),w)this.code(w).endFor();return this}for($,w){return this._for(new iT($),w)}forRange($,w,E,X,G=this.opts.es5?c1.varKinds.var:c1.varKinds.let){let J=this._scope.toName($);return this._for(new dT(G,J,w,E),()=>X(J))}forOf($,w,E,X=c1.varKinds.const){let G=this._scope.toName($);if(this.opts.es5){let J=w instanceof M0.Name?w:this.var("_arr",w);return this.forRange("_i",0,M0._`${J}.length`,(A)=>{this.var(G,M0._`${J}[${A}]`),E(G)})}return this._for(new QW("of",X,G,w),()=>E(G))}forIn($,w,E,X=this.opts.es5?c1.varKinds.var:c1.varKinds.const){if(this.opts.ownProperties)return this.forOf($,M0._`Object.keys(${w})`,E);let G=this._scope.toName($);return this._for(new QW("in",X,G,w),()=>E(G))}endFor(){return this._endBlockNode(nX)}label($){return this._leafNode(new mT($))}break($){return this._leafNode(new rT($))}return($){let w=new c4;if(this._blockNode(w),this.code($),w.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(c4)}try($,w,E){if(!w&&!E)throw Error('CodeGen: "try" without "catch" and "finally"');let X=new lT;if(this._blockNode(X),this.code($),w){let G=this.name("e");this._currNode=X.catch=new n4(G),w(G)}if(E)this._currNode=X.finally=new m4,this.code(E);return this._endBlockNode(n4,m4)}throw($){return this._leafNode(new pT($))}block($,w){if(this._blockStarts.push(this._nodes.length),$)this.code($).endBlock(w);return this}endBlock($){let w=this._blockStarts.pop();if(w===void 0)throw Error("CodeGen: not in self-balancing block");let E=this._nodes.length-w;if(E<0||$!==void 0&&E!==$)throw Error(`CodeGen: wrong number of nodes: ${E} vs ${$} expected`);return this._nodes.length=w,this}func($,w=M0.nil,E,X){if(this._blockNode(new h4($,w,E)),X)this.code(X).endFunc();return this}endFunc(){return this._endBlockNode(h4)}optimize($=1){while($-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode($){return this._currNode.nodes.push($),this}_blockNode($){this._currNode.nodes.push($),this._nodes.push($)}_endBlockNode($,w){let E=this._currNode;if(E instanceof $||w&&E instanceof w)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${w?`${$.kind}/${w.kind}`:$.kind}"`)}_elseNode($){let w=this._currNode;if(!(w instanceof Pw))throw Error('CodeGen: "else" without "if"');return this._currNode=w.else=$,this}get _root(){return this._nodes[0]}get _currNode(){let $=this._nodes;return $[$.length-1]}set _currNode($){let w=this._nodes;w[w.length-1]=$}}$1.CodeGen=sT;function kE($,w){for(let E in w)$[E]=($[E]||0)+(w[E]||0);return $}function r4($,w){return w instanceof M0._CodeOrName?kE($,w.names):$}function mX($,w,E){if($ instanceof M0.Name)return X($);if(!G($))return $;return new M0._Code($._items.reduce((J,A)=>{if(A instanceof M0.Name)A=X(A);if(A instanceof M0._Code)J.push(...A._items);else J.push(A);return J},[]));function X(J){let A=E[J.str];if(A===void 0||w[J.str]!==1)return J;return delete w[J.str],A}function G(J){return J instanceof M0._Code&&J._items.some((A)=>A instanceof M0.Name&&w[A.str]===1&&E[A.str]!==void 0)}}function wg($,w){for(let E in w)$[E]=($[E]||0)-(w[E]||0)}function aT($){return typeof $=="boolean"||typeof $=="number"||$===null?!$:M0._`!${IW($)}`}$1.not=aT;var Eg=eT($1.operators.AND);function Xg(...$){return $.reduce(Eg)}$1.and=Xg;var Gg=eT($1.operators.OR);function Jg(...$){return $.reduce(Gg)}$1.or=Jg;function eT($){return(w,E)=>w===M0.nil?E:E===M0.nil?w:M0._`${IW(w)} ${$} ${IW(E)}`}function IW($){return $ instanceof M0.Name?$:M0._`(${$})`}});var R0=Z((NB)=>{Object.defineProperty(NB,"__esModule",{value:!0});NB.checkStrictMode=NB.getErrorPath=NB.Type=NB.useFunc=NB.setEvaluated=NB.evaluatedPropsToName=NB.mergeEvaluated=NB.eachItem=NB.unescapeJsonPointer=NB.escapeJsonPointer=NB.escapeFragment=NB.unescapeFragment=NB.schemaRefOrVal=NB.schemaHasRulesButRef=NB.schemaHasRules=NB.checkUnknownRules=NB.alwaysValidSchema=NB.toHash=void 0;var b0=W0(),Wg=g6();function Og($){let w={};for(let E of $)w[E]=!0;return w}NB.toHash=Og;function Ug($,w){if(typeof w=="boolean")return w;if(Object.keys(w).length===0)return!0;return XB($,w),!GB(w,$.self.RULES.all)}NB.alwaysValidSchema=Ug;function XB($,w=$.schema){let{opts:E,self:X}=$;if(!E.strictSchema)return;if(typeof w==="boolean")return;let G=X.RULES.keywords;for(let J in w)if(!G[J])DB($,`unknown keyword: "${J}"`)}NB.checkUnknownRules=XB;function GB($,w){if(typeof $=="boolean")return!$;for(let E in $)if(w[E])return!0;return!1}NB.schemaHasRules=GB;function Yg($,w){if(typeof $=="boolean")return!$;for(let E in $)if(E!=="$ref"&&w.all[E])return!0;return!1}NB.schemaHasRulesButRef=Yg;function Hg({topSchemaRef:$,schemaPath:w},E,X,G){if(!G){if(typeof E=="number"||typeof E=="boolean")return E;if(typeof E=="string")return b0._`${E}`}return b0._`${$}${w}${(0,b0.getProperty)(X)}`}NB.schemaRefOrVal=Hg;function Lg($){return JB(decodeURIComponent($))}NB.unescapeFragment=Lg;function Fg($){return encodeURIComponent(PW($))}NB.escapeFragment=Fg;function PW($){if(typeof $=="number")return`${$}`;return $.replace(/~/g,"~0").replace(/\//g,"~1")}NB.escapeJsonPointer=PW;function JB($){return $.replace(/~1/g,"/").replace(/~0/g,"~")}NB.unescapeJsonPointer=JB;function jg($,w){if(Array.isArray($))for(let E of $)w(E);else w($)}NB.eachItem=jg;function wB({mergeNames:$,mergeToName:w,mergeValues:E,resultToName:X}){return(G,J,A,D)=>{let N=A===void 0?J:A instanceof b0.Name?(J instanceof b0.Name?$(G,J,A):w(G,J,A),A):J instanceof b0.Name?(w(G,A,J),J):E(J,A);return D===b0.Name&&!(N instanceof b0.Name)?X(G,N):N}}NB.mergeEvaluated={props:wB({mergeNames:($,w,E)=>$.if(b0._`${E} !== true && ${w} !== undefined`,()=>{$.if(b0._`${w} === true`,()=>$.assign(E,!0),()=>$.assign(E,b0._`${E} || {}`).code(b0._`Object.assign(${E}, ${w})`))}),mergeToName:($,w,E)=>$.if(b0._`${E} !== true`,()=>{if(w===!0)$.assign(E,!0);else $.assign(E,b0._`${E} || {}`),qW($,E,w)}),mergeValues:($,w)=>$===!0?!0:{...$,...w},resultToName:AB}),items:wB({mergeNames:($,w,E)=>$.if(b0._`${E} !== true && ${w} !== undefined`,()=>$.assign(E,b0._`${w} === true ? true : ${E} > ${w} ? ${E} : ${w}`)),mergeToName:($,w,E)=>$.if(b0._`${E} !== true`,()=>$.assign(E,w===!0?!0:b0._`${E} > ${w} ? ${E} : ${w}`)),mergeValues:($,w)=>$===!0?!0:Math.max($,w),resultToName:($,w)=>$.var("items",w)})};function AB($,w){if(w===!0)return $.var("props",!0);let E=$.var("props",b0._`{}`);if(w!==void 0)qW($,E,w);return E}NB.evaluatedPropsToName=AB;function qW($,w,E){Object.keys(E).forEach((X)=>$.assign(b0._`${w}${(0,b0.getProperty)(X)}`,!0))}NB.setEvaluated=qW;var EB={};function Mg($,w){return $.scopeValue("func",{ref:w,code:EB[w.code]||(EB[w.code]=new Wg._Code(w.code))})}NB.useFunc=Mg;var VW;(function($){$[$.Num=0]="Num",$[$.Str=1]="Str"})(VW||(NB.Type=VW={}));function Rg($,w,E){if($ instanceof b0.Name){let X=w===VW.Num;return E?X?b0._`"[" + ${$} + "]"`:b0._`"['" + ${$} + "']"`:X?b0._`"/" + ${$}`:b0._`"/" + ${$}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return E?(0,b0.getProperty)($).toString():"/"+PW($)}NB.getErrorPath=Rg;function DB($,w,E=$.opts.strictSchema){if(!E)return;if(w=`strict mode: ${w}`,E===!0)throw Error(w);$.self.logger.warn(w)}NB.checkStrictMode=DB});var qw=Z((OB)=>{Object.defineProperty(OB,"__esModule",{value:!0});var Z$=W0(),xg={data:new Z$.Name("data"),valCxt:new Z$.Name("valCxt"),instancePath:new Z$.Name("instancePath"),parentData:new Z$.Name("parentData"),parentDataProperty:new Z$.Name("parentDataProperty"),rootData:new Z$.Name("rootData"),dynamicAnchors:new Z$.Name("dynamicAnchors"),vErrors:new Z$.Name("vErrors"),errors:new Z$.Name("errors"),this:new Z$.Name("this"),self:new Z$.Name("self"),scope:new Z$.Name("scope"),json:new Z$.Name("json"),jsonPos:new Z$.Name("jsonPos"),jsonLen:new Z$.Name("jsonLen"),jsonPart:new Z$.Name("jsonPart")};OB.default=xg});var h6=Z((LB)=>{Object.defineProperty(LB,"__esModule",{value:!0});LB.extendErrors=LB.resetErrorsCount=LB.reportExtraError=LB.reportError=LB.keyword$DataError=LB.keywordError=void 0;var z0=W0(),i4=R0(),c$=qw();LB.keywordError={message:({keyword:$})=>z0.str`must pass "${$}" keyword validation`};LB.keyword$DataError={message:({keyword:$,schemaType:w})=>w?z0.str`"${$}" keyword must be ${w} ($data)`:z0.str`"${$}" keyword is invalid ($data)`};function gg($,w=LB.keywordError,E,X){let{it:G}=$,{gen:J,compositeRule:A,allErrors:D}=G,N=HB($,w,E);if(X!==null&&X!==void 0?X:A||D)UB(J,N);else YB(G,z0._`[${N}]`)}LB.reportError=gg;function ug($,w=LB.keywordError,E){let{it:X}=$,{gen:G,compositeRule:J,allErrors:A}=X,D=HB($,w,E);if(UB(G,D),!(J||A))YB(X,c$.default.vErrors)}LB.reportExtraError=ug;function hg($,w){$.assign(c$.default.errors,w),$.if(z0._`${c$.default.vErrors} !== null`,()=>$.if(w,()=>$.assign(z0._`${c$.default.vErrors}.length`,w),()=>$.assign(c$.default.vErrors,null)))}LB.resetErrorsCount=hg;function cg({gen:$,keyword:w,schemaValue:E,data:X,errsCount:G,it:J}){if(G===void 0)throw Error("ajv implementation error");let A=$.name("err");$.forRange("i",G,c$.default.errors,(D)=>{if($.const(A,z0._`${c$.default.vErrors}[${D}]`),$.if(z0._`${A}.instancePath === undefined`,()=>$.assign(z0._`${A}.instancePath`,(0,z0.strConcat)(c$.default.instancePath,J.errorPath))),$.assign(z0._`${A}.schemaPath`,z0.str`${J.errSchemaPath}/${w}`),J.opts.verbose)$.assign(z0._`${A}.schema`,E),$.assign(z0._`${A}.data`,X)})}LB.extendErrors=cg;function UB($,w){let E=$.const("err",w);$.if(z0._`${c$.default.vErrors} === null`,()=>$.assign(c$.default.vErrors,z0._`[${E}]`),z0._`${c$.default.vErrors}.push(${E})`),$.code(z0._`${c$.default.errors}++`)}function YB($,w){let{gen:E,validateName:X,schemaEnv:G}=$;if(G.$async)E.throw(z0._`new ${$.ValidationError}(${w})`);else E.assign(z0._`${X}.errors`,w),E.return(!1)}var bE={keyword:new z0.Name("keyword"),schemaPath:new z0.Name("schemaPath"),params:new z0.Name("params"),propertyName:new z0.Name("propertyName"),message:new z0.Name("message"),schema:new z0.Name("schema"),parentSchema:new z0.Name("parentSchema")};function HB($,w,E){let{createErrors:X}=$.it;if(X===!1)return z0._`{}`;return ng($,w,E)}function ng($,w,E={}){let{gen:X,it:G}=$,J=[mg(G,E),rg($,E)];return pg($,w,J),X.object(...J)}function mg({errorPath:$},{instancePath:w}){let E=w?z0.str`${$}${(0,i4.getErrorPath)(w,i4.Type.Str)}`:$;return[c$.default.instancePath,(0,z0.strConcat)(c$.default.instancePath,E)]}function rg({keyword:$,it:{errSchemaPath:w}},{schemaPath:E,parentSchema:X}){let G=X?w:z0.str`${w}/${$}`;if(E)G=z0.str`${G}${(0,i4.getErrorPath)(E,i4.Type.Str)}`;return[bE.schemaPath,G]}function pg($,{params:w,message:E},X){let{keyword:G,data:J,schemaValue:A,it:D}=$,{opts:N,propertyName:W,topSchemaRef:O,schemaPath:Y}=D;if(X.push([bE.keyword,G],[bE.params,typeof w=="function"?w($):w||z0._`{}`]),N.messages)X.push([bE.message,typeof E=="function"?E($):E]);if(N.verbose)X.push([bE.schema,A],[bE.parentSchema,z0._`${O}${Y}`],[c$.default.data,J]);if(W)X.push([bE.propertyName,W])}});var zB=Z((MB)=>{Object.defineProperty(MB,"__esModule",{value:!0});MB.boolOrEmptySchema=MB.topBoolOrEmptySchema=void 0;var lg=h6(),sg=W0(),ag=qw(),eg={message:"boolean schema is false"};function $u($){let{gen:w,schema:E,validateName:X}=$;if(E===!1)jB($,!1);else if(typeof E=="object"&&E.$async===!0)w.return(ag.default.data);else w.assign(sg._`${X}.errors`,null),w.return(!0)}MB.topBoolOrEmptySchema=$u;function wu($,w){let{gen:E,schema:X}=$;if(X===!1)E.var(w,!1),jB($);else E.var(w,!0)}MB.boolOrEmptySchema=wu;function jB($,w){let{gen:E,data:X}=$,G={gen:E,keyword:"false schema",data:X,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:$};(0,lg.reportError)(G,eg,void 0,w)}});var kW=Z((TB)=>{Object.defineProperty(TB,"__esModule",{value:!0});TB.getRules=TB.isJSONType=void 0;var Xu=["string","number","integer","boolean","null","object","array"],Gu=new Set(Xu);function Ju($){return typeof $=="string"&&Gu.has($)}TB.isJSONType=Ju;function Au(){let $={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...$,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},$.number,$.string,$.array,$.object],post:{rules:[]},all:{},keywords:{}}}TB.getRules=Au});var bW=Z((KB)=>{Object.defineProperty(KB,"__esModule",{value:!0});KB.shouldUseRule=KB.shouldUseGroup=KB.schemaHasRulesForType=void 0;function Nu({schema:$,self:w},E){let X=w.RULES.types[E];return X&&X!==!0&&QB($,X)}KB.schemaHasRulesForType=Nu;function QB($,w){return w.rules.some((E)=>IB($,E))}KB.shouldUseGroup=QB;function IB($,w){var E;return $[w.keyword]!==void 0||((E=w.definition.implements)===null||E===void 0?void 0:E.some((X)=>$[X]!==void 0))}KB.shouldUseRule=IB});var c6=Z((kB)=>{Object.defineProperty(kB,"__esModule",{value:!0});kB.reportTypeError=kB.checkDataTypes=kB.checkDataType=kB.coerceAndCheckDataType=kB.getJSONTypes=kB.getSchemaTypes=kB.DataType=void 0;var Uu=kW(),Yu=bW(),Hu=h6(),D0=W0(),PB=R0(),rX;(function($){$[$.Correct=0]="Correct",$[$.Wrong=1]="Wrong"})(rX||(kB.DataType=rX={}));function Lu($){let w=qB($.type);if(w.includes("null")){if($.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!w.length&&$.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if($.nullable===!0)w.push("null")}return w}kB.getSchemaTypes=Lu;function qB($){let w=Array.isArray($)?$:$?[$]:[];if(w.every(Uu.isJSONType))return w;throw Error("type must be JSONType or JSONType[]: "+w.join(","))}kB.getJSONTypes=qB;function Fu($,w){let{gen:E,data:X,opts:G}=$,J=ju(w,G.coerceTypes),A=w.length>0&&!(J.length===0&&w.length===1&&(0,Yu.schemaHasRulesForType)($,w[0]));if(A){let D=CW(w,X,G.strictNumbers,rX.Wrong);E.if(D,()=>{if(J.length)Mu($,w,J);else _W($)})}return A}kB.coerceAndCheckDataType=Fu;var SB=new Set(["string","number","integer","boolean","null"]);function ju($,w){return w?$.filter((E)=>SB.has(E)||w==="array"&&E==="array"):[]}function Mu($,w,E){let{gen:X,data:G,opts:J}=$,A=X.let("dataType",D0._`typeof ${G}`),D=X.let("coerced",D0._`undefined`);if(J.coerceTypes==="array")X.if(D0._`${A} == 'object' && Array.isArray(${G}) && ${G}.length == 1`,()=>X.assign(G,D0._`${G}[0]`).assign(A,D0._`typeof ${G}`).if(CW(w,G,J.strictNumbers),()=>X.assign(D,G)));X.if(D0._`${D} !== undefined`);for(let W of E)if(SB.has(W)||W==="array"&&J.coerceTypes==="array")N(W);X.else(),_W($),X.endIf(),X.if(D0._`${D} !== undefined`,()=>{X.assign(G,D),Ru($,D)});function N(W){switch(W){case"string":X.elseIf(D0._`${A} == "number" || ${A} == "boolean"`).assign(D,D0._`"" + ${G}`).elseIf(D0._`${G} === null`).assign(D,D0._`""`);return;case"number":X.elseIf(D0._`${A} == "boolean" || ${G} === null
|
|
570
|
+
})));`),H.write(`newResult[${PE(B)}] = ${Q}.value`)}H.write("payload.value = newResult;"),H.write("return payload;");let z=H.compile();return(B,Q)=>z(Y,B,Q)},G,J=CX,A=!$4.jitless,N=A&&y9.value,W=w.catchall,O;$._zod.parse=(Y,H)=>{O??(O=E.value);let L=Y.value;if(!J(L))return Y.issues.push({expected:"object",code:"invalid_type",input:L,inst:$}),Y;let F=[];if(A&&N&&H?.async===!1&&H.jitless!==!0){if(!G)G=X(w.shape);Y=G(Y,H)}else{Y.value={};let Q=O.shape;for(let k of O.keys){let v=Q[k],C=v._zod.run({value:L[k],issues:[]},H),n=v._zod.optin==="optional"&&v._zod.optout==="optional";if(C instanceof Promise)F.push(C.then((T0)=>n?mM(T0,Y,k,L):N4(T0,Y,k)));else if(n)mM(C,Y,k,L);else N4(C,Y,k)}}if(!W)return F.length?Promise.all(F).then(()=>Y):Y;let j=[],M=O.keySet,z=W._zod,B=z.def.type;for(let Q of Object.keys(L)){if(M.has(Q))continue;if(B==="never"){j.push(Q);continue}let k=z.run({value:L[Q],issues:[]},H);if(k instanceof Promise)F.push(k.then((v)=>N4(v,Y,Q)));else N4(k,Y,Q)}if(j.length)Y.issues.push({code:"unrecognized_keys",keys:j,input:L,inst:$});if(!F.length)return Y;return Promise.all(F).then(()=>{return Y})}});E5=S("$ZodUnion",($,w)=>{_0.init($,w),C0($._zod,"optin",()=>w.options.some((E)=>E._zod.optin==="optional")?"optional":void 0),C0($._zod,"optout",()=>w.options.some((E)=>E._zod.optout==="optional")?"optional":void 0),C0($._zod,"values",()=>{if(w.options.every((E)=>E._zod.values))return new Set(w.options.flatMap((E)=>Array.from(E._zod.values)));return}),C0($._zod,"pattern",()=>{if(w.options.every((E)=>E._zod.pattern)){let E=w.options.map((X)=>X._zod.pattern);return new RegExp(`^(${E.map((X)=>M6(X.source)).join("|")})$`)}return}),$._zod.parse=(E,X)=>{let G=!1,J=[];for(let A of w.options){let D=A._zod.run({value:E.value,issues:[]},X);if(D instanceof Promise)J.push(D),G=!0;else{if(D.issues.length===0)return D;J.push(D)}}if(!G)return rM(J,E,$,X);return Promise.all(J).then((A)=>{return rM(A,E,$,X)})}}),SR=S("$ZodDiscriminatedUnion",($,w)=>{E5.init($,w);let E=$._zod.parse;C0($._zod,"propValues",()=>{let G={};for(let J of w.options){let A=J._zod.propValues;if(!A||Object.keys(A).length===0)throw Error(`Invalid discriminated union option at index "${w.options.indexOf(J)}"`);for(let[D,N]of Object.entries(A)){if(!G[D])G[D]=new Set;for(let W of N)G[D].add(W)}}return G});let X=F6(()=>{let G=w.options,J=new Map;for(let A of G){let D=A._zod.propValues[w.discriminator];if(!D||D.size===0)throw Error(`Invalid discriminated union option at index "${w.options.indexOf(A)}"`);for(let N of D){if(J.has(N))throw Error(`Duplicate discriminator value "${String(N)}"`);J.set(N,A)}}return J});$._zod.parse=(G,J)=>{let A=G.value;if(!CX(A))return G.issues.push({code:"invalid_type",expected:"object",input:A,inst:$}),G;let D=X.value.get(A?.[w.discriminator]);if(D)return D._zod.run(G,J);if(w.unionFallback)return E(G,J);return G.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:A,path:[w.discriminator],inst:$}),G}}),kR=S("$ZodIntersection",($,w)=>{_0.init($,w),$._zod.parse=(E,X)=>{let G=E.value,J=w.left._zod.run({value:G,issues:[]},X),A=w.right._zod.run({value:G,issues:[]},X);if(J instanceof Promise||A instanceof Promise)return Promise.all([J,A]).then(([N,W])=>{return pM(E,N,W)});return pM(E,J,A)}});bR=S("$ZodRecord",($,w)=>{_0.init($,w),$._zod.parse=(E,X)=>{let G=E.value;if(!_X(G))return E.issues.push({expected:"record",code:"invalid_type",input:G,inst:$}),E;let J=[];if(w.keyType._zod.values){let A=w.keyType._zod.values;E.value={};for(let N of A)if(typeof N==="string"||typeof N==="number"||typeof N==="symbol"){let W=w.valueType._zod.run({value:G[N],issues:[]},X);if(W instanceof Promise)J.push(W.then((O)=>{if(O.issues.length)E.issues.push(...Jw(N,O.issues));E.value[N]=O.value}));else{if(W.issues.length)E.issues.push(...Jw(N,W.issues));E.value[N]=W.value}}let D;for(let N in G)if(!A.has(N))D=D??[],D.push(N);if(D&&D.length>0)E.issues.push({code:"unrecognized_keys",input:G,inst:$,keys:D})}else{E.value={};for(let A of Reflect.ownKeys(G)){if(A==="__proto__")continue;let D=w.keyType._zod.run({value:A,issues:[]},X);if(D instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(D.issues.length){E.issues.push({origin:"record",code:"invalid_key",issues:D.issues.map((W)=>u1(W,X,R1())),input:A,path:[A],inst:$}),E.value[D.value]=D.value;continue}let N=w.valueType._zod.run({value:G[A],issues:[]},X);if(N instanceof Promise)J.push(N.then((W)=>{if(W.issues.length)E.issues.push(...Jw(A,W.issues));E.value[D.value]=W.value}));else{if(N.issues.length)E.issues.push(...Jw(A,N.issues));E.value[D.value]=N.value}}}if(J.length)return Promise.all(J).then(()=>E);return E}}),ZR=S("$ZodEnum",($,w)=>{_0.init($,w);let E=_9(w.entries);$._zod.values=new Set(E),$._zod.pattern=new RegExp(`^(${E.filter((X)=>g9.has(typeof X)).map((X)=>typeof X==="string"?dw(X):X.toString()).join("|")})$`),$._zod.parse=(X,G)=>{let J=X.value;if($._zod.values.has(J))return X;return X.issues.push({code:"invalid_value",values:E,input:J,inst:$}),X}}),CR=S("$ZodLiteral",($,w)=>{_0.init($,w),$._zod.values=new Set(w.values),$._zod.pattern=new RegExp(`^(${w.values.map((E)=>typeof E==="string"?dw(E):E?E.toString():String(E)).join("|")})$`),$._zod.parse=(E,X)=>{let G=E.value;if($._zod.values.has(G))return E;return E.issues.push({code:"invalid_value",values:w.values,input:G,inst:$}),E}}),_R=S("$ZodTransform",($,w)=>{_0.init($,w),$._zod.parse=(E,X)=>{let G=w.transform(E.value,E);if(X.async)return(G instanceof Promise?G:Promise.resolve(G)).then((A)=>{return E.value=A,E});if(G instanceof Promise)throw new iw;return E.value=G,E}}),vR=S("$ZodOptional",($,w)=>{_0.init($,w),$._zod.optin="optional",$._zod.optout="optional",C0($._zod,"values",()=>{return w.innerType._zod.values?new Set([...w.innerType._zod.values,void 0]):void 0}),C0($._zod,"pattern",()=>{let E=w.innerType._zod.pattern;return E?new RegExp(`^(${M6(E.source)})?$`):void 0}),$._zod.parse=(E,X)=>{if(w.innerType._zod.optin==="optional")return w.innerType._zod.run(E,X);if(E.value===void 0)return E;return w.innerType._zod.run(E,X)}}),fR=S("$ZodNullable",($,w)=>{_0.init($,w),C0($._zod,"optin",()=>w.innerType._zod.optin),C0($._zod,"optout",()=>w.innerType._zod.optout),C0($._zod,"pattern",()=>{let E=w.innerType._zod.pattern;return E?new RegExp(`^(${M6(E.source)}|null)$`):void 0}),C0($._zod,"values",()=>{return w.innerType._zod.values?new Set([...w.innerType._zod.values,null]):void 0}),$._zod.parse=(E,X)=>{if(E.value===null)return E;return w.innerType._zod.run(E,X)}}),xR=S("$ZodDefault",($,w)=>{_0.init($,w),$._zod.optin="optional",C0($._zod,"values",()=>w.innerType._zod.values),$._zod.parse=(E,X)=>{if(E.value===void 0)return E.value=w.defaultValue,E;let G=w.innerType._zod.run(E,X);if(G instanceof Promise)return G.then((J)=>oM(J,w));return oM(G,w)}});yR=S("$ZodPrefault",($,w)=>{_0.init($,w),$._zod.optin="optional",C0($._zod,"values",()=>w.innerType._zod.values),$._zod.parse=(E,X)=>{if(E.value===void 0)E.value=w.defaultValue;return w.innerType._zod.run(E,X)}}),gR=S("$ZodNonOptional",($,w)=>{_0.init($,w),C0($._zod,"values",()=>{let E=w.innerType._zod.values;return E?new Set([...E].filter((X)=>X!==void 0)):void 0}),$._zod.parse=(E,X)=>{let G=w.innerType._zod.run(E,X);if(G instanceof Promise)return G.then((J)=>tM(J,$));return tM(G,$)}});uR=S("$ZodCatch",($,w)=>{_0.init($,w),$._zod.optin="optional",C0($._zod,"optout",()=>w.innerType._zod.optout),C0($._zod,"values",()=>w.innerType._zod.values),$._zod.parse=(E,X)=>{let G=w.innerType._zod.run(E,X);if(G instanceof Promise)return G.then((J)=>{if(E.value=J.value,J.issues.length)E.value=w.catchValue({...E,error:{issues:J.issues.map((A)=>u1(A,X,R1()))},input:E.value}),E.issues=[];return E});if(E.value=G.value,G.issues.length)E.value=w.catchValue({...E,error:{issues:G.issues.map((J)=>u1(J,X,R1()))},input:E.value}),E.issues=[];return E}}),hR=S("$ZodPipe",($,w)=>{_0.init($,w),C0($._zod,"values",()=>w.in._zod.values),C0($._zod,"optin",()=>w.in._zod.optin),C0($._zod,"optout",()=>w.out._zod.optout),$._zod.parse=(E,X)=>{let G=w.in._zod.run(E,X);if(G instanceof Promise)return G.then((J)=>iM(J,w,X));return iM(G,w,X)}});cR=S("$ZodReadonly",($,w)=>{_0.init($,w),C0($._zod,"propValues",()=>w.innerType._zod.propValues),C0($._zod,"values",()=>w.innerType._zod.values),C0($._zod,"optin",()=>w.innerType._zod.optin),C0($._zod,"optout",()=>w.innerType._zod.optout),$._zod.parse=(E,X)=>{let G=w.innerType._zod.run(E,X);if(G instanceof Promise)return G.then(dM);return dM(G)}});nR=S("$ZodCustom",($,w)=>{b$.init($,w),_0.init($,w),$._zod.parse=(E,X)=>{return E},$._zod.check=(E)=>{let X=E.value,G=w.fn(X);if(G instanceof Promise)return G.then((J)=>lM(J,E,X,$));lM(G,E,X,$);return}})});function X5(){return{localeError:iv()}}var tv=($)=>{let w=typeof $;switch(w){case"number":return Number.isNaN($)?"NaN":"number";case"object":{if(Array.isArray($))return"array";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return w},iv=()=>{let $={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function w(X){return $[X]??null}let E={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return(X)=>{switch(X.code){case"invalid_type":return`Invalid input: expected ${X.expected}, received ${tv(X.input)}`;case"invalid_value":if(X.values.length===1)return`Invalid input: expected ${X4(X.values[0])}`;return`Invalid option: expected one of ${w4(X.values,"|")}`;case"too_big":{let G=X.inclusive?"<=":"<",J=w(X.origin);if(J)return`Too big: expected ${X.origin??"value"} to have ${G}${X.maximum.toString()} ${J.unit??"elements"}`;return`Too big: expected ${X.origin??"value"} to be ${G}${X.maximum.toString()}`}case"too_small":{let G=X.inclusive?">=":">",J=w(X.origin);if(J)return`Too small: expected ${X.origin} to have ${G}${X.minimum.toString()} ${J.unit}`;return`Too small: expected ${X.origin} to be ${G}${X.minimum.toString()}`}case"invalid_format":{let G=X;if(G.format==="starts_with")return`Invalid string: must start with "${G.prefix}"`;if(G.format==="ends_with")return`Invalid string: must end with "${G.suffix}"`;if(G.format==="includes")return`Invalid string: must include "${G.includes}"`;if(G.format==="regex")return`Invalid string: must match pattern ${G.pattern}`;return`Invalid ${E[G.format]??X.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${X.divisor}`;case"unrecognized_keys":return`Unrecognized key${X.keys.length>1?"s":""}: ${w4(X.keys,", ")}`;case"invalid_key":return`Invalid key in ${X.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${X.origin}`;default:return"Invalid input"}}};var rR=R(()=>{Kw()});var O4=()=>{};class pR{constructor(){this._map=new Map,this._idmap=new Map}add($,...w){let E=w[0];if(this._map.set($,E),E&&typeof E==="object"&&"id"in E){if(this._idmap.has(E.id))throw Error(`ID ${E.id} already exists in the registry`);this._idmap.set(E.id,$)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove($){let w=this._map.get($);if(w&&typeof w==="object"&&"id"in w)this._idmap.delete(w.id);return this._map.delete($),this}get($){let w=$._zod.parent;if(w){let E={...this.get(w)??{}};return delete E.id,{...E,...this._map.get($)}}return this._map.get($)}has($){return this._map.has($)}}function dv(){return new pR}var cG0,nG0,B6;var oR=R(()=>{cG0=Symbol("ZodOutput"),nG0=Symbol("ZodInput");B6=dv()});function tR($,w){return new $({type:"string",...l(w)})}function iR($,w){return new $({type:"string",format:"email",check:"string_format",abort:!1,...l(w)})}function J5($,w){return new $({type:"string",format:"guid",check:"string_format",abort:!1,...l(w)})}function dR($,w){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,...l(w)})}function lR($,w){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...l(w)})}function sR($,w){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...l(w)})}function aR($,w){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...l(w)})}function eR($,w){return new $({type:"string",format:"url",check:"string_format",abort:!1,...l(w)})}function $z($,w){return new $({type:"string",format:"emoji",check:"string_format",abort:!1,...l(w)})}function wz($,w){return new $({type:"string",format:"nanoid",check:"string_format",abort:!1,...l(w)})}function Ez($,w){return new $({type:"string",format:"cuid",check:"string_format",abort:!1,...l(w)})}function Xz($,w){return new $({type:"string",format:"cuid2",check:"string_format",abort:!1,...l(w)})}function Gz($,w){return new $({type:"string",format:"ulid",check:"string_format",abort:!1,...l(w)})}function Jz($,w){return new $({type:"string",format:"xid",check:"string_format",abort:!1,...l(w)})}function Az($,w){return new $({type:"string",format:"ksuid",check:"string_format",abort:!1,...l(w)})}function Dz($,w){return new $({type:"string",format:"ipv4",check:"string_format",abort:!1,...l(w)})}function Nz($,w){return new $({type:"string",format:"ipv6",check:"string_format",abort:!1,...l(w)})}function Wz($,w){return new $({type:"string",format:"cidrv4",check:"string_format",abort:!1,...l(w)})}function Oz($,w){return new $({type:"string",format:"cidrv6",check:"string_format",abort:!1,...l(w)})}function Uz($,w){return new $({type:"string",format:"base64",check:"string_format",abort:!1,...l(w)})}function Yz($,w){return new $({type:"string",format:"base64url",check:"string_format",abort:!1,...l(w)})}function Hz($,w){return new $({type:"string",format:"e164",check:"string_format",abort:!1,...l(w)})}function Lz($,w){return new $({type:"string",format:"jwt",check:"string_format",abort:!1,...l(w)})}function Fz($,w){return new $({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...l(w)})}function jz($,w){return new $({type:"string",format:"date",check:"string_format",...l(w)})}function Mz($,w){return new $({type:"string",format:"time",check:"string_format",precision:null,...l(w)})}function Rz($,w){return new $({type:"string",format:"duration",check:"string_format",...l(w)})}function zz($,w){return new $({type:"number",checks:[],...l(w)})}function Tz($,w){return new $({type:"number",check:"number_format",abort:!1,format:"safeint",...l(w)})}function Bz($,w){return new $({type:"boolean",...l(w)})}function Qz($,w){return new $({type:"null",...l(w)})}function Iz($){return new $({type:"unknown"})}function Kz($,w){return new $({type:"never",...l(w)})}function U4($,w){return new l9({check:"less_than",...l(w),value:$,inclusive:!1})}function Q6($,w){return new l9({check:"less_than",...l(w),value:$,inclusive:!0})}function Y4($,w){return new s9({check:"greater_than",...l(w),value:$,inclusive:!1})}function I6($,w){return new s9({check:"greater_than",...l(w),value:$,inclusive:!0})}function H4($,w){return new SM({check:"multiple_of",...l(w),value:$})}function L4($,w){return new bM({check:"max_length",...l(w),maximum:$})}function vX($,w){return new ZM({check:"min_length",...l(w),minimum:$})}function F4($,w){return new CM({check:"length_equals",...l(w),length:$})}function A5($,w){return new _M({check:"string_format",format:"regex",...l(w),pattern:$})}function D5($){return new vM({check:"string_format",format:"lowercase",...l($)})}function N5($){return new fM({check:"string_format",format:"uppercase",...l($)})}function W5($,w){return new xM({check:"string_format",format:"includes",...l(w),includes:$})}function O5($,w){return new yM({check:"string_format",format:"starts_with",...l(w),prefix:$})}function U5($,w){return new gM({check:"string_format",format:"ends_with",...l(w),suffix:$})}function SE($){return new uM({check:"overwrite",tx:$})}function Y5($){return SE((w)=>w.normalize($))}function H5(){return SE(($)=>$.trim())}function L5(){return SE(($)=>$.toLowerCase())}function F5(){return SE(($)=>$.toUpperCase())}function Vz($,w,E){return new $({type:"array",element:w,...l(E)})}function Pz($,w,E){let X=l(E);return X.abort??(X.abort=!0),new $({type:"custom",check:"custom",fn:w,...X})}function qz($,w,E){return new $({type:"custom",check:"custom",fn:w,...l(E)})}var Sz=R(()=>{D4();Kw()});var kz=()=>{};var bz=()=>{};var Zz=()=>{};var z1=R(()=>{Kw();A4();O4();Zz();ZX();o9();m9();mR();D4();e9();oR();kz();Sz();bz()});var Cz=R(()=>{z1()});var _z=()=>{};var vz=()=>{};var fz=()=>{};var xz=()=>{};var yz=R(()=>{z1();O4();fz();xz();Cz();_z();vz()});var gz=R(()=>{yz()});var uz=R(()=>{gz()});function xX($){return!!$._zod}function lw($,w){if(xX($))return z6($,w);return $.safeParse(w)}function j4($){if(!$)return;let w;if(xX($))w=$._zod?.def?.shape;else w=$.shape;if(!w)return;if(typeof w==="function")try{return w()}catch{return}return w}function hz($){if(xX($)){let J=$._zod?.def;if(J){if(J.value!==void 0)return J.value;if(Array.isArray(J.values)&&J.values.length>0)return J.values[0]}}let E=$._def;if(E){if(E.value!==void 0)return E.value;if(Array.isArray(E.values)&&E.values.length>0)return E.values[0]}let X=$.value;if(X!==void 0)return X;return}var M4=R(()=>{uz()});var j5=R(()=>{z1()});var K6={};Ww(K6,{time:()=>z5,duration:()=>T5,datetime:()=>M5,date:()=>R5,ZodISOTime:()=>mz,ZodISODuration:()=>rz,ZodISODateTime:()=>cz,ZodISODate:()=>nz});function M5($){return Fz(cz,$)}function R5($){return jz(nz,$)}function z5($){return Mz(mz,$)}function T5($){return Rz(rz,$)}var cz,nz,mz,rz;var B5=R(()=>{z1();Q5();cz=S("ZodISODateTime",($,w)=>{NR.init($,w),o0.init($,w)});nz=S("ZodISODate",($,w)=>{WR.init($,w),o0.init($,w)});mz=S("ZodISOTime",($,w)=>{OR.init($,w),o0.init($,w)});rz=S("ZodISODuration",($,w)=>{UR.init($,w),o0.init($,w)})});var pz=($,w)=>{G4.init($,w),$.name="ZodError",Object.defineProperties($,{format:{value:(E)=>dj($,E)},flatten:{value:(E)=>ij($,E)},addIssue:{value:(E)=>$.issues.push(E)},addIssues:{value:(E)=>$.issues.push(...E)},isEmpty:{get(){return $.issues.length===0}}})},C60,V6;var I5=R(()=>{z1();z1();C60=S("ZodError",pz),V6=S("ZodError",pz,{Parent:Error})});var oz,tz,iz,dz;var K5=R(()=>{z1();I5();oz=lj(V6),tz=sj(V6),iz=r9(V6),dz=p9(V6)});function P($){return tR(Af,$)}function q0($){return zz($T,$)}function sz($){return Tz(Kf,$)}function F$($){return Bz(Vf,$)}function q5($){return Qz(Pf,$)}function t0(){return Iz(qf)}function kf($){return Kz(Sf,$)}function j0($,w){return Vz(bf,$,w)}function u($,w){let E={type:"object",get shape(){return B0.assignProp(this,"shape",{...$}),this.shape},...B0.normalizeParams(w)};return new wT(E)}function h$($,w){return new wT({type:"object",get shape(){return B0.assignProp(this,"shape",{...$}),this.shape},catchall:t0(),...B0.normalizeParams(w)})}function v0($,w){return new ET({type:"union",options:$,...B0.normalizeParams(w)})}function S5($,w,E){return new Zf({type:"union",options:w,discriminator:$,...B0.normalizeParams(E)})}function z4($,w){return new Cf({type:"intersection",left:$,right:w})}function i0($,w,E){return new _f({type:"record",keyType:$,valueType:w,...B0.normalizeParams(E)})}function a$($,w){let E=Array.isArray($)?Object.fromEntries($.map((X)=>[X,X])):$;return new V5({type:"enum",entries:E,...B0.normalizeParams(w)})}function p($,w){return new vf({type:"literal",values:Array.isArray($)?$:[$],...B0.normalizeParams(w)})}function XT($){return new ff({type:"transform",transform:$})}function a0($){return new GT({type:"optional",innerType:$})}function az($){return new xf({type:"nullable",innerType:$})}function gf($,w){return new yf({type:"default",innerType:$,get defaultValue(){return typeof w==="function"?w():w}})}function hf($,w){return new uf({type:"prefault",innerType:$,get defaultValue(){return typeof w==="function"?w():w}})}function cf($,w){return new JT({type:"nonoptional",innerType:$,...B0.normalizeParams(w)})}function mf($,w){return new nf({type:"catch",innerType:$,catchValue:typeof w==="function"?w:()=>w})}function P5($,w){return new rf({type:"pipe",in:$,out:w})}function of($){return new pf({type:"readonly",innerType:$})}function tf($){let w=new b$({check:"custom"});return w._zod.check=$,w}function DT($,w){return Pz(AT,$??(()=>!0),w)}function df($,w={}){return qz(AT,$,w)}function lf($){let w=tf((E)=>{return E.addIssue=(X)=>{if(typeof X==="string")E.issues.push(B0.issue(X,E.value,w._zod.def));else{let G=X;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=E.value),G.inst??(G.inst=w),G.continue??(G.continue=!w._zod.def.abort),E.issues.push(B0.issue(G))}},$(E.value,E)});return w}function k5($,w){return P5(XT($),w)}var e0,ez,Af,o0,Df,lz,R4,Nf,Wf,Of,Uf,Yf,Hf,Lf,Ff,jf,Mf,Rf,zf,Tf,Bf,Qf,If,$T,Kf,Vf,Pf,qf,Sf,bf,wT,ET,Zf,Cf,_f,V5,vf,ff,GT,xf,yf,uf,JT,nf,rf,pf,AT;var Q5=R(()=>{z1();z1();j5();B5();K5();e0=S("ZodType",($,w)=>{return _0.init($,w),$.def=w,Object.defineProperty($,"_def",{value:w}),$.check=(...E)=>{return $.clone({...w,checks:[...w.checks??[],...E.map((X)=>typeof X==="function"?{_zod:{check:X,def:{check:"custom"},onattach:[]}}:X)]})},$.clone=(E,X)=>Gw($,E,X),$.brand=()=>$,$.register=(E,X)=>{return E.add($,X),$},$.parse=(E,X)=>oz($,E,X,{callee:$.parse}),$.safeParse=(E,X)=>iz($,E,X),$.parseAsync=async(E,X)=>tz($,E,X,{callee:$.parseAsync}),$.safeParseAsync=async(E,X)=>dz($,E,X),$.spa=$.safeParseAsync,$.refine=(E,X)=>$.check(df(E,X)),$.superRefine=(E)=>$.check(lf(E)),$.overwrite=(E)=>$.check(SE(E)),$.optional=()=>a0($),$.nullable=()=>az($),$.nullish=()=>a0(az($)),$.nonoptional=(E)=>cf($,E),$.array=()=>j0($),$.or=(E)=>v0([$,E]),$.and=(E)=>z4($,E),$.transform=(E)=>P5($,XT(E)),$.default=(E)=>gf($,E),$.prefault=(E)=>hf($,E),$.catch=(E)=>mf($,E),$.pipe=(E)=>P5($,E),$.readonly=()=>of($),$.describe=(E)=>{let X=$.clone();return B6.add(X,{description:E}),X},Object.defineProperty($,"description",{get(){return B6.get($)?.description},configurable:!0}),$.meta=(...E)=>{if(E.length===0)return B6.get($);let X=$.clone();return B6.add(X,E[0]),X},$.isOptional=()=>$.safeParse(void 0).success,$.isNullable=()=>$.safeParse(null).success,$}),ez=S("_ZodString",($,w)=>{W4.init($,w),e0.init($,w);let E=$._zod.bag;$.format=E.format??null,$.minLength=E.minimum??null,$.maxLength=E.maximum??null,$.regex=(...X)=>$.check(A5(...X)),$.includes=(...X)=>$.check(W5(...X)),$.startsWith=(...X)=>$.check(O5(...X)),$.endsWith=(...X)=>$.check(U5(...X)),$.min=(...X)=>$.check(vX(...X)),$.max=(...X)=>$.check(L4(...X)),$.length=(...X)=>$.check(F4(...X)),$.nonempty=(...X)=>$.check(vX(1,...X)),$.lowercase=(X)=>$.check(D5(X)),$.uppercase=(X)=>$.check(N5(X)),$.trim=()=>$.check(H5()),$.normalize=(...X)=>$.check(Y5(...X)),$.toLowerCase=()=>$.check(L5()),$.toUpperCase=()=>$.check(F5())}),Af=S("ZodString",($,w)=>{W4.init($,w),ez.init($,w),$.email=(E)=>$.check(iR(Df,E)),$.url=(E)=>$.check(eR(Nf,E)),$.jwt=(E)=>$.check(Lz(If,E)),$.emoji=(E)=>$.check($z(Wf,E)),$.guid=(E)=>$.check(J5(lz,E)),$.uuid=(E)=>$.check(dR(R4,E)),$.uuidv4=(E)=>$.check(lR(R4,E)),$.uuidv6=(E)=>$.check(sR(R4,E)),$.uuidv7=(E)=>$.check(aR(R4,E)),$.nanoid=(E)=>$.check(wz(Of,E)),$.guid=(E)=>$.check(J5(lz,E)),$.cuid=(E)=>$.check(Ez(Uf,E)),$.cuid2=(E)=>$.check(Xz(Yf,E)),$.ulid=(E)=>$.check(Gz(Hf,E)),$.base64=(E)=>$.check(Uz(Tf,E)),$.base64url=(E)=>$.check(Yz(Bf,E)),$.xid=(E)=>$.check(Jz(Lf,E)),$.ksuid=(E)=>$.check(Az(Ff,E)),$.ipv4=(E)=>$.check(Dz(jf,E)),$.ipv6=(E)=>$.check(Nz(Mf,E)),$.cidrv4=(E)=>$.check(Wz(Rf,E)),$.cidrv6=(E)=>$.check(Oz(zf,E)),$.e164=(E)=>$.check(Hz(Qf,E)),$.datetime=(E)=>$.check(M5(E)),$.date=(E)=>$.check(R5(E)),$.time=(E)=>$.check(z5(E)),$.duration=(E)=>$.check(T5(E))});o0=S("ZodStringFormat",($,w)=>{u0.init($,w),ez.init($,w)}),Df=S("ZodEmail",($,w)=>{eM.init($,w),o0.init($,w)}),lz=S("ZodGUID",($,w)=>{sM.init($,w),o0.init($,w)}),R4=S("ZodUUID",($,w)=>{aM.init($,w),o0.init($,w)}),Nf=S("ZodURL",($,w)=>{$R.init($,w),o0.init($,w)}),Wf=S("ZodEmoji",($,w)=>{wR.init($,w),o0.init($,w)}),Of=S("ZodNanoID",($,w)=>{ER.init($,w),o0.init($,w)}),Uf=S("ZodCUID",($,w)=>{XR.init($,w),o0.init($,w)}),Yf=S("ZodCUID2",($,w)=>{GR.init($,w),o0.init($,w)}),Hf=S("ZodULID",($,w)=>{JR.init($,w),o0.init($,w)}),Lf=S("ZodXID",($,w)=>{AR.init($,w),o0.init($,w)}),Ff=S("ZodKSUID",($,w)=>{DR.init($,w),o0.init($,w)}),jf=S("ZodIPv4",($,w)=>{YR.init($,w),o0.init($,w)}),Mf=S("ZodIPv6",($,w)=>{HR.init($,w),o0.init($,w)}),Rf=S("ZodCIDRv4",($,w)=>{LR.init($,w),o0.init($,w)}),zf=S("ZodCIDRv6",($,w)=>{FR.init($,w),o0.init($,w)}),Tf=S("ZodBase64",($,w)=>{MR.init($,w),o0.init($,w)}),Bf=S("ZodBase64URL",($,w)=>{RR.init($,w),o0.init($,w)}),Qf=S("ZodE164",($,w)=>{zR.init($,w),o0.init($,w)}),If=S("ZodJWT",($,w)=>{TR.init($,w),o0.init($,w)}),$T=S("ZodNumber",($,w)=>{w5.init($,w),e0.init($,w),$.gt=(X,G)=>$.check(Y4(X,G)),$.gte=(X,G)=>$.check(I6(X,G)),$.min=(X,G)=>$.check(I6(X,G)),$.lt=(X,G)=>$.check(U4(X,G)),$.lte=(X,G)=>$.check(Q6(X,G)),$.max=(X,G)=>$.check(Q6(X,G)),$.int=(X)=>$.check(sz(X)),$.safe=(X)=>$.check(sz(X)),$.positive=(X)=>$.check(Y4(0,X)),$.nonnegative=(X)=>$.check(I6(0,X)),$.negative=(X)=>$.check(U4(0,X)),$.nonpositive=(X)=>$.check(Q6(0,X)),$.multipleOf=(X,G)=>$.check(H4(X,G)),$.step=(X,G)=>$.check(H4(X,G)),$.finite=()=>$;let E=$._zod.bag;$.minValue=Math.max(E.minimum??Number.NEGATIVE_INFINITY,E.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,$.maxValue=Math.min(E.maximum??Number.POSITIVE_INFINITY,E.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,$.isInt=(E.format??"").includes("int")||Number.isSafeInteger(E.multipleOf??0.5),$.isFinite=!0,$.format=E.format??null});Kf=S("ZodNumberFormat",($,w)=>{BR.init($,w),$T.init($,w)});Vf=S("ZodBoolean",($,w)=>{QR.init($,w),e0.init($,w)});Pf=S("ZodNull",($,w)=>{IR.init($,w),e0.init($,w)});qf=S("ZodUnknown",($,w)=>{KR.init($,w),e0.init($,w)});Sf=S("ZodNever",($,w)=>{VR.init($,w),e0.init($,w)});bf=S("ZodArray",($,w)=>{PR.init($,w),e0.init($,w),$.element=w.element,$.min=(E,X)=>$.check(vX(E,X)),$.nonempty=(E)=>$.check(vX(1,E)),$.max=(E,X)=>$.check(L4(E,X)),$.length=(E,X)=>$.check(F4(E,X)),$.unwrap=()=>$.element});wT=S("ZodObject",($,w)=>{qR.init($,w),e0.init($,w),B0.defineLazy($,"shape",()=>w.shape),$.keyof=()=>a$(Object.keys($._zod.def.shape)),$.catchall=(E)=>$.clone({...$._zod.def,catchall:E}),$.passthrough=()=>$.clone({...$._zod.def,catchall:t0()}),$.loose=()=>$.clone({...$._zod.def,catchall:t0()}),$.strict=()=>$.clone({...$._zod.def,catchall:kf()}),$.strip=()=>$.clone({...$._zod.def,catchall:void 0}),$.extend=(E)=>{return B0.extend($,E)},$.merge=(E)=>B0.merge($,E),$.pick=(E)=>B0.pick($,E),$.omit=(E)=>B0.omit($,E),$.partial=(...E)=>B0.partial(GT,$,E[0]),$.required=(...E)=>B0.required(JT,$,E[0])});ET=S("ZodUnion",($,w)=>{E5.init($,w),e0.init($,w),$.options=w.options});Zf=S("ZodDiscriminatedUnion",($,w)=>{ET.init($,w),SR.init($,w)});Cf=S("ZodIntersection",($,w)=>{kR.init($,w),e0.init($,w)});_f=S("ZodRecord",($,w)=>{bR.init($,w),e0.init($,w),$.keyType=w.keyType,$.valueType=w.valueType});V5=S("ZodEnum",($,w)=>{ZR.init($,w),e0.init($,w),$.enum=w.entries,$.options=Object.values(w.entries);let E=new Set(Object.keys(w.entries));$.extract=(X,G)=>{let J={};for(let A of X)if(E.has(A))J[A]=w.entries[A];else throw Error(`Key ${A} not found in enum`);return new V5({...w,checks:[],...B0.normalizeParams(G),entries:J})},$.exclude=(X,G)=>{let J={...w.entries};for(let A of X)if(E.has(A))delete J[A];else throw Error(`Key ${A} not found in enum`);return new V5({...w,checks:[],...B0.normalizeParams(G),entries:J})}});vf=S("ZodLiteral",($,w)=>{CR.init($,w),e0.init($,w),$.values=new Set(w.values),Object.defineProperty($,"value",{get(){if(w.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return w.values[0]}})});ff=S("ZodTransform",($,w)=>{_R.init($,w),e0.init($,w),$._zod.parse=(E,X)=>{E.addIssue=(J)=>{if(typeof J==="string")E.issues.push(B0.issue(J,E.value,w));else{let A=J;if(A.fatal)A.continue=!1;A.code??(A.code="custom"),A.input??(A.input=E.value),A.inst??(A.inst=$),A.continue??(A.continue=!0),E.issues.push(B0.issue(A))}};let G=w.transform(E.value,E);if(G instanceof Promise)return G.then((J)=>{return E.value=J,E});return E.value=G,E}});GT=S("ZodOptional",($,w)=>{vR.init($,w),e0.init($,w),$.unwrap=()=>$._zod.def.innerType});xf=S("ZodNullable",($,w)=>{fR.init($,w),e0.init($,w),$.unwrap=()=>$._zod.def.innerType});yf=S("ZodDefault",($,w)=>{xR.init($,w),e0.init($,w),$.unwrap=()=>$._zod.def.innerType,$.removeDefault=$.unwrap});uf=S("ZodPrefault",($,w)=>{yR.init($,w),e0.init($,w),$.unwrap=()=>$._zod.def.innerType});JT=S("ZodNonOptional",($,w)=>{gR.init($,w),e0.init($,w),$.unwrap=()=>$._zod.def.innerType});nf=S("ZodCatch",($,w)=>{uR.init($,w),e0.init($,w),$.unwrap=()=>$._zod.def.innerType,$.removeCatch=$.unwrap});rf=S("ZodPipe",($,w)=>{hR.init($,w),e0.init($,w),$.in=w.in,$.out=w.out});pf=S("ZodReadonly",($,w)=>{cR.init($,w),e0.init($,w)});AT=S("ZodCustom",($,w)=>{nR.init($,w),e0.init($,w)})});var NT=()=>{};var WT=()=>{};var OT=R(()=>{z1();z1();rR();O4();B5();WT();Q5();j5();I5();K5();NT();R1(X5())});var UT=R(()=>{OT()});var YT=R(()=>{UT()});var b5="2025-11-25",HT,sw="io.modelcontextprotocol/related-task",B4="2.0",T$,LT,FT,qJ0,ef,$x,Z5,W1,P6,jT=($)=>P6.safeParse($).success,B$,T1,B1,Q$,Q4,MT,C5=($)=>MT.safeParse($).success,RT,zT=($)=>RT.safeParse($).success,_5,q6=($)=>_5.safeParse($).success,L0,v5,TT=($)=>v5.safeParse($).success,BT,SJ0,I4,wx,K4,Ex,S6,yX,QT,Xx,Gx,Jx,Ax,Dx,Nx,f5,Wx,Ox,x5,V4,Ux,Yx,P4,Hx,k6,b6,Lx,Z6,gX,Fx,C6,q4,S4,k4,kJ0,b4,Z4,C4,IT,KT,VT,y5,PT,_6,uX,qT,jx,Mx,Rx,zx,Tx,g5,Bx,Qx,Ix,Kx,Vx,Px,qx,Sx,kx,bx,Zx,Cx,_x,vx,fx,xx,u5,h5,c5,yx,gx,ux,n5,hx,cx,nx,mx,rx,ST,m5,px,_4,bJ0,ox,v6,tx,ZJ0,f6,ix,r5,dx,lx,sx,ax,ex,$y,wy,T4,Ey,Xy,Gy,x6,p5,Jy,Ay,Dy,Ny,Wy,Oy,Uy,Yy,Hy,Ly,Fy,jy,My,Ry,zy,Ty,By,Qy,hX,Iy,Ky,Vy,Py,qy,Sy,ky,o5,by,CJ0,_J0,vJ0,fJ0,xJ0,yJ0,A0,kT;var cX=R(()=>{YT();HT=[b5,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],T$=DT(($)=>$!==null&&(typeof $==="object"||typeof $==="function")),LT=v0([P(),q0().int()]),FT=P(),qJ0=h$({ttl:v0([q0(),q5()]).optional(),pollInterval:q0().optional()}),ef=u({ttl:q0().optional()}),$x=u({taskId:P()}),Z5=h$({progressToken:LT.optional(),[sw]:$x.optional()}),W1=u({_meta:Z5.optional()}),P6=W1.extend({task:ef.optional()}),B$=u({method:P(),params:W1.loose().optional()}),T1=u({_meta:Z5.optional()}),B1=u({method:P(),params:T1.loose().optional()}),Q$=h$({_meta:Z5.optional()}),Q4=v0([P(),q0().int()]),MT=u({jsonrpc:p(B4),id:Q4,...B$.shape}).strict(),RT=u({jsonrpc:p(B4),...B1.shape}).strict(),_5=u({jsonrpc:p(B4),id:Q4,result:Q$}).strict();(function($){$[$.ConnectionClosed=-32000]="ConnectionClosed",$[$.RequestTimeout=-32001]="RequestTimeout",$[$.ParseError=-32700]="ParseError",$[$.InvalidRequest=-32600]="InvalidRequest",$[$.MethodNotFound=-32601]="MethodNotFound",$[$.InvalidParams=-32602]="InvalidParams",$[$.InternalError=-32603]="InternalError",$[$.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(L0||(L0={}));v5=u({jsonrpc:p(B4),id:Q4.optional(),error:u({code:q0().int(),message:P(),data:t0().optional()})}).strict(),BT=v0([MT,RT,_5,v5]),SJ0=v0([_5,v5]),I4=Q$.strict(),wx=T1.extend({requestId:Q4.optional(),reason:P().optional()}),K4=B1.extend({method:p("notifications/cancelled"),params:wx}),Ex=u({src:P(),mimeType:P().optional(),sizes:j0(P()).optional(),theme:a$(["light","dark"]).optional()}),S6=u({icons:j0(Ex).optional()}),yX=u({name:P(),title:P().optional()}),QT=yX.extend({...yX.shape,...S6.shape,version:P(),websiteUrl:P().optional(),description:P().optional()}),Xx=z4(u({applyDefaults:F$().optional()}),i0(P(),t0())),Gx=k5(($)=>{if($&&typeof $==="object"&&!Array.isArray($)){if(Object.keys($).length===0)return{form:{}}}return $},z4(u({form:Xx.optional(),url:T$.optional()}),i0(P(),t0()).optional())),Jx=h$({list:T$.optional(),cancel:T$.optional(),requests:h$({sampling:h$({createMessage:T$.optional()}).optional(),elicitation:h$({create:T$.optional()}).optional()}).optional()}),Ax=h$({list:T$.optional(),cancel:T$.optional(),requests:h$({tools:h$({call:T$.optional()}).optional()}).optional()}),Dx=u({experimental:i0(P(),T$).optional(),sampling:u({context:T$.optional(),tools:T$.optional()}).optional(),elicitation:Gx.optional(),roots:u({listChanged:F$().optional()}).optional(),tasks:Jx.optional()}),Nx=W1.extend({protocolVersion:P(),capabilities:Dx,clientInfo:QT}),f5=B$.extend({method:p("initialize"),params:Nx}),Wx=u({experimental:i0(P(),T$).optional(),logging:T$.optional(),completions:T$.optional(),prompts:u({listChanged:F$().optional()}).optional(),resources:u({subscribe:F$().optional(),listChanged:F$().optional()}).optional(),tools:u({listChanged:F$().optional()}).optional(),tasks:Ax.optional()}),Ox=Q$.extend({protocolVersion:P(),capabilities:Wx,serverInfo:QT,instructions:P().optional()}),x5=B1.extend({method:p("notifications/initialized"),params:T1.optional()}),V4=B$.extend({method:p("ping"),params:W1.optional()}),Ux=u({progress:q0(),total:a0(q0()),message:a0(P())}),Yx=u({...T1.shape,...Ux.shape,progressToken:LT}),P4=B1.extend({method:p("notifications/progress"),params:Yx}),Hx=W1.extend({cursor:FT.optional()}),k6=B$.extend({params:Hx.optional()}),b6=Q$.extend({nextCursor:FT.optional()}),Lx=a$(["working","input_required","completed","failed","cancelled"]),Z6=u({taskId:P(),status:Lx,ttl:v0([q0(),q5()]),createdAt:P(),lastUpdatedAt:P(),pollInterval:a0(q0()),statusMessage:a0(P())}),gX=Q$.extend({task:Z6}),Fx=T1.merge(Z6),C6=B1.extend({method:p("notifications/tasks/status"),params:Fx}),q4=B$.extend({method:p("tasks/get"),params:W1.extend({taskId:P()})}),S4=Q$.merge(Z6),k4=B$.extend({method:p("tasks/result"),params:W1.extend({taskId:P()})}),kJ0=Q$.loose(),b4=k6.extend({method:p("tasks/list")}),Z4=b6.extend({tasks:j0(Z6)}),C4=B$.extend({method:p("tasks/cancel"),params:W1.extend({taskId:P()})}),IT=Q$.merge(Z6),KT=u({uri:P(),mimeType:a0(P()),_meta:i0(P(),t0()).optional()}),VT=KT.extend({text:P()}),y5=P().refine(($)=>{try{return atob($),!0}catch{return!1}},{message:"Invalid Base64 string"}),PT=KT.extend({blob:y5}),_6=a$(["user","assistant"]),uX=u({audience:j0(_6).optional(),priority:q0().min(0).max(1).optional(),lastModified:K6.datetime({offset:!0}).optional()}),qT=u({...yX.shape,...S6.shape,uri:P(),description:a0(P()),mimeType:a0(P()),annotations:uX.optional(),_meta:a0(h$({}))}),jx=u({...yX.shape,...S6.shape,uriTemplate:P(),description:a0(P()),mimeType:a0(P()),annotations:uX.optional(),_meta:a0(h$({}))}),Mx=k6.extend({method:p("resources/list")}),Rx=b6.extend({resources:j0(qT)}),zx=k6.extend({method:p("resources/templates/list")}),Tx=b6.extend({resourceTemplates:j0(jx)}),g5=W1.extend({uri:P()}),Bx=g5,Qx=B$.extend({method:p("resources/read"),params:Bx}),Ix=Q$.extend({contents:j0(v0([VT,PT]))}),Kx=B1.extend({method:p("notifications/resources/list_changed"),params:T1.optional()}),Vx=g5,Px=B$.extend({method:p("resources/subscribe"),params:Vx}),qx=g5,Sx=B$.extend({method:p("resources/unsubscribe"),params:qx}),kx=T1.extend({uri:P()}),bx=B1.extend({method:p("notifications/resources/updated"),params:kx}),Zx=u({name:P(),description:a0(P()),required:a0(F$())}),Cx=u({...yX.shape,...S6.shape,description:a0(P()),arguments:a0(j0(Zx)),_meta:a0(h$({}))}),_x=k6.extend({method:p("prompts/list")}),vx=b6.extend({prompts:j0(Cx)}),fx=W1.extend({name:P(),arguments:i0(P(),P()).optional()}),xx=B$.extend({method:p("prompts/get"),params:fx}),u5=u({type:p("text"),text:P(),annotations:uX.optional(),_meta:i0(P(),t0()).optional()}),h5=u({type:p("image"),data:y5,mimeType:P(),annotations:uX.optional(),_meta:i0(P(),t0()).optional()}),c5=u({type:p("audio"),data:y5,mimeType:P(),annotations:uX.optional(),_meta:i0(P(),t0()).optional()}),yx=u({type:p("tool_use"),name:P(),id:P(),input:i0(P(),t0()),_meta:i0(P(),t0()).optional()}),gx=u({type:p("resource"),resource:v0([VT,PT]),annotations:uX.optional(),_meta:i0(P(),t0()).optional()}),ux=qT.extend({type:p("resource_link")}),n5=v0([u5,h5,c5,ux,gx]),hx=u({role:_6,content:n5}),cx=Q$.extend({description:P().optional(),messages:j0(hx)}),nx=B1.extend({method:p("notifications/prompts/list_changed"),params:T1.optional()}),mx=u({title:P().optional(),readOnlyHint:F$().optional(),destructiveHint:F$().optional(),idempotentHint:F$().optional(),openWorldHint:F$().optional()}),rx=u({taskSupport:a$(["required","optional","forbidden"]).optional()}),ST=u({...yX.shape,...S6.shape,description:P().optional(),inputSchema:u({type:p("object"),properties:i0(P(),T$).optional(),required:j0(P()).optional()}).catchall(t0()),outputSchema:u({type:p("object"),properties:i0(P(),T$).optional(),required:j0(P()).optional()}).catchall(t0()).optional(),annotations:mx.optional(),execution:rx.optional(),_meta:i0(P(),t0()).optional()}),m5=k6.extend({method:p("tools/list")}),px=b6.extend({tools:j0(ST)}),_4=Q$.extend({content:j0(n5).default([]),structuredContent:i0(P(),t0()).optional(),isError:F$().optional()}),bJ0=_4.or(Q$.extend({toolResult:t0()})),ox=P6.extend({name:P(),arguments:i0(P(),t0()).optional()}),v6=B$.extend({method:p("tools/call"),params:ox}),tx=B1.extend({method:p("notifications/tools/list_changed"),params:T1.optional()}),ZJ0=u({autoRefresh:F$().default(!0),debounceMs:q0().int().nonnegative().default(300)}),f6=a$(["debug","info","notice","warning","error","critical","alert","emergency"]),ix=W1.extend({level:f6}),r5=B$.extend({method:p("logging/setLevel"),params:ix}),dx=T1.extend({level:f6,logger:P().optional(),data:t0()}),lx=B1.extend({method:p("notifications/message"),params:dx}),sx=u({name:P().optional()}),ax=u({hints:j0(sx).optional(),costPriority:q0().min(0).max(1).optional(),speedPriority:q0().min(0).max(1).optional(),intelligencePriority:q0().min(0).max(1).optional()}),ex=u({mode:a$(["auto","required","none"]).optional()}),$y=u({type:p("tool_result"),toolUseId:P().describe("The unique identifier for the corresponding tool call."),content:j0(n5).default([]),structuredContent:u({}).loose().optional(),isError:F$().optional(),_meta:i0(P(),t0()).optional()}),wy=S5("type",[u5,h5,c5]),T4=S5("type",[u5,h5,c5,yx,$y]),Ey=u({role:_6,content:v0([T4,j0(T4)]),_meta:i0(P(),t0()).optional()}),Xy=P6.extend({messages:j0(Ey),modelPreferences:ax.optional(),systemPrompt:P().optional(),includeContext:a$(["none","thisServer","allServers"]).optional(),temperature:q0().optional(),maxTokens:q0().int(),stopSequences:j0(P()).optional(),metadata:T$.optional(),tools:j0(ST).optional(),toolChoice:ex.optional()}),Gy=B$.extend({method:p("sampling/createMessage"),params:Xy}),x6=Q$.extend({model:P(),stopReason:a0(a$(["endTurn","stopSequence","maxTokens"]).or(P())),role:_6,content:wy}),p5=Q$.extend({model:P(),stopReason:a0(a$(["endTurn","stopSequence","maxTokens","toolUse"]).or(P())),role:_6,content:v0([T4,j0(T4)])}),Jy=u({type:p("boolean"),title:P().optional(),description:P().optional(),default:F$().optional()}),Ay=u({type:p("string"),title:P().optional(),description:P().optional(),minLength:q0().optional(),maxLength:q0().optional(),format:a$(["email","uri","date","date-time"]).optional(),default:P().optional()}),Dy=u({type:a$(["number","integer"]),title:P().optional(),description:P().optional(),minimum:q0().optional(),maximum:q0().optional(),default:q0().optional()}),Ny=u({type:p("string"),title:P().optional(),description:P().optional(),enum:j0(P()),default:P().optional()}),Wy=u({type:p("string"),title:P().optional(),description:P().optional(),oneOf:j0(u({const:P(),title:P()})),default:P().optional()}),Oy=u({type:p("string"),title:P().optional(),description:P().optional(),enum:j0(P()),enumNames:j0(P()).optional(),default:P().optional()}),Uy=v0([Ny,Wy]),Yy=u({type:p("array"),title:P().optional(),description:P().optional(),minItems:q0().optional(),maxItems:q0().optional(),items:u({type:p("string"),enum:j0(P())}),default:j0(P()).optional()}),Hy=u({type:p("array"),title:P().optional(),description:P().optional(),minItems:q0().optional(),maxItems:q0().optional(),items:u({anyOf:j0(u({const:P(),title:P()}))}),default:j0(P()).optional()}),Ly=v0([Yy,Hy]),Fy=v0([Oy,Uy,Ly]),jy=v0([Fy,Jy,Ay,Dy]),My=P6.extend({mode:p("form").optional(),message:P(),requestedSchema:u({type:p("object"),properties:i0(P(),jy),required:j0(P()).optional()})}),Ry=P6.extend({mode:p("url"),message:P(),elicitationId:P(),url:P().url()}),zy=v0([My,Ry]),Ty=B$.extend({method:p("elicitation/create"),params:zy}),By=T1.extend({elicitationId:P()}),Qy=B1.extend({method:p("notifications/elicitation/complete"),params:By}),hX=Q$.extend({action:a$(["accept","decline","cancel"]),content:k5(($)=>$===null?void 0:$,i0(P(),v0([P(),q0(),F$(),j0(P())])).optional())}),Iy=u({type:p("ref/resource"),uri:P()}),Ky=u({type:p("ref/prompt"),name:P()}),Vy=W1.extend({ref:v0([Ky,Iy]),argument:u({name:P(),value:P()}),context:u({arguments:i0(P(),P()).optional()}).optional()}),Py=B$.extend({method:p("completion/complete"),params:Vy}),qy=Q$.extend({completion:h$({values:j0(P()).max(100),total:a0(q0().int()),hasMore:a0(F$())})}),Sy=u({uri:P().startsWith("file://"),name:P().optional(),_meta:i0(P(),t0()).optional()}),ky=B$.extend({method:p("roots/list"),params:W1.optional()}),o5=Q$.extend({roots:j0(Sy)}),by=B1.extend({method:p("notifications/roots/list_changed"),params:T1.optional()}),CJ0=v0([V4,f5,Py,r5,xx,_x,Mx,zx,Qx,Px,Sx,v6,m5,q4,k4,b4,C4]),_J0=v0([K4,P4,x5,by,C6]),vJ0=v0([I4,x6,p5,hX,o5,S4,Z4,gX]),fJ0=v0([V4,Gy,Ty,ky,q4,k4,b4,C4]),xJ0=v0([K4,P4,lx,bx,Kx,tx,nx,C6,Qy]),yJ0=v0([I4,Ox,qy,cx,vx,Rx,Tx,Ix,_4,px,S4,Z4,gX]);A0=class A0 extends Error{constructor($,w,E){super(`MCP error ${$}: ${w}`);this.code=$,this.data=E,this.name="McpError"}static fromError($,w,E){if($===L0.UrlElicitationRequired&&E){let X=E;if(X.elicitations)return new kT(X.elicitations,w)}return new A0($,w,E)}};kT=class kT extends A0{constructor($,w=`URL elicitation${$.length>1?"s":""} required`){super(L0.UrlElicitationRequired,w,{elicitations:$})}get elicitations(){return this.data?.elicitations??[]}}});function aw($){return $==="completed"||$==="failed"||$==="cancelled"}var Zy;var v4=R(()=>{Zy=Symbol("Let zodToJsonSchema decide on which parser to use")});var t5=R(()=>{v4()});var Q1=()=>{};var i5=R(()=>{N$()});var d5=()=>{};var f4=R(()=>{N$()});var l5=R(()=>{N$()});var s5=()=>{};var a5=R(()=>{N$()});var e5=R(()=>{N$();Q1()});var $W=R(()=>{N$()});var jA0;var x4=R(()=>{jA0=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});var y4=R(()=>{N$();x4();f4();Q1()});var wW=R(()=>{N$();y4();Q1()});var EW=R(()=>{Q1()});var g4=R(()=>{N$()});var XW=R(()=>{N$();g4()});var GW=()=>{};var JW=R(()=>{N$()});var AW=R(()=>{N$();Q1()});var DW=R(()=>{N$()});var NW=R(()=>{N$()});var WW=R(()=>{N$()});var OW=R(()=>{N$()});var UW=R(()=>{Q1()});var YW=R(()=>{Q1()});var HW=R(()=>{N$()});var LW=R(()=>{Q1();i5();d5();f4();l5();s5();a5();e5();$W();wW();EW();XW();GW();JW();AW();DW();NW();y4();WW();x4();OW();UW();g4();YW();HW()});var N$=R(()=>{v4();LW();Q1()});var bT=()=>{};var FW=R(()=>{N$();t5();Q1()});var ZT=R(()=>{FW();v4();t5();N$();bT();Q1();i5();d5();f4();l5();s5();a5();e5();$W();wW();EW();XW();GW();JW();AW();DW();NW();HW();y4();WW();x4();OW();UW();g4();YW();LW();FW()});function jW($){let E=j4($)?.method;if(!E)throw Error("Schema is missing a method literal");let X=hz(E);if(typeof X!=="string")throw Error("Schema method literal must be a string");return X}function MW($,w){let E=lw($,w);if(!E.success)throw E.error;return E.data}var CT=R(()=>{M4();ZT()});class RW{constructor($){if(this._options=$,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(K4,(w)=>{this._oncancel(w)}),this.setNotificationHandler(P4,(w)=>{this._onprogress(w)}),this.setRequestHandler(V4,(w)=>({})),this._taskStore=$?.taskStore,this._taskMessageQueue=$?.taskMessageQueue,this._taskStore)this.setRequestHandler(q4,async(w,E)=>{let X=await this._taskStore.getTask(w.params.taskId,E.sessionId);if(!X)throw new A0(L0.InvalidParams,"Failed to retrieve task: Task not found");return{...X}}),this.setRequestHandler(k4,async(w,E)=>{let X=async()=>{let G=w.params.taskId;if(this._taskMessageQueue){let A;while(A=await this._taskMessageQueue.dequeue(G,E.sessionId)){if(A.type==="response"||A.type==="error"){let D=A.message,N=D.id,W=this._requestResolvers.get(N);if(W)if(this._requestResolvers.delete(N),A.type==="response")W(D);else{let O=D,Y=new A0(O.error.code,O.error.message,O.error.data);W(Y)}else{let O=A.type==="response"?"Response":"Error";this._onerror(Error(`${O} handler missing for request ${N}`))}continue}await this._transport?.send(A.message,{relatedRequestId:E.requestId})}}let J=await this._taskStore.getTask(G,E.sessionId);if(!J)throw new A0(L0.InvalidParams,`Task not found: ${G}`);if(!aw(J.status))return await this._waitForTaskUpdate(G,E.signal),await X();if(aw(J.status)){let A=await this._taskStore.getTaskResult(G,E.sessionId);return this._clearTaskQueue(G),{...A,_meta:{...A._meta,[sw]:{taskId:G}}}}return await X()};return await X()}),this.setRequestHandler(b4,async(w,E)=>{try{let{tasks:X,nextCursor:G}=await this._taskStore.listTasks(w.params?.cursor,E.sessionId);return{tasks:X,nextCursor:G,_meta:{}}}catch(X){throw new A0(L0.InvalidParams,`Failed to list tasks: ${X instanceof Error?X.message:String(X)}`)}}),this.setRequestHandler(C4,async(w,E)=>{try{let X=await this._taskStore.getTask(w.params.taskId,E.sessionId);if(!X)throw new A0(L0.InvalidParams,`Task not found: ${w.params.taskId}`);if(aw(X.status))throw new A0(L0.InvalidParams,`Cannot cancel task in terminal status: ${X.status}`);await this._taskStore.updateTaskStatus(w.params.taskId,"cancelled","Client cancelled task execution.",E.sessionId),this._clearTaskQueue(w.params.taskId);let G=await this._taskStore.getTask(w.params.taskId,E.sessionId);if(!G)throw new A0(L0.InvalidParams,`Task not found after cancellation: ${w.params.taskId}`);return{_meta:{},...G}}catch(X){if(X instanceof A0)throw X;throw new A0(L0.InvalidRequest,`Failed to cancel task: ${X instanceof Error?X.message:String(X)}`)}})}async _oncancel($){if(!$.params.requestId)return;this._requestHandlerAbortControllers.get($.params.requestId)?.abort($.params.reason)}_setupTimeout($,w,E,X,G=!1){this._timeoutInfo.set($,{timeoutId:setTimeout(X,w),startTime:Date.now(),timeout:w,maxTotalTimeout:E,resetTimeoutOnProgress:G,onTimeout:X})}_resetTimeout($){let w=this._timeoutInfo.get($);if(!w)return!1;let E=Date.now()-w.startTime;if(w.maxTotalTimeout&&E>=w.maxTotalTimeout)throw this._timeoutInfo.delete($),A0.fromError(L0.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:w.maxTotalTimeout,totalElapsed:E});return clearTimeout(w.timeoutId),w.timeoutId=setTimeout(w.onTimeout,w.timeout),!0}_cleanupTimeout($){let w=this._timeoutInfo.get($);if(w)clearTimeout(w.timeoutId),this._timeoutInfo.delete($)}async connect($){if(this._transport)throw Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=$;let w=this.transport?.onclose;this._transport.onclose=()=>{w?.(),this._onclose()};let E=this.transport?.onerror;this._transport.onerror=(G)=>{E?.(G),this._onerror(G)};let X=this._transport?.onmessage;this._transport.onmessage=(G,J)=>{if(X?.(G,J),q6(G)||TT(G))this._onresponse(G);else if(C5(G))this._onrequest(G,J);else if(zT(G))this._onnotification(G);else this._onerror(Error(`Unknown message type: ${JSON.stringify(G)}`))},await this._transport.start()}_onclose(){let $=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let E of this._requestHandlerAbortControllers.values())E.abort();this._requestHandlerAbortControllers.clear();let w=A0.fromError(L0.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let E of $.values())E(w)}_onerror($){this.onerror?.($)}_onnotification($){let w=this._notificationHandlers.get($.method)??this.fallbackNotificationHandler;if(w===void 0)return;Promise.resolve().then(()=>w($)).catch((E)=>this._onerror(Error(`Uncaught error in notification handler: ${E}`)))}_onrequest($,w){let E=this._requestHandlers.get($.method)??this.fallbackRequestHandler,X=this._transport,G=$.params?._meta?.[sw]?.taskId;if(E===void 0){let W={jsonrpc:"2.0",id:$.id,error:{code:L0.MethodNotFound,message:"Method not found"}};if(G&&this._taskMessageQueue)this._enqueueTaskMessage(G,{type:"error",message:W,timestamp:Date.now()},X?.sessionId).catch((O)=>this._onerror(Error(`Failed to enqueue error response: ${O}`)));else X?.send(W).catch((O)=>this._onerror(Error(`Failed to send an error response: ${O}`)));return}let J=new AbortController;this._requestHandlerAbortControllers.set($.id,J);let A=jT($.params)?$.params.task:void 0,D=this._taskStore?this.requestTaskStore($,X?.sessionId):void 0,N={signal:J.signal,sessionId:X?.sessionId,_meta:$.params?._meta,sendNotification:async(W)=>{if(J.signal.aborted)return;let O={relatedRequestId:$.id};if(G)O.relatedTask={taskId:G};await this.notification(W,O)},sendRequest:async(W,O,Y)=>{if(J.signal.aborted)throw new A0(L0.ConnectionClosed,"Request was cancelled");let H={...Y,relatedRequestId:$.id};if(G&&!H.relatedTask)H.relatedTask={taskId:G};let L=H.relatedTask?.taskId??G;if(L&&D)await D.updateTaskStatus(L,"input_required");return await this.request(W,O,H)},authInfo:w?.authInfo,requestId:$.id,requestInfo:w?.requestInfo,taskId:G,taskStore:D,taskRequestedTtl:A?.ttl,closeSSEStream:w?.closeSSEStream,closeStandaloneSSEStream:w?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(A)this.assertTaskHandlerCapability($.method)}).then(()=>E($,N)).then(async(W)=>{if(J.signal.aborted)return;let O={result:W,jsonrpc:"2.0",id:$.id};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"response",message:O,timestamp:Date.now()},X?.sessionId);else await X?.send(O)},async(W)=>{if(J.signal.aborted)return;let O={jsonrpc:"2.0",id:$.id,error:{code:Number.isSafeInteger(W.code)?W.code:L0.InternalError,message:W.message??"Internal error",...W.data!==void 0&&{data:W.data}}};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"error",message:O,timestamp:Date.now()},X?.sessionId);else await X?.send(O)}).catch((W)=>this._onerror(Error(`Failed to send response: ${W}`))).finally(()=>{this._requestHandlerAbortControllers.delete($.id)})}_onprogress($){let{progressToken:w,...E}=$.params,X=Number(w),G=this._progressHandlers.get(X);if(!G){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify($)}`));return}let J=this._responseHandlers.get(X),A=this._timeoutInfo.get(X);if(A&&J&&A.resetTimeoutOnProgress)try{this._resetTimeout(X)}catch(D){this._responseHandlers.delete(X),this._progressHandlers.delete(X),this._cleanupTimeout(X),J(D);return}G(E)}_onresponse($){let w=Number($.id),E=this._requestResolvers.get(w);if(E){if(this._requestResolvers.delete(w),q6($))E($);else{let J=new A0($.error.code,$.error.message,$.error.data);E(J)}return}let X=this._responseHandlers.get(w);if(X===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify($)}`));return}this._responseHandlers.delete(w),this._cleanupTimeout(w);let G=!1;if(q6($)&&$.result&&typeof $.result==="object"){let J=$.result;if(J.task&&typeof J.task==="object"){let A=J.task;if(typeof A.taskId==="string")G=!0,this._taskProgressTokens.set(A.taskId,w)}}if(!G)this._progressHandlers.delete(w);if(q6($))X($);else{let J=A0.fromError($.error.code,$.error.message,$.error.data);X(J)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream($,w,E){let{task:X}=E??{};if(!X){try{yield{type:"result",result:await this.request($,w,E)}}catch(J){yield{type:"error",error:J instanceof A0?J:new A0(L0.InternalError,String(J))}}return}let G;try{let J=await this.request($,gX,E);if(J.task)G=J.task.taskId,yield{type:"taskCreated",task:J.task};else throw new A0(L0.InternalError,"Task creation did not return a task");while(!0){let A=await this.getTask({taskId:G},E);if(yield{type:"taskStatus",task:A},aw(A.status)){if(A.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:G},w,E)};else if(A.status==="failed")yield{type:"error",error:new A0(L0.InternalError,`Task ${G} failed`)};else if(A.status==="cancelled")yield{type:"error",error:new A0(L0.InternalError,`Task ${G} was cancelled`)};return}if(A.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:G},w,E)};return}let D=A.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((N)=>setTimeout(N,D)),E?.signal?.throwIfAborted()}}catch(J){yield{type:"error",error:J instanceof A0?J:new A0(L0.InternalError,String(J))}}}request($,w,E){let{relatedRequestId:X,resumptionToken:G,onresumptiontoken:J,task:A,relatedTask:D}=E??{};return new Promise((N,W)=>{let O=(z)=>{W(z)};if(!this._transport){O(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod($.method),A)this.assertTaskCapability($.method)}catch(z){O(z);return}E?.signal?.throwIfAborted();let Y=this._requestMessageId++,H={...$,jsonrpc:"2.0",id:Y};if(E?.onprogress)this._progressHandlers.set(Y,E.onprogress),H.params={...$.params,_meta:{...$.params?._meta||{},progressToken:Y}};if(A)H.params={...H.params,task:A};if(D)H.params={...H.params,_meta:{...H.params?._meta||{},[sw]:D}};let L=(z)=>{this._responseHandlers.delete(Y),this._progressHandlers.delete(Y),this._cleanupTimeout(Y),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:Y,reason:String(z)}},{relatedRequestId:X,resumptionToken:G,onresumptiontoken:J}).catch((Q)=>this._onerror(Error(`Failed to send cancellation: ${Q}`)));let B=z instanceof A0?z:new A0(L0.RequestTimeout,String(z));W(B)};this._responseHandlers.set(Y,(z)=>{if(E?.signal?.aborted)return;if(z instanceof Error)return W(z);try{let B=lw(w,z.result);if(!B.success)W(B.error);else N(B.data)}catch(B){W(B)}}),E?.signal?.addEventListener("abort",()=>{L(E?.signal?.reason)});let F=E?.timeout??yy,j=()=>L(A0.fromError(L0.RequestTimeout,"Request timed out",{timeout:F}));this._setupTimeout(Y,F,E?.maxTotalTimeout,j,E?.resetTimeoutOnProgress??!1);let M=D?.taskId;if(M){let z=(B)=>{let Q=this._responseHandlers.get(Y);if(Q)Q(B);else this._onerror(Error(`Response handler missing for side-channeled request ${Y}`))};this._requestResolvers.set(Y,z),this._enqueueTaskMessage(M,{type:"request",message:H,timestamp:Date.now()}).catch((B)=>{this._cleanupTimeout(Y),W(B)})}else this._transport.send(H,{relatedRequestId:X,resumptionToken:G,onresumptiontoken:J}).catch((z)=>{this._cleanupTimeout(Y),W(z)})})}async getTask($,w){return this.request({method:"tasks/get",params:$},S4,w)}async getTaskResult($,w,E){return this.request({method:"tasks/result",params:$},w,E)}async listTasks($,w){return this.request({method:"tasks/list",params:$},Z4,w)}async cancelTask($,w){return this.request({method:"tasks/cancel",params:$},IT,w)}async notification($,w){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability($.method);let E=w?.relatedTask?.taskId;if(E){let A={...$,jsonrpc:"2.0",params:{...$.params,_meta:{...$.params?._meta||{},[sw]:w.relatedTask}}};await this._enqueueTaskMessage(E,{type:"notification",message:A,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes($.method)&&!$.params&&!w?.relatedRequestId&&!w?.relatedTask){if(this._pendingDebouncedNotifications.has($.method))return;this._pendingDebouncedNotifications.add($.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete($.method),!this._transport)return;let A={...$,jsonrpc:"2.0"};if(w?.relatedTask)A={...A,params:{...A.params,_meta:{...A.params?._meta||{},[sw]:w.relatedTask}}};this._transport?.send(A,w).catch((D)=>this._onerror(D))});return}let J={...$,jsonrpc:"2.0"};if(w?.relatedTask)J={...J,params:{...J.params,_meta:{...J.params?._meta||{},[sw]:w.relatedTask}}};await this._transport.send(J,w)}setRequestHandler($,w){let E=jW($);this.assertRequestHandlerCapability(E),this._requestHandlers.set(E,(X,G)=>{let J=MW($,X);return Promise.resolve(w(J,G))})}removeRequestHandler($){this._requestHandlers.delete($)}assertCanSetRequestHandler($){if(this._requestHandlers.has($))throw Error(`A request handler for ${$} already exists, which would be overridden`)}setNotificationHandler($,w){let E=jW($);this._notificationHandlers.set(E,(X)=>{let G=MW($,X);return Promise.resolve(w(G))})}removeNotificationHandler($){this._notificationHandlers.delete($)}_cleanupTaskProgressHandler($){let w=this._taskProgressTokens.get($);if(w!==void 0)this._progressHandlers.delete(w),this._taskProgressTokens.delete($)}async _enqueueTaskMessage($,w,E){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let X=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue($,w,E,X)}async _clearTaskQueue($,w){if(this._taskMessageQueue){let E=await this._taskMessageQueue.dequeueAll($,w);for(let X of E)if(X.type==="request"&&C5(X.message)){let G=X.message.id,J=this._requestResolvers.get(G);if(J)J(new A0(L0.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(G);else this._onerror(Error(`Resolver missing for request ${G} during task ${$} cleanup`))}}}async _waitForTaskUpdate($,w){let E=this._options?.defaultTaskPollInterval??1000;try{let X=await this._taskStore?.getTask($);if(X?.pollInterval)E=X.pollInterval}catch{}return new Promise((X,G)=>{if(w.aborted){G(new A0(L0.InvalidRequest,"Request cancelled"));return}let J=setTimeout(X,E);w.addEventListener("abort",()=>{clearTimeout(J),G(new A0(L0.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore($,w){let E=this._taskStore;if(!E)throw Error("No task store configured");return{createTask:async(X)=>{if(!$)throw Error("No request provided");return await E.createTask(X,$.id,{method:$.method,params:$.params},w)},getTask:async(X)=>{let G=await E.getTask(X,w);if(!G)throw new A0(L0.InvalidParams,"Failed to retrieve task: Task not found");return G},storeTaskResult:async(X,G,J)=>{await E.storeTaskResult(X,G,J,w);let A=await E.getTask(X,w);if(A){let D=C6.parse({method:"notifications/tasks/status",params:A});if(await this.notification(D),aw(A.status))this._cleanupTaskProgressHandler(X)}},getTaskResult:(X)=>{return E.getTaskResult(X,w)},updateTaskStatus:async(X,G,J)=>{let A=await E.getTask(X,w);if(!A)throw new A0(L0.InvalidParams,`Task "${X}" not found - it may have been cleaned up`);if(aw(A.status))throw new A0(L0.InvalidParams,`Cannot update task "${X}" from terminal status "${A.status}" to "${G}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await E.updateTaskStatus(X,G,J,w);let D=await E.getTask(X,w);if(D){let N=C6.parse({method:"notifications/tasks/status",params:D});if(await this.notification(N),aw(D.status))this._cleanupTaskProgressHandler(X)}},listTasks:(X)=>{return E.listTasks(X,w)}}}}function _T($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function vT($,w){let E={...$};for(let X in w){let G=X,J=w[G];if(J===void 0)continue;let A=E[G];if(_T(A)&&_T(J))E[G]={...A,...J};else E[G]=J}return E}var yy=60000;var fT=R(()=>{M4();cX();CT()});var u6=Z((gT)=>{Object.defineProperty(gT,"__esModule",{value:!0});gT.regexpCode=gT.getEsmExportName=gT.getProperty=gT.safeStringify=gT.stringify=gT.strConcat=gT.addCodeArg=gT.str=gT._=gT.nil=gT._Code=gT.Name=gT.IDENTIFIER=gT._CodeOrName=void 0;class u4{}gT._CodeOrName=u4;gT.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class nX extends u4{constructor($){super();if(!gT.IDENTIFIER.test($))throw Error("CodeGen: name must be a valid identifier");this.str=$}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}gT.Name=nX;class h1 extends u4{constructor($){super();this._items=typeof $==="string"?[$]:$}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let $=this._items[0];return $===""||$==='""'}get str(){var $;return($=this._str)!==null&&$!==void 0?$:this._str=this._items.reduce((w,E)=>`${w}${E}`,"")}get names(){var $;return($=this._names)!==null&&$!==void 0?$:this._names=this._items.reduce((w,E)=>{if(E instanceof nX)w[E.str]=(w[E.str]||0)+1;return w},{})}}gT._Code=h1;gT.nil=new h1("");function xT($,...w){let E=[$[0]],X=0;while(X<w.length)TW(E,w[X]),E.push($[++X]);return new h1(E)}gT._=xT;var zW=new h1("+");function yT($,...w){let E=[g6($[0])],X=0;while(X<w.length)E.push(zW),TW(E,w[X]),E.push(zW,g6($[++X]));return gy(E),new h1(E)}gT.str=yT;function TW($,w){if(w instanceof h1)$.push(...w._items);else if(w instanceof nX)$.push(w);else $.push(cy(w))}gT.addCodeArg=TW;function gy($){let w=1;while(w<$.length-1){if($[w]===zW){let E=uy($[w-1],$[w+1]);if(E!==void 0){$.splice(w-1,3,E);continue}$[w++]="+"}w++}}function uy($,w){if(w==='""')return $;if($==='""')return w;if(typeof $=="string"){if(w instanceof nX||$[$.length-1]!=='"')return;if(typeof w!="string")return`${$.slice(0,-1)}${w}"`;if(w[0]==='"')return $.slice(0,-1)+w.slice(1);return}if(typeof w=="string"&&w[0]==='"'&&!($ instanceof nX))return`"${$}${w.slice(1)}`;return}function hy($,w){return w.emptyStr()?$:$.emptyStr()?w:yT`${$}${w}`}gT.strConcat=hy;function cy($){return typeof $=="number"||typeof $=="boolean"||$===null?$:g6(Array.isArray($)?$.join(","):$)}function ny($){return new h1(g6($))}gT.stringify=ny;function g6($){return JSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}gT.safeStringify=g6;function my($){return typeof $=="string"&&gT.IDENTIFIER.test($)?new h1(`.${$}`):xT`[${$}]`}gT.getProperty=my;function ry($){if(typeof $=="string"&&gT.IDENTIFIER.test($))return new h1(`${$}`);throw Error(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}gT.getEsmExportName=ry;function py($){return new h1($.toString())}gT.regexpCode=py});var KW=Z((nT)=>{Object.defineProperty(nT,"__esModule",{value:!0});nT.ValueScope=nT.ValueScopeName=nT.Scope=nT.varKinds=nT.UsedValueState=void 0;var e$=u6();class hT extends Error{constructor($){super(`CodeGen: "code" for ${$} not defined`);this.value=$.value}}var c4;(function($){$[$.Started=0]="Started",$[$.Completed=1]="Completed"})(c4||(nT.UsedValueState=c4={}));nT.varKinds={const:new e$.Name("const"),let:new e$.Name("let"),var:new e$.Name("var")};class QW{constructor({prefixes:$,parent:w}={}){this._names={},this._prefixes=$,this._parent=w}toName($){return $ instanceof e$.Name?$:this.name($)}name($){return new e$.Name(this._newName($))}_newName($){let w=this._names[$]||this._nameGroup($);return`${$}${w.index++}`}_nameGroup($){var w,E;if(((E=(w=this._parent)===null||w===void 0?void 0:w._prefixes)===null||E===void 0?void 0:E.has($))||this._prefixes&&!this._prefixes.has($))throw Error(`CodeGen: prefix "${$}" is not allowed in this scope`);return this._names[$]={prefix:$,index:0}}}nT.Scope=QW;class IW extends e$.Name{constructor($,w){super(w);this.prefix=$}setValue($,{property:w,itemIndex:E}){this.value=$,this.scopePath=e$._`.${new e$.Name(w)}[${E}]`}}nT.ValueScopeName=IW;var Gg=e$._`\n`;class cT extends QW{constructor($){super($);this._values={},this._scope=$.scope,this.opts={...$,_n:$.lines?Gg:e$.nil}}get(){return this._scope}name($){return new IW($,this._newName($))}value($,w){var E;if(w.ref===void 0)throw Error("CodeGen: ref must be passed in value");let X=this.toName($),{prefix:G}=X,J=(E=w.key)!==null&&E!==void 0?E:w.ref,A=this._values[G];if(A){let W=A.get(J);if(W)return W}else A=this._values[G]=new Map;A.set(J,X);let D=this._scope[G]||(this._scope[G]=[]),N=D.length;return D[N]=w.ref,X.setValue(w,{property:G,itemIndex:N}),X}getValue($,w){let E=this._values[$];if(!E)return;return E.get(w)}scopeRefs($,w=this._values){return this._reduceValues(w,(E)=>{if(E.scopePath===void 0)throw Error(`CodeGen: name "${E}" has no value`);return e$._`${$}${E.scopePath}`})}scopeCode($=this._values,w,E){return this._reduceValues($,(X)=>{if(X.value===void 0)throw Error(`CodeGen: name "${X}" has no value`);return X.value.code},w,E)}_reduceValues($,w,E={},X){let G=e$.nil;for(let J in $){let A=$[J];if(!A)continue;let D=E[J]=E[J]||new Map;A.forEach((N)=>{if(D.has(N))return;D.set(N,c4.Started);let W=w(N);if(W){let O=this.opts.es5?nT.varKinds.var:nT.varKinds.const;G=e$._`${G}${O} ${N} = ${W};${this.opts._n}`}else if(W=X===null||X===void 0?void 0:X(N))G=e$._`${G}${W}${this.opts._n}`;else throw new hT(N);D.set(N,c4.Completed)})}return G}}nT.ValueScope=cT});var W0=Z(($1)=>{Object.defineProperty($1,"__esModule",{value:!0});$1.or=$1.and=$1.not=$1.CodeGen=$1.operators=$1.varKinds=$1.ValueScopeName=$1.ValueScope=$1.Scope=$1.Name=$1.regexpCode=$1.stringify=$1.getProperty=$1.nil=$1.strConcat=$1.str=$1._=void 0;var M0=u6(),c1=KW(),ew=u6();Object.defineProperty($1,"_",{enumerable:!0,get:function(){return ew._}});Object.defineProperty($1,"str",{enumerable:!0,get:function(){return ew.str}});Object.defineProperty($1,"strConcat",{enumerable:!0,get:function(){return ew.strConcat}});Object.defineProperty($1,"nil",{enumerable:!0,get:function(){return ew.nil}});Object.defineProperty($1,"getProperty",{enumerable:!0,get:function(){return ew.getProperty}});Object.defineProperty($1,"stringify",{enumerable:!0,get:function(){return ew.stringify}});Object.defineProperty($1,"regexpCode",{enumerable:!0,get:function(){return ew.regexpCode}});Object.defineProperty($1,"Name",{enumerable:!0,get:function(){return ew.Name}});var t4=KW();Object.defineProperty($1,"Scope",{enumerable:!0,get:function(){return t4.Scope}});Object.defineProperty($1,"ValueScope",{enumerable:!0,get:function(){return t4.ValueScope}});Object.defineProperty($1,"ValueScopeName",{enumerable:!0,get:function(){return t4.ValueScopeName}});Object.defineProperty($1,"varKinds",{enumerable:!0,get:function(){return t4.varKinds}});$1.operators={GT:new M0._Code(">"),GTE:new M0._Code(">="),LT:new M0._Code("<"),LTE:new M0._Code("<="),EQ:new M0._Code("==="),NEQ:new M0._Code("!=="),NOT:new M0._Code("!"),OR:new M0._Code("||"),AND:new M0._Code("&&"),ADD:new M0._Code("+")};class $E{optimizeNodes(){return this}optimizeNames($,w){return this}}class rT extends $E{constructor($,w,E){super();this.varKind=$,this.name=w,this.rhs=E}render({es5:$,_n:w}){let E=$?c1.varKinds.var:this.varKind,X=this.rhs===void 0?"":` = ${this.rhs}`;return`${E} ${this.name}${X};`+w}optimizeNames($,w){if(!$[this.name.str])return;if(this.rhs)this.rhs=rX(this.rhs,$,w);return this}get names(){return this.rhs instanceof M0._CodeOrName?this.rhs.names:{}}}class qW extends $E{constructor($,w,E){super();this.lhs=$,this.rhs=w,this.sideEffects=E}render({_n:$}){return`${this.lhs} = ${this.rhs};`+$}optimizeNames($,w){if(this.lhs instanceof M0.Name&&!$[this.lhs.str]&&!this.sideEffects)return;return this.rhs=rX(this.rhs,$,w),this}get names(){let $=this.lhs instanceof M0.Name?{}:{...this.lhs.names};return o4($,this.rhs)}}class pT extends qW{constructor($,w,E,X){super($,E,X);this.op=w}render({_n:$}){return`${this.lhs} ${this.op}= ${this.rhs};`+$}}class oT extends $E{constructor($){super();this.label=$,this.names={}}render({_n:$}){return`${this.label}:`+$}}class tT extends $E{constructor($){super();this.label=$,this.names={}}render({_n:$}){return`break${this.label?` ${this.label}`:""};`+$}}class iT extends $E{constructor($){super();this.error=$}render({_n:$}){return`throw ${this.error};`+$}get names(){return this.error.names}}class dT extends $E{constructor($){super();this.code=$}render({_n:$}){return`${this.code};`+$}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames($,w){return this.code=rX(this.code,$,w),this}get names(){return this.code instanceof M0._CodeOrName?this.code.names:{}}}class i4 extends $E{constructor($=[]){super();this.nodes=$}render($){return this.nodes.reduce((w,E)=>w+E.render($),"")}optimizeNodes(){let{nodes:$}=this,w=$.length;while(w--){let E=$[w].optimizeNodes();if(Array.isArray(E))$.splice(w,1,...E);else if(E)$[w]=E;else $.splice(w,1)}return $.length>0?this:void 0}optimizeNames($,w){let{nodes:E}=this,X=E.length;while(X--){let G=E[X];if(G.optimizeNames($,w))continue;Ng($,G.names),E.splice(X,1)}return E.length>0?this:void 0}get names(){return this.nodes.reduce(($,w)=>kE($,w.names),{})}}class wE extends i4{render($){return"{"+$._n+super.render($)+"}"+$._n}}class lT extends i4{}class h6 extends wE{}h6.kind="else";class Pw extends wE{constructor($,w){super(w);this.condition=$}render($){let w=`if(${this.condition})`+super.render($);if(this.else)w+="else "+this.else.render($);return w}optimizeNodes(){super.optimizeNodes();let $=this.condition;if($===!0)return this.nodes;let w=this.else;if(w){let E=w.optimizeNodes();w=this.else=Array.isArray(E)?new h6(E):E}if(w){if($===!1)return w instanceof Pw?w:w.nodes;if(this.nodes.length)return this;return new Pw(wB($),w instanceof Pw?[w]:w.nodes)}if($===!1||!this.nodes.length)return;return this}optimizeNames($,w){var E;if(this.else=(E=this.else)===null||E===void 0?void 0:E.optimizeNames($,w),!(super.optimizeNames($,w)||this.else))return;return this.condition=rX(this.condition,$,w),this}get names(){let $=super.names;if(o4($,this.condition),this.else)kE($,this.else.names);return $}}Pw.kind="if";class mX extends wE{}mX.kind="for";class sT extends mX{constructor($){super();this.iteration=$}render($){return`for(${this.iteration})`+super.render($)}optimizeNames($,w){if(!super.optimizeNames($,w))return;return this.iteration=rX(this.iteration,$,w),this}get names(){return kE(super.names,this.iteration.names)}}class aT extends mX{constructor($,w,E,X){super();this.varKind=$,this.name=w,this.from=E,this.to=X}render($){let w=$.es5?c1.varKinds.var:this.varKind,{name:E,from:X,to:G}=this;return`for(${w} ${E}=${X}; ${E}<${G}; ${E}++)`+super.render($)}get names(){let $=o4(super.names,this.from);return o4($,this.to)}}class VW extends mX{constructor($,w,E,X){super();this.loop=$,this.varKind=w,this.name=E,this.iterable=X}render($){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render($)}optimizeNames($,w){if(!super.optimizeNames($,w))return;return this.iterable=rX(this.iterable,$,w),this}get names(){return kE(super.names,this.iterable.names)}}class n4 extends wE{constructor($,w,E){super();this.name=$,this.args=w,this.async=E}render($){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render($)}}n4.kind="func";class m4 extends i4{render($){return"return "+super.render($)}}m4.kind="return";class eT extends wE{render($){let w="try"+super.render($);if(this.catch)w+=this.catch.render($);if(this.finally)w+=this.finally.render($);return w}optimizeNodes(){var $,w;return super.optimizeNodes(),($=this.catch)===null||$===void 0||$.optimizeNodes(),(w=this.finally)===null||w===void 0||w.optimizeNodes(),this}optimizeNames($,w){var E,X;return super.optimizeNames($,w),(E=this.catch)===null||E===void 0||E.optimizeNames($,w),(X=this.finally)===null||X===void 0||X.optimizeNames($,w),this}get names(){let $=super.names;if(this.catch)kE($,this.catch.names);if(this.finally)kE($,this.finally.names);return $}}class r4 extends wE{constructor($){super();this.error=$}render($){return`catch(${this.error})`+super.render($)}}r4.kind="catch";class p4 extends wE{render($){return"finally"+super.render($)}}p4.kind="finally";class $B{constructor($,w={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...w,_n:w.lines?`
|
|
571
|
+
`:""},this._extScope=$,this._scope=new c1.Scope({parent:$}),this._nodes=[new lT]}toString(){return this._root.render(this.opts)}name($){return this._scope.name($)}scopeName($){return this._extScope.name($)}scopeValue($,w){let E=this._extScope.value($,w);return(this._values[E.prefix]||(this._values[E.prefix]=new Set)).add(E),E}getScopeValue($,w){return this._extScope.getValue($,w)}scopeRefs($){return this._extScope.scopeRefs($,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def($,w,E,X){let G=this._scope.toName(w);if(E!==void 0&&X)this._constants[G.str]=E;return this._leafNode(new rT($,G,E)),G}const($,w,E){return this._def(c1.varKinds.const,$,w,E)}let($,w,E){return this._def(c1.varKinds.let,$,w,E)}var($,w,E){return this._def(c1.varKinds.var,$,w,E)}assign($,w,E){return this._leafNode(new qW($,w,E))}add($,w){return this._leafNode(new pT($,$1.operators.ADD,w))}code($){if(typeof $=="function")$();else if($!==M0.nil)this._leafNode(new dT($));return this}object(...$){let w=["{"];for(let[E,X]of $){if(w.length>1)w.push(",");if(w.push(E),E!==X||this.opts.es5)w.push(":"),(0,M0.addCodeArg)(w,X)}return w.push("}"),new M0._Code(w)}if($,w,E){if(this._blockNode(new Pw($)),w&&E)this.code(w).else().code(E).endIf();else if(w)this.code(w).endIf();else if(E)throw Error('CodeGen: "else" body without "then" body');return this}elseIf($){return this._elseNode(new Pw($))}else(){return this._elseNode(new h6)}endIf(){return this._endBlockNode(Pw,h6)}_for($,w){if(this._blockNode($),w)this.code(w).endFor();return this}for($,w){return this._for(new sT($),w)}forRange($,w,E,X,G=this.opts.es5?c1.varKinds.var:c1.varKinds.let){let J=this._scope.toName($);return this._for(new aT(G,J,w,E),()=>X(J))}forOf($,w,E,X=c1.varKinds.const){let G=this._scope.toName($);if(this.opts.es5){let J=w instanceof M0.Name?w:this.var("_arr",w);return this.forRange("_i",0,M0._`${J}.length`,(A)=>{this.var(G,M0._`${J}[${A}]`),E(G)})}return this._for(new VW("of",X,G,w),()=>E(G))}forIn($,w,E,X=this.opts.es5?c1.varKinds.var:c1.varKinds.const){if(this.opts.ownProperties)return this.forOf($,M0._`Object.keys(${w})`,E);let G=this._scope.toName($);return this._for(new VW("in",X,G,w),()=>E(G))}endFor(){return this._endBlockNode(mX)}label($){return this._leafNode(new oT($))}break($){return this._leafNode(new tT($))}return($){let w=new m4;if(this._blockNode(w),this.code($),w.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(m4)}try($,w,E){if(!w&&!E)throw Error('CodeGen: "try" without "catch" and "finally"');let X=new eT;if(this._blockNode(X),this.code($),w){let G=this.name("e");this._currNode=X.catch=new r4(G),w(G)}if(E)this._currNode=X.finally=new p4,this.code(E);return this._endBlockNode(r4,p4)}throw($){return this._leafNode(new iT($))}block($,w){if(this._blockStarts.push(this._nodes.length),$)this.code($).endBlock(w);return this}endBlock($){let w=this._blockStarts.pop();if(w===void 0)throw Error("CodeGen: not in self-balancing block");let E=this._nodes.length-w;if(E<0||$!==void 0&&E!==$)throw Error(`CodeGen: wrong number of nodes: ${E} vs ${$} expected`);return this._nodes.length=w,this}func($,w=M0.nil,E,X){if(this._blockNode(new n4($,w,E)),X)this.code(X).endFunc();return this}endFunc(){return this._endBlockNode(n4)}optimize($=1){while($-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode($){return this._currNode.nodes.push($),this}_blockNode($){this._currNode.nodes.push($),this._nodes.push($)}_endBlockNode($,w){let E=this._currNode;if(E instanceof $||w&&E instanceof w)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${w?`${$.kind}/${w.kind}`:$.kind}"`)}_elseNode($){let w=this._currNode;if(!(w instanceof Pw))throw Error('CodeGen: "else" without "if"');return this._currNode=w.else=$,this}get _root(){return this._nodes[0]}get _currNode(){let $=this._nodes;return $[$.length-1]}set _currNode($){let w=this._nodes;w[w.length-1]=$}}$1.CodeGen=$B;function kE($,w){for(let E in w)$[E]=($[E]||0)+(w[E]||0);return $}function o4($,w){return w instanceof M0._CodeOrName?kE($,w.names):$}function rX($,w,E){if($ instanceof M0.Name)return X($);if(!G($))return $;return new M0._Code($._items.reduce((J,A)=>{if(A instanceof M0.Name)A=X(A);if(A instanceof M0._Code)J.push(...A._items);else J.push(A);return J},[]));function X(J){let A=E[J.str];if(A===void 0||w[J.str]!==1)return J;return delete w[J.str],A}function G(J){return J instanceof M0._Code&&J._items.some((A)=>A instanceof M0.Name&&w[A.str]===1&&E[A.str]!==void 0)}}function Ng($,w){for(let E in w)$[E]=($[E]||0)-(w[E]||0)}function wB($){return typeof $=="boolean"||typeof $=="number"||$===null?!$:M0._`!${PW($)}`}$1.not=wB;var Wg=EB($1.operators.AND);function Og(...$){return $.reduce(Wg)}$1.and=Og;var Ug=EB($1.operators.OR);function Yg(...$){return $.reduce(Ug)}$1.or=Yg;function EB($){return(w,E)=>w===M0.nil?E:E===M0.nil?w:M0._`${PW(w)} ${$} ${PW(E)}`}function PW($){return $ instanceof M0.Name?$:M0._`(${$})`}});var R0=Z((UB)=>{Object.defineProperty(UB,"__esModule",{value:!0});UB.checkStrictMode=UB.getErrorPath=UB.Type=UB.useFunc=UB.setEvaluated=UB.evaluatedPropsToName=UB.mergeEvaluated=UB.eachItem=UB.unescapeJsonPointer=UB.escapeJsonPointer=UB.escapeFragment=UB.unescapeFragment=UB.schemaRefOrVal=UB.schemaHasRulesButRef=UB.schemaHasRules=UB.checkUnknownRules=UB.alwaysValidSchema=UB.toHash=void 0;var b0=W0(),jg=u6();function Mg($){let w={};for(let E of $)w[E]=!0;return w}UB.toHash=Mg;function Rg($,w){if(typeof w=="boolean")return w;if(Object.keys(w).length===0)return!0;return AB($,w),!DB(w,$.self.RULES.all)}UB.alwaysValidSchema=Rg;function AB($,w=$.schema){let{opts:E,self:X}=$;if(!E.strictSchema)return;if(typeof w==="boolean")return;let G=X.RULES.keywords;for(let J in w)if(!G[J])OB($,`unknown keyword: "${J}"`)}UB.checkUnknownRules=AB;function DB($,w){if(typeof $=="boolean")return!$;for(let E in $)if(w[E])return!0;return!1}UB.schemaHasRules=DB;function zg($,w){if(typeof $=="boolean")return!$;for(let E in $)if(E!=="$ref"&&w.all[E])return!0;return!1}UB.schemaHasRulesButRef=zg;function Tg({topSchemaRef:$,schemaPath:w},E,X,G){if(!G){if(typeof E=="number"||typeof E=="boolean")return E;if(typeof E=="string")return b0._`${E}`}return b0._`${$}${w}${(0,b0.getProperty)(X)}`}UB.schemaRefOrVal=Tg;function Bg($){return NB(decodeURIComponent($))}UB.unescapeFragment=Bg;function Qg($){return encodeURIComponent(kW($))}UB.escapeFragment=Qg;function kW($){if(typeof $=="number")return`${$}`;return $.replace(/~/g,"~0").replace(/\//g,"~1")}UB.escapeJsonPointer=kW;function NB($){return $.replace(/~1/g,"/").replace(/~0/g,"~")}UB.unescapeJsonPointer=NB;function Ig($,w){if(Array.isArray($))for(let E of $)w(E);else w($)}UB.eachItem=Ig;function GB({mergeNames:$,mergeToName:w,mergeValues:E,resultToName:X}){return(G,J,A,D)=>{let N=A===void 0?J:A instanceof b0.Name?(J instanceof b0.Name?$(G,J,A):w(G,J,A),A):J instanceof b0.Name?(w(G,A,J),J):E(J,A);return D===b0.Name&&!(N instanceof b0.Name)?X(G,N):N}}UB.mergeEvaluated={props:GB({mergeNames:($,w,E)=>$.if(b0._`${E} !== true && ${w} !== undefined`,()=>{$.if(b0._`${w} === true`,()=>$.assign(E,!0),()=>$.assign(E,b0._`${E} || {}`).code(b0._`Object.assign(${E}, ${w})`))}),mergeToName:($,w,E)=>$.if(b0._`${E} !== true`,()=>{if(w===!0)$.assign(E,!0);else $.assign(E,b0._`${E} || {}`),bW($,E,w)}),mergeValues:($,w)=>$===!0?!0:{...$,...w},resultToName:WB}),items:GB({mergeNames:($,w,E)=>$.if(b0._`${E} !== true && ${w} !== undefined`,()=>$.assign(E,b0._`${w} === true ? true : ${E} > ${w} ? ${E} : ${w}`)),mergeToName:($,w,E)=>$.if(b0._`${E} !== true`,()=>$.assign(E,w===!0?!0:b0._`${E} > ${w} ? ${E} : ${w}`)),mergeValues:($,w)=>$===!0?!0:Math.max($,w),resultToName:($,w)=>$.var("items",w)})};function WB($,w){if(w===!0)return $.var("props",!0);let E=$.var("props",b0._`{}`);if(w!==void 0)bW($,E,w);return E}UB.evaluatedPropsToName=WB;function bW($,w,E){Object.keys(E).forEach((X)=>$.assign(b0._`${w}${(0,b0.getProperty)(X)}`,!0))}UB.setEvaluated=bW;var JB={};function Kg($,w){return $.scopeValue("func",{ref:w,code:JB[w.code]||(JB[w.code]=new jg._Code(w.code))})}UB.useFunc=Kg;var SW;(function($){$[$.Num=0]="Num",$[$.Str=1]="Str"})(SW||(UB.Type=SW={}));function Vg($,w,E){if($ instanceof b0.Name){let X=w===SW.Num;return E?X?b0._`"[" + ${$} + "]"`:b0._`"['" + ${$} + "']"`:X?b0._`"/" + ${$}`:b0._`"/" + ${$}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return E?(0,b0.getProperty)($).toString():"/"+kW($)}UB.getErrorPath=Vg;function OB($,w,E=$.opts.strictSchema){if(!E)return;if(w=`strict mode: ${w}`,E===!0)throw Error(w);$.self.logger.warn(w)}UB.checkStrictMode=OB});var qw=Z((HB)=>{Object.defineProperty(HB,"__esModule",{value:!0});var Z$=W0(),mg={data:new Z$.Name("data"),valCxt:new Z$.Name("valCxt"),instancePath:new Z$.Name("instancePath"),parentData:new Z$.Name("parentData"),parentDataProperty:new Z$.Name("parentDataProperty"),rootData:new Z$.Name("rootData"),dynamicAnchors:new Z$.Name("dynamicAnchors"),vErrors:new Z$.Name("vErrors"),errors:new Z$.Name("errors"),this:new Z$.Name("this"),self:new Z$.Name("self"),scope:new Z$.Name("scope"),json:new Z$.Name("json"),jsonPos:new Z$.Name("jsonPos"),jsonLen:new Z$.Name("jsonLen"),jsonPart:new Z$.Name("jsonPart")};HB.default=mg});var c6=Z((MB)=>{Object.defineProperty(MB,"__esModule",{value:!0});MB.extendErrors=MB.resetErrorsCount=MB.reportExtraError=MB.reportError=MB.keyword$DataError=MB.keywordError=void 0;var z0=W0(),l4=R0(),c$=qw();MB.keywordError={message:({keyword:$})=>z0.str`must pass "${$}" keyword validation`};MB.keyword$DataError={message:({keyword:$,schemaType:w})=>w?z0.str`"${$}" keyword must be ${w} ($data)`:z0.str`"${$}" keyword is invalid ($data)`};function pg($,w=MB.keywordError,E,X){let{it:G}=$,{gen:J,compositeRule:A,allErrors:D}=G,N=jB($,w,E);if(X!==null&&X!==void 0?X:A||D)LB(J,N);else FB(G,z0._`[${N}]`)}MB.reportError=pg;function og($,w=MB.keywordError,E){let{it:X}=$,{gen:G,compositeRule:J,allErrors:A}=X,D=jB($,w,E);if(LB(G,D),!(J||A))FB(X,c$.default.vErrors)}MB.reportExtraError=og;function tg($,w){$.assign(c$.default.errors,w),$.if(z0._`${c$.default.vErrors} !== null`,()=>$.if(w,()=>$.assign(z0._`${c$.default.vErrors}.length`,w),()=>$.assign(c$.default.vErrors,null)))}MB.resetErrorsCount=tg;function ig({gen:$,keyword:w,schemaValue:E,data:X,errsCount:G,it:J}){if(G===void 0)throw Error("ajv implementation error");let A=$.name("err");$.forRange("i",G,c$.default.errors,(D)=>{if($.const(A,z0._`${c$.default.vErrors}[${D}]`),$.if(z0._`${A}.instancePath === undefined`,()=>$.assign(z0._`${A}.instancePath`,(0,z0.strConcat)(c$.default.instancePath,J.errorPath))),$.assign(z0._`${A}.schemaPath`,z0.str`${J.errSchemaPath}/${w}`),J.opts.verbose)$.assign(z0._`${A}.schema`,E),$.assign(z0._`${A}.data`,X)})}MB.extendErrors=ig;function LB($,w){let E=$.const("err",w);$.if(z0._`${c$.default.vErrors} === null`,()=>$.assign(c$.default.vErrors,z0._`[${E}]`),z0._`${c$.default.vErrors}.push(${E})`),$.code(z0._`${c$.default.errors}++`)}function FB($,w){let{gen:E,validateName:X,schemaEnv:G}=$;if(G.$async)E.throw(z0._`new ${$.ValidationError}(${w})`);else E.assign(z0._`${X}.errors`,w),E.return(!1)}var bE={keyword:new z0.Name("keyword"),schemaPath:new z0.Name("schemaPath"),params:new z0.Name("params"),propertyName:new z0.Name("propertyName"),message:new z0.Name("message"),schema:new z0.Name("schema"),parentSchema:new z0.Name("parentSchema")};function jB($,w,E){let{createErrors:X}=$.it;if(X===!1)return z0._`{}`;return dg($,w,E)}function dg($,w,E={}){let{gen:X,it:G}=$,J=[lg(G,E),sg($,E)];return ag($,w,J),X.object(...J)}function lg({errorPath:$},{instancePath:w}){let E=w?z0.str`${$}${(0,l4.getErrorPath)(w,l4.Type.Str)}`:$;return[c$.default.instancePath,(0,z0.strConcat)(c$.default.instancePath,E)]}function sg({keyword:$,it:{errSchemaPath:w}},{schemaPath:E,parentSchema:X}){let G=X?w:z0.str`${w}/${$}`;if(E)G=z0.str`${G}${(0,l4.getErrorPath)(E,l4.Type.Str)}`;return[bE.schemaPath,G]}function ag($,{params:w,message:E},X){let{keyword:G,data:J,schemaValue:A,it:D}=$,{opts:N,propertyName:W,topSchemaRef:O,schemaPath:Y}=D;if(X.push([bE.keyword,G],[bE.params,typeof w=="function"?w($):w||z0._`{}`]),N.messages)X.push([bE.message,typeof E=="function"?E($):E]);if(N.verbose)X.push([bE.schema,A],[bE.parentSchema,z0._`${O}${Y}`],[c$.default.data,J]);if(W)X.push([bE.propertyName,W])}});var QB=Z((TB)=>{Object.defineProperty(TB,"__esModule",{value:!0});TB.boolOrEmptySchema=TB.topBoolOrEmptySchema=void 0;var Xu=c6(),Gu=W0(),Ju=qw(),Au={message:"boolean schema is false"};function Du($){let{gen:w,schema:E,validateName:X}=$;if(E===!1)zB($,!1);else if(typeof E=="object"&&E.$async===!0)w.return(Ju.default.data);else w.assign(Gu._`${X}.errors`,null),w.return(!0)}TB.topBoolOrEmptySchema=Du;function Nu($,w){let{gen:E,schema:X}=$;if(X===!1)E.var(w,!1),zB($);else E.var(w,!0)}TB.boolOrEmptySchema=Nu;function zB($,w){let{gen:E,data:X}=$,G={gen:E,keyword:"false schema",data:X,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:$};(0,Xu.reportError)(G,Au,void 0,w)}});var CW=Z((IB)=>{Object.defineProperty(IB,"__esModule",{value:!0});IB.getRules=IB.isJSONType=void 0;var Ou=["string","number","integer","boolean","null","object","array"],Uu=new Set(Ou);function Yu($){return typeof $=="string"&&Uu.has($)}IB.isJSONType=Yu;function Hu(){let $={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...$,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},$.number,$.string,$.array,$.object],post:{rules:[]},all:{},keywords:{}}}IB.getRules=Hu});var _W=Z((qB)=>{Object.defineProperty(qB,"__esModule",{value:!0});qB.shouldUseRule=qB.shouldUseGroup=qB.schemaHasRulesForType=void 0;function Fu({schema:$,self:w},E){let X=w.RULES.types[E];return X&&X!==!0&&VB($,X)}qB.schemaHasRulesForType=Fu;function VB($,w){return w.rules.some((E)=>PB($,E))}qB.shouldUseGroup=VB;function PB($,w){var E;return $[w.keyword]!==void 0||((E=w.definition.implements)===null||E===void 0?void 0:E.some((X)=>$[X]!==void 0))}qB.shouldUseRule=PB});var n6=Z((CB)=>{Object.defineProperty(CB,"__esModule",{value:!0});CB.reportTypeError=CB.checkDataTypes=CB.checkDataType=CB.coerceAndCheckDataType=CB.getJSONTypes=CB.getSchemaTypes=CB.DataType=void 0;var Ru=CW(),zu=_W(),Tu=c6(),D0=W0(),kB=R0(),pX;(function($){$[$.Correct=0]="Correct",$[$.Wrong=1]="Wrong"})(pX||(CB.DataType=pX={}));function Bu($){let w=bB($.type);if(w.includes("null")){if($.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!w.length&&$.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if($.nullable===!0)w.push("null")}return w}CB.getSchemaTypes=Bu;function bB($){let w=Array.isArray($)?$:$?[$]:[];if(w.every(Ru.isJSONType))return w;throw Error("type must be JSONType or JSONType[]: "+w.join(","))}CB.getJSONTypes=bB;function Qu($,w){let{gen:E,data:X,opts:G}=$,J=Iu(w,G.coerceTypes),A=w.length>0&&!(J.length===0&&w.length===1&&(0,zu.schemaHasRulesForType)($,w[0]));if(A){let D=fW(w,X,G.strictNumbers,pX.Wrong);E.if(D,()=>{if(J.length)Ku($,w,J);else xW($)})}return A}CB.coerceAndCheckDataType=Qu;var ZB=new Set(["string","number","integer","boolean","null"]);function Iu($,w){return w?$.filter((E)=>ZB.has(E)||w==="array"&&E==="array"):[]}function Ku($,w,E){let{gen:X,data:G,opts:J}=$,A=X.let("dataType",D0._`typeof ${G}`),D=X.let("coerced",D0._`undefined`);if(J.coerceTypes==="array")X.if(D0._`${A} == 'object' && Array.isArray(${G}) && ${G}.length == 1`,()=>X.assign(G,D0._`${G}[0]`).assign(A,D0._`typeof ${G}`).if(fW(w,G,J.strictNumbers),()=>X.assign(D,G)));X.if(D0._`${D} !== undefined`);for(let W of E)if(ZB.has(W)||W==="array"&&J.coerceTypes==="array")N(W);X.else(),xW($),X.endIf(),X.if(D0._`${D} !== undefined`,()=>{X.assign(G,D),Vu($,D)});function N(W){switch(W){case"string":X.elseIf(D0._`${A} == "number" || ${A} == "boolean"`).assign(D,D0._`"" + ${G}`).elseIf(D0._`${G} === null`).assign(D,D0._`""`);return;case"number":X.elseIf(D0._`${A} == "boolean" || ${G} === null
|
|
572
572
|
|| (${A} == "string" && ${G} && ${G} == +${G})`).assign(D,D0._`+${G}`);return;case"integer":X.elseIf(D0._`${A} === "boolean" || ${G} === null
|
|
573
573
|
|| (${A} === "string" && ${G} && ${G} == +${G} && !(${G} % 1))`).assign(D,D0._`+${G}`);return;case"boolean":X.elseIf(D0._`${G} === "false" || ${G} === 0 || ${G} === null`).assign(D,!1).elseIf(D0._`${G} === "true" || ${G} === 1`).assign(D,!0);return;case"null":X.elseIf(D0._`${G} === "" || ${G} === 0 || ${G} === false`),X.assign(D,null);return;case"array":X.elseIf(D0._`${A} === "string" || ${A} === "number"
|
|
574
|
-
|| ${A} === "boolean" || ${G} === null`).assign(D,D0._`[${G}]`)}}}function Ru({gen:$,parentData:w,parentDataProperty:E},X){$.if(D0._`${w} !== undefined`,()=>$.assign(D0._`${w}[${E}]`,X))}function ZW($,w,E,X=rX.Correct){let G=X===rX.Correct?D0.operators.EQ:D0.operators.NEQ,J;switch($){case"null":return D0._`${w} ${G} null`;case"array":J=D0._`Array.isArray(${w})`;break;case"object":J=D0._`${w} && typeof ${w} == "object" && !Array.isArray(${w})`;break;case"integer":J=A(D0._`!(${w} % 1) && !isNaN(${w})`);break;case"number":J=A();break;default:return D0._`typeof ${w} ${G} ${$}`}return X===rX.Correct?J:(0,D0.not)(J);function A(D=D0.nil){return(0,D0.and)(D0._`typeof ${w} == "number"`,D,E?D0._`isFinite(${w})`:D0.nil)}}kB.checkDataType=ZW;function CW($,w,E,X){if($.length===1)return ZW($[0],w,E,X);let G,J=(0,PB.toHash)($);if(J.array&&J.object){let A=D0._`typeof ${w} != "object"`;G=J.null?A:D0._`!${w} || ${A}`,delete J.null,delete J.array,delete J.object}else G=D0.nil;if(J.number)delete J.integer;for(let A in J)G=(0,D0.and)(G,ZW(A,w,E,X));return G}kB.checkDataTypes=CW;var zu={message:({schema:$})=>`must be ${$}`,params:({schema:$,schemaValue:w})=>typeof $=="string"?D0._`{type: ${$}}`:D0._`{type: ${w}}`};function _W($){let w=Tu($);(0,Hu.reportError)(w,zu)}kB.reportTypeError=_W;function Tu($){let{gen:w,data:E,schema:X}=$,G=(0,PB.schemaRefOrVal)($,X,"type");return{gen:w,keyword:"type",data:E,schema:X.type,schemaCode:G,schemaValue:G,parentSchema:X,params:{},it:$}}});var vB=Z((CB)=>{Object.defineProperty(CB,"__esModule",{value:!0});CB.assignDefaults=void 0;var pX=W0(),qu=R0();function Su($,w){let{properties:E,items:X}=$.schema;if(w==="object"&&E)for(let G in E)ZB($,G,E[G].default);else if(w==="array"&&Array.isArray(X))X.forEach((G,J)=>ZB($,J,G.default))}CB.assignDefaults=Su;function ZB($,w,E){let{gen:X,compositeRule:G,data:J,opts:A}=$;if(E===void 0)return;let D=pX._`${J}${(0,pX.getProperty)(w)}`;if(G){(0,qu.checkStrictMode)($,`default is ignored for: ${D}`);return}let N=pX._`${D} === undefined`;if(A.useDefaults==="empty")N=pX._`${N} || ${D} === null || ${D} === ""`;X.if(N,pX._`${D} = ${(0,pX.stringify)(E)}`)}});var I1=Z((yB)=>{Object.defineProperty(yB,"__esModule",{value:!0});yB.validateUnion=yB.validateArray=yB.usePattern=yB.callValidateCode=yB.schemaProperties=yB.allSchemaProperties=yB.noPropertyInData=yB.propertyInData=yB.isOwnProperty=yB.hasPropFunc=yB.reportMissingProp=yB.checkMissingProp=yB.checkReportMissingProp=void 0;var h0=W0(),vW=R0(),EE=qw(),ku=R0();function bu($,w){let{gen:E,data:X,it:G}=$;E.if(xW(E,X,w,G.opts.ownProperties),()=>{$.setParams({missingProperty:h0._`${w}`},!0),$.error()})}yB.checkReportMissingProp=bu;function Zu({gen:$,data:w,it:{opts:E}},X,G){return(0,h0.or)(...X.map((J)=>(0,h0.and)(xW($,w,J,E.ownProperties),h0._`${G} = ${J}`)))}yB.checkMissingProp=Zu;function Cu($,w){$.setParams({missingProperty:w},!0),$.error()}yB.reportMissingProp=Cu;function fB($){return $.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:h0._`Object.prototype.hasOwnProperty`})}yB.hasPropFunc=fB;function fW($,w,E){return h0._`${fB($)}.call(${w}, ${E})`}yB.isOwnProperty=fW;function _u($,w,E,X){let G=h0._`${w}${(0,h0.getProperty)(E)} !== undefined`;return X?h0._`${G} && ${fW($,w,E)}`:G}yB.propertyInData=_u;function xW($,w,E,X){let G=h0._`${w}${(0,h0.getProperty)(E)} === undefined`;return X?(0,h0.or)(G,(0,h0.not)(fW($,w,E))):G}yB.noPropertyInData=xW;function xB($){return $?Object.keys($).filter((w)=>w!=="__proto__"):[]}yB.allSchemaProperties=xB;function vu($,w){return xB(w).filter((E)=>!(0,vW.alwaysValidSchema)($,w[E]))}yB.schemaProperties=vu;function fu({schemaCode:$,data:w,it:{gen:E,topSchemaRef:X,schemaPath:G,errorPath:J},it:A},D,N,W){let O=W?h0._`${$}, ${w}, ${X}${G}`:w,Y=[[EE.default.instancePath,(0,h0.strConcat)(EE.default.instancePath,J)],[EE.default.parentData,A.parentData],[EE.default.parentDataProperty,A.parentDataProperty],[EE.default.rootData,EE.default.rootData]];if(A.opts.dynamicRef)Y.push([EE.default.dynamicAnchors,EE.default.dynamicAnchors]);let H=h0._`${O}, ${E.object(...Y)}`;return N!==h0.nil?h0._`${D}.call(${N}, ${H})`:h0._`${D}(${H})`}yB.callValidateCode=fu;var xu=h0._`new RegExp`;function yu({gen:$,it:{opts:w}},E){let X=w.unicodeRegExp?"u":"",{regExp:G}=w.code,J=G(E,X);return $.scopeValue("pattern",{key:J.toString(),ref:J,code:h0._`${G.code==="new RegExp"?xu:(0,ku.useFunc)($,G)}(${E}, ${X})`})}yB.usePattern=yu;function gu($){let{gen:w,data:E,keyword:X,it:G}=$,J=w.name("valid");if(G.allErrors){let D=w.let("valid",!0);return A(()=>w.assign(D,!1)),D}return w.var(J,!0),A(()=>w.break()),J;function A(D){let N=w.const("len",h0._`${E}.length`);w.forRange("i",0,N,(W)=>{$.subschema({keyword:X,dataProp:W,dataPropType:vW.Type.Num},J),w.if((0,h0.not)(J),D)})}}yB.validateArray=gu;function uu($){let{gen:w,schema:E,keyword:X,it:G}=$;if(!Array.isArray(E))throw Error("ajv implementation error");if(E.some((N)=>(0,vW.alwaysValidSchema)(G,N))&&!G.opts.unevaluated)return;let A=w.let("valid",!1),D=w.name("_valid");w.block(()=>E.forEach((N,W)=>{let O=$.subschema({keyword:X,schemaProp:W,compositeRule:!0},D);if(w.assign(A,h0._`${A} || ${D}`),!$.mergeValidEvaluated(O,D))w.if((0,h0.not)(A))})),$.result(A,()=>$.reset(),()=>$.error(!0))}yB.validateUnion=uu});var mB=Z((cB)=>{Object.defineProperty(cB,"__esModule",{value:!0});cB.validateKeywordUsage=cB.validSchemaType=cB.funcKeywordCode=cB.macroKeywordCode=void 0;var n$=W0(),ZE=qw(),au=I1(),eu=h6();function $h($,w){let{gen:E,keyword:X,schema:G,parentSchema:J,it:A}=$,D=w.macro.call(A.self,G,J,A),N=hB(E,X,D);if(A.opts.validateSchema!==!1)A.self.validateSchema(D,!0);let W=E.name("valid");$.subschema({schema:D,schemaPath:n$.nil,errSchemaPath:`${A.errSchemaPath}/${X}`,topSchemaRef:N,compositeRule:!0},W),$.pass(W,()=>$.error(!0))}cB.macroKeywordCode=$h;function wh($,w){var E;let{gen:X,keyword:G,schema:J,parentSchema:A,$data:D,it:N}=$;Xh(N,w);let W=!D&&w.compile?w.compile.call(N.self,J,A,N):w.validate,O=hB(X,G,W),Y=X.let("valid");$.block$data(Y,H),$.ok((E=w.valid)!==null&&E!==void 0?E:Y);function H(){if(w.errors===!1){if(j(),w.modifying)uB($);M(()=>$.error())}else{let z=w.async?L():F();if(w.modifying)uB($);M(()=>Eh($,z))}}function L(){let z=X.let("ruleErrs",null);return X.try(()=>j(n$._`await `),(B)=>X.assign(Y,!1).if(n$._`${B} instanceof ${N.ValidationError}`,()=>X.assign(z,n$._`${B}.errors`),()=>X.throw(B))),z}function F(){let z=n$._`${O}.errors`;return X.assign(z,null),j(n$.nil),z}function j(z=w.async?n$._`await `:n$.nil){let B=N.opts.passContext?ZE.default.this:ZE.default.self,Q=!(("compile"in w)&&!D||w.schema===!1);X.assign(Y,n$._`${z}${(0,au.callValidateCode)($,O,B,Q)}`,w.modifying)}function M(z){var B;X.if((0,n$.not)((B=w.valid)!==null&&B!==void 0?B:Y),z)}}cB.funcKeywordCode=wh;function uB($){let{gen:w,data:E,it:X}=$;w.if(X.parentData,()=>w.assign(E,n$._`${X.parentData}[${X.parentDataProperty}]`))}function Eh($,w){let{gen:E}=$;E.if(n$._`Array.isArray(${w})`,()=>{E.assign(ZE.default.vErrors,n$._`${ZE.default.vErrors} === null ? ${w} : ${ZE.default.vErrors}.concat(${w})`).assign(ZE.default.errors,n$._`${ZE.default.vErrors}.length`),(0,eu.extendErrors)($)},()=>$.error())}function Xh({schemaEnv:$},w){if(w.async&&!$.$async)throw Error("async keyword in sync schema")}function hB($,w,E){if(E===void 0)throw Error(`keyword "${w}" failed to compile`);return $.scopeValue("keyword",typeof E=="function"?{ref:E}:{ref:E,code:(0,n$.stringify)(E)})}function Gh($,w,E=!1){return!w.length||w.some((X)=>X==="array"?Array.isArray($):X==="object"?$&&typeof $=="object"&&!Array.isArray($):typeof $==X||E&&typeof $>"u")}cB.validSchemaType=Gh;function Jh({schema:$,opts:w,self:E,errSchemaPath:X},G,J){if(Array.isArray(G.keyword)?!G.keyword.includes(J):G.keyword!==J)throw Error("ajv implementation error");let A=G.dependencies;if(A===null||A===void 0?void 0:A.some((D)=>!Object.prototype.hasOwnProperty.call($,D)))throw Error(`parent schema must have dependencies of ${J}: ${A.join(",")}`);if(G.validateSchema){if(!G.validateSchema($[J])){let N=`keyword "${J}" value is invalid at path "${X}": `+E.errorsText(G.validateSchema.errors);if(w.validateSchema==="log")E.logger.error(N);else throw Error(N)}}}cB.validateKeywordUsage=Jh});var tB=Z((pB)=>{Object.defineProperty(pB,"__esModule",{value:!0});pB.extendSubschemaMode=pB.extendSubschemaData=pB.getSubschema=void 0;var Aw=W0(),rB=R0();function Wh($,{keyword:w,schemaProp:E,schema:X,schemaPath:G,errSchemaPath:J,topSchemaRef:A}){if(w!==void 0&&X!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(w!==void 0){let D=$.schema[w];return E===void 0?{schema:D,schemaPath:Aw._`${$.schemaPath}${(0,Aw.getProperty)(w)}`,errSchemaPath:`${$.errSchemaPath}/${w}`}:{schema:D[E],schemaPath:Aw._`${$.schemaPath}${(0,Aw.getProperty)(w)}${(0,Aw.getProperty)(E)}`,errSchemaPath:`${$.errSchemaPath}/${w}/${(0,rB.escapeFragment)(E)}`}}if(X!==void 0){if(G===void 0||J===void 0||A===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:X,schemaPath:G,topSchemaRef:A,errSchemaPath:J}}throw Error('either "keyword" or "schema" must be passed')}pB.getSubschema=Wh;function Oh($,w,{dataProp:E,dataPropType:X,data:G,dataTypes:J,propertyName:A}){if(G!==void 0&&E!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:D}=w;if(E!==void 0){let{errorPath:W,dataPathArr:O,opts:Y}=w,H=D.let("data",Aw._`${w.data}${(0,Aw.getProperty)(E)}`,!0);N(H),$.errorPath=Aw.str`${W}${(0,rB.getErrorPath)(E,X,Y.jsPropertySyntax)}`,$.parentDataProperty=Aw._`${E}`,$.dataPathArr=[...O,$.parentDataProperty]}if(G!==void 0){let W=G instanceof Aw.Name?G:D.let("data",G,!0);if(N(W),A!==void 0)$.propertyName=A}if(J)$.dataTypes=J;function N(W){$.data=W,$.dataLevel=w.dataLevel+1,$.dataTypes=[],w.definedProperties=new Set,$.parentData=w.data,$.dataNames=[...w.dataNames,W]}}pB.extendSubschemaData=Oh;function Uh($,{jtdDiscriminator:w,jtdMetadata:E,compositeRule:X,createErrors:G,allErrors:J}){if(X!==void 0)$.compositeRule=X;if(G!==void 0)$.createErrors=G;if(J!==void 0)$.allErrors=J;$.jtdDiscriminator=w,$.jtdMetadata=E}pB.extendSubschemaMode=Uh});var yW=Z((_80,iB)=>{iB.exports=function $(w,E){if(w===E)return!0;if(w&&E&&typeof w=="object"&&typeof E=="object"){if(w.constructor!==E.constructor)return!1;var X,G,J;if(Array.isArray(w)){if(X=w.length,X!=E.length)return!1;for(G=X;G--!==0;)if(!$(w[G],E[G]))return!1;return!0}if(w.constructor===RegExp)return w.source===E.source&&w.flags===E.flags;if(w.valueOf!==Object.prototype.valueOf)return w.valueOf()===E.valueOf();if(w.toString!==Object.prototype.toString)return w.toString()===E.toString();if(J=Object.keys(w),X=J.length,X!==Object.keys(E).length)return!1;for(G=X;G--!==0;)if(!Object.prototype.hasOwnProperty.call(E,J[G]))return!1;for(G=X;G--!==0;){var A=J[G];if(!$(w[A],E[A]))return!1}return!0}return w!==w&&E!==E}});var lB=Z((v80,dB)=>{var XE=dB.exports=function($,w,E){if(typeof w=="function")E=w,w={};E=w.cb||E;var X=typeof E=="function"?E:E.pre||function(){},G=E.post||function(){};d4(w,X,G,$,"",$)};XE.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};XE.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};XE.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};XE.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function d4($,w,E,X,G,J,A,D,N,W){if(X&&typeof X=="object"&&!Array.isArray(X)){w(X,G,J,A,D,N,W);for(var O in X){var Y=X[O];if(Array.isArray(Y)){if(O in XE.arrayKeywords)for(var H=0;H<Y.length;H++)d4($,w,E,Y[H],G+"/"+O+"/"+H,J,G,O,X,H)}else if(O in XE.propsKeywords){if(Y&&typeof Y=="object")for(var L in Y)d4($,w,E,Y[L],G+"/"+O+"/"+Lh(L),J,G,O,X,L)}else if(O in XE.keywords||$.allKeys&&!(O in XE.skipKeywords))d4($,w,E,Y,G+"/"+O,J,G,O,X)}E(X,G,J,A,D,N,W)}}function Lh($){return $.replace(/~/g,"~0").replace(/\//g,"~1")}});var n6=Z(($Q)=>{Object.defineProperty($Q,"__esModule",{value:!0});$Q.getSchemaRefs=$Q.resolveUrl=$Q.normalizeId=$Q._getFullPath=$Q.getFullPath=$Q.inlineRef=void 0;var Fh=R0(),jh=yW(),Mh=lB(),Rh=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function zh($,w=!0){if(typeof $=="boolean")return!0;if(w===!0)return!gW($);if(!w)return!1;return sB($)<=w}$Q.inlineRef=zh;var Th=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function gW($){for(let w in $){if(Th.has(w))return!0;let E=$[w];if(Array.isArray(E)&&E.some(gW))return!0;if(typeof E=="object"&&gW(E))return!0}return!1}function sB($){let w=0;for(let E in $){if(E==="$ref")return 1/0;if(w++,Rh.has(E))continue;if(typeof $[E]=="object")(0,Fh.eachItem)($[E],(X)=>w+=sB(X));if(w===1/0)return 1/0}return w}function aB($,w="",E){if(E!==!1)w=oX(w);let X=$.parse(w);return eB($,X)}$Q.getFullPath=aB;function eB($,w){return $.serialize(w).split("#")[0]+"#"}$Q._getFullPath=eB;var Bh=/#\/?$/;function oX($){return $?$.replace(Bh,""):""}$Q.normalizeId=oX;function Qh($,w,E){return E=oX(E),$.resolve(w,E)}$Q.resolveUrl=Qh;var Ih=/^[a-z_][-a-z0-9._]*$/i;function Kh($,w){if(typeof $=="boolean")return{};let{schemaId:E,uriResolver:X}=this.opts,G=oX($[E]||w),J={"":G},A=aB(X,G,!1),D={},N=new Set;return Mh($,{allKeys:!0},(Y,H,L,F)=>{if(F===void 0)return;let j=A+H,M=J[F];if(typeof Y[E]=="string")M=z.call(this,Y[E]);B.call(this,Y.$anchor),B.call(this,Y.$dynamicAnchor),J[H]=M;function z(Q){let k=this.opts.uriResolver.resolve;if(Q=oX(M?k(M,Q):Q),N.has(Q))throw O(Q);N.add(Q);let v=this.refs[Q];if(typeof v=="string")v=this.refs[v];if(typeof v=="object")W(Y,v.schema,Q);else if(Q!==oX(j))if(Q[0]==="#")W(Y,D[Q],Q),D[Q]=Y;else this.refs[Q]=j;return Q}function B(Q){if(typeof Q=="string"){if(!Ih.test(Q))throw Error(`invalid anchor "${Q}"`);z.call(this,`#${Q}`)}}}),D;function W(Y,H,L){if(H!==void 0&&!jh(Y,H))throw O(L)}function O(Y){return Error(`reference "${Y}" resolves to more than one schema`)}}$Q.getSchemaRefs=Kh});var p6=Z((jQ)=>{Object.defineProperty(jQ,"__esModule",{value:!0});jQ.getData=jQ.KeywordCxt=jQ.validateFunctionCode=void 0;var AQ=zB(),EQ=c6(),hW=bW(),l4=c6(),bh=vB(),r6=mB(),uW=tB(),o=W0(),w0=qw(),Zh=n6(),Sw=R0(),m6=h6();function Ch($){if(WQ($)){if(OQ($),NQ($)){fh($);return}}DQ($,()=>(0,AQ.topBoolOrEmptySchema)($))}jQ.validateFunctionCode=Ch;function DQ({gen:$,validateName:w,schema:E,schemaEnv:X,opts:G},J){if(G.code.es5)$.func(w,o._`${w0.default.data}, ${w0.default.valCxt}`,X.$async,()=>{$.code(o._`"use strict"; ${XQ(E,G)}`),vh($,G),$.code(J)});else $.func(w,o._`${w0.default.data}, ${_h(G)}`,X.$async,()=>$.code(XQ(E,G)).code(J))}function _h($){return o._`{${w0.default.instancePath}="", ${w0.default.parentData}, ${w0.default.parentDataProperty}, ${w0.default.rootData}=${w0.default.data}${$.dynamicRef?o._`, ${w0.default.dynamicAnchors}={}`:o.nil}}={}`}function vh($,w){$.if(w0.default.valCxt,()=>{if($.var(w0.default.instancePath,o._`${w0.default.valCxt}.${w0.default.instancePath}`),$.var(w0.default.parentData,o._`${w0.default.valCxt}.${w0.default.parentData}`),$.var(w0.default.parentDataProperty,o._`${w0.default.valCxt}.${w0.default.parentDataProperty}`),$.var(w0.default.rootData,o._`${w0.default.valCxt}.${w0.default.rootData}`),w.dynamicRef)$.var(w0.default.dynamicAnchors,o._`${w0.default.valCxt}.${w0.default.dynamicAnchors}`)},()=>{if($.var(w0.default.instancePath,o._`""`),$.var(w0.default.parentData,o._`undefined`),$.var(w0.default.parentDataProperty,o._`undefined`),$.var(w0.default.rootData,w0.default.data),w.dynamicRef)$.var(w0.default.dynamicAnchors,o._`{}`)})}function fh($){let{schema:w,opts:E,gen:X}=$;DQ($,()=>{if(E.$comment&&w.$comment)YQ($);if(hh($),X.let(w0.default.vErrors,null),X.let(w0.default.errors,0),E.unevaluated)xh($);UQ($),mh($)});return}function xh($){let{gen:w,validateName:E}=$;$.evaluated=w.const("evaluated",o._`${E}.evaluated`),w.if(o._`${$.evaluated}.dynamicProps`,()=>w.assign(o._`${$.evaluated}.props`,o._`undefined`)),w.if(o._`${$.evaluated}.dynamicItems`,()=>w.assign(o._`${$.evaluated}.items`,o._`undefined`))}function XQ($,w){let E=typeof $=="object"&&$[w.schemaId];return E&&(w.code.source||w.code.process)?o._`/*# sourceURL=${E} */`:o.nil}function yh($,w){if(WQ($)){if(OQ($),NQ($)){gh($,w);return}}(0,AQ.boolOrEmptySchema)($,w)}function NQ({schema:$,self:w}){if(typeof $=="boolean")return!$;for(let E in $)if(w.RULES.all[E])return!0;return!1}function WQ($){return typeof $.schema!="boolean"}function gh($,w){let{schema:E,gen:X,opts:G}=$;if(G.$comment&&E.$comment)YQ($);ch($),nh($);let J=X.const("_errs",w0.default.errors);UQ($,J),X.var(w,o._`${J} === ${w0.default.errors}`)}function OQ($){(0,Sw.checkUnknownRules)($),uh($)}function UQ($,w){if($.opts.jtd)return GQ($,[],!1,w);let E=(0,EQ.getSchemaTypes)($.schema),X=(0,EQ.coerceAndCheckDataType)($,E);GQ($,E,!X,w)}function uh($){let{schema:w,errSchemaPath:E,opts:X,self:G}=$;if(w.$ref&&X.ignoreKeywordsWithRef&&(0,Sw.schemaHasRulesButRef)(w,G.RULES))G.logger.warn(`$ref: keywords ignored in schema at path "${E}"`)}function hh($){let{schema:w,opts:E}=$;if(w.default!==void 0&&E.useDefaults&&E.strictSchema)(0,Sw.checkStrictMode)($,"default is ignored in the schema root")}function ch($){let w=$.schema[$.opts.schemaId];if(w)$.baseId=(0,Zh.resolveUrl)($.opts.uriResolver,$.baseId,w)}function nh($){if($.schema.$async&&!$.schemaEnv.$async)throw Error("async schema in sync schema")}function YQ({gen:$,schemaEnv:w,schema:E,errSchemaPath:X,opts:G}){let J=E.$comment;if(G.$comment===!0)$.code(o._`${w0.default.self}.logger.log(${J})`);else if(typeof G.$comment=="function"){let A=o.str`${X}/$comment`,D=$.scopeValue("root",{ref:w.root});$.code(o._`${w0.default.self}.opts.$comment(${J}, ${A}, ${D}.schema)`)}}function mh($){let{gen:w,schemaEnv:E,validateName:X,ValidationError:G,opts:J}=$;if(E.$async)w.if(o._`${w0.default.errors} === 0`,()=>w.return(w0.default.data),()=>w.throw(o._`new ${G}(${w0.default.vErrors})`));else{if(w.assign(o._`${X}.errors`,w0.default.vErrors),J.unevaluated)rh($);w.return(o._`${w0.default.errors} === 0`)}}function rh({gen:$,evaluated:w,props:E,items:X}){if(E instanceof o.Name)$.assign(o._`${w}.props`,E);if(X instanceof o.Name)$.assign(o._`${w}.items`,X)}function GQ($,w,E,X){let{gen:G,schema:J,data:A,allErrors:D,opts:N,self:W}=$,{RULES:O}=W;if(J.$ref&&(N.ignoreKeywordsWithRef||!(0,Sw.schemaHasRulesButRef)(J,O))){G.block(()=>LQ($,"$ref",O.all.$ref.definition));return}if(!N.jtd)ph($,w);G.block(()=>{for(let H of O.rules)Y(H);Y(O.post)});function Y(H){if(!(0,hW.shouldUseGroup)(J,H))return;if(H.type){if(G.if((0,l4.checkDataType)(H.type,A,N.strictNumbers)),JQ($,H),w.length===1&&w[0]===H.type&&E)G.else(),(0,l4.reportTypeError)($);G.endIf()}else JQ($,H);if(!D)G.if(o._`${w0.default.errors} === ${X||0}`)}}function JQ($,w){let{gen:E,schema:X,opts:{useDefaults:G}}=$;if(G)(0,bh.assignDefaults)($,w.type);E.block(()=>{for(let J of w.rules)if((0,hW.shouldUseRule)(X,J))LQ($,J.keyword,J.definition,w.type)})}function ph($,w){if($.schemaEnv.meta||!$.opts.strictTypes)return;if(oh($,w),!$.opts.allowUnionTypes)th($,w);ih($,$.dataTypes)}function oh($,w){if(!w.length)return;if(!$.dataTypes.length){$.dataTypes=w;return}w.forEach((E)=>{if(!HQ($.dataTypes,E))cW($,`type "${E}" not allowed by context "${$.dataTypes.join(",")}"`)}),lh($,w)}function th($,w){if(w.length>1&&!(w.length===2&&w.includes("null")))cW($,"use allowUnionTypes to allow union type keyword")}function ih($,w){let E=$.self.RULES.all;for(let X in E){let G=E[X];if(typeof G=="object"&&(0,hW.shouldUseRule)($.schema,G)){let{type:J}=G.definition;if(J.length&&!J.some((A)=>dh(w,A)))cW($,`missing type "${J.join(",")}" for keyword "${X}"`)}}}function dh($,w){return $.includes(w)||w==="number"&&$.includes("integer")}function HQ($,w){return $.includes(w)||w==="integer"&&$.includes("number")}function lh($,w){let E=[];for(let X of $.dataTypes)if(HQ(w,X))E.push(X);else if(w.includes("integer")&&X==="number")E.push("integer");$.dataTypes=E}function cW($,w){let E=$.schemaEnv.baseId+$.errSchemaPath;w+=` at "${E}" (strictTypes)`,(0,Sw.checkStrictMode)($,w,$.opts.strictTypes)}class nW{constructor($,w,E){if((0,r6.validateKeywordUsage)($,w,E),this.gen=$.gen,this.allErrors=$.allErrors,this.keyword=E,this.data=$.data,this.schema=$.schema[E],this.$data=w.$data&&$.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Sw.schemaRefOrVal)($,this.schema,E,this.$data),this.schemaType=w.schemaType,this.parentSchema=$.schema,this.params={},this.it=$,this.def=w,this.$data)this.schemaCode=$.gen.const("vSchema",FQ(this.$data,$));else if(this.schemaCode=this.schemaValue,!(0,r6.validSchemaType)(this.schema,w.schemaType,w.allowUndefined))throw Error(`${E} value must be ${JSON.stringify(w.schemaType)}`);if("code"in w?w.trackErrors:w.errors!==!1)this.errsCount=$.gen.const("_errs",w0.default.errors)}result($,w,E){this.failResult((0,o.not)($),w,E)}failResult($,w,E){if(this.gen.if($),E)E();else this.error();if(w){if(this.gen.else(),w(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass($,w){this.failResult((0,o.not)($),void 0,w)}fail($){if($===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if($),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data($){if(!this.$data)return this.fail($);let{schemaCode:w}=this;this.fail(o._`${w} !== undefined && (${(0,o.or)(this.invalid$data(),$)})`)}error($,w,E){if(w){this.setParams(w),this._error($,E),this.setParams({});return}this._error($,E)}_error($,w){($?m6.reportExtraError:m6.reportError)(this,this.def.error,w)}$dataError(){(0,m6.reportError)(this,this.def.$dataError||m6.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,m6.resetErrorsCount)(this.gen,this.errsCount)}ok($){if(!this.allErrors)this.gen.if($)}setParams($,w){if(w)Object.assign(this.params,$);else this.params=$}block$data($,w,E=o.nil){this.gen.block(()=>{this.check$data($,E),w()})}check$data($=o.nil,w=o.nil){if(!this.$data)return;let{gen:E,schemaCode:X,schemaType:G,def:J}=this;if(E.if((0,o.or)(o._`${X} === undefined`,w)),$!==o.nil)E.assign($,!0);if(G.length||J.validateSchema){if(E.elseIf(this.invalid$data()),this.$dataError(),$!==o.nil)E.assign($,!1)}E.else()}invalid$data(){let{gen:$,schemaCode:w,schemaType:E,def:X,it:G}=this;return(0,o.or)(J(),A());function J(){if(E.length){if(!(w instanceof o.Name))throw Error("ajv implementation error");let D=Array.isArray(E)?E:[E];return o._`${(0,l4.checkDataTypes)(D,w,G.opts.strictNumbers,l4.DataType.Wrong)}`}return o.nil}function A(){if(X.validateSchema){let D=$.scopeValue("validate$data",{ref:X.validateSchema});return o._`!${D}(${w})`}return o.nil}}subschema($,w){let E=(0,uW.getSubschema)(this.it,$);(0,uW.extendSubschemaData)(E,this.it,$),(0,uW.extendSubschemaMode)(E,$);let X={...this.it,...E,items:void 0,props:void 0};return yh(X,w),X}mergeEvaluated($,w){let{it:E,gen:X}=this;if(!E.opts.unevaluated)return;if(E.props!==!0&&$.props!==void 0)E.props=Sw.mergeEvaluated.props(X,$.props,E.props,w);if(E.items!==!0&&$.items!==void 0)E.items=Sw.mergeEvaluated.items(X,$.items,E.items,w)}mergeValidEvaluated($,w){let{it:E,gen:X}=this;if(E.opts.unevaluated&&(E.props!==!0||E.items!==!0))return X.if(w,()=>this.mergeEvaluated($,o.Name)),!0}}jQ.KeywordCxt=nW;function LQ($,w,E,X){let G=new nW($,E,w);if("code"in E)E.code(G,X);else if(G.$data&&E.validate)(0,r6.funcKeywordCode)(G,E);else if("macro"in E)(0,r6.macroKeywordCode)(G,E);else if(E.compile||E.validate)(0,r6.funcKeywordCode)(G,E)}var sh=/^\/(?:[^~]|~0|~1)*$/,ah=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function FQ($,{dataLevel:w,dataNames:E,dataPathArr:X}){let G,J;if($==="")return w0.default.rootData;if($[0]==="/"){if(!sh.test($))throw Error(`Invalid JSON-pointer: ${$}`);G=$,J=w0.default.rootData}else{let W=ah.exec($);if(!W)throw Error(`Invalid JSON-pointer: ${$}`);let O=+W[1];if(G=W[2],G==="#"){if(O>=w)throw Error(N("property/index",O));return X[w-O]}if(O>w)throw Error(N("data",O));if(J=E[w-O],!G)return J}let A=J,D=G.split("/");for(let W of D)if(W)J=o._`${J}${(0,o.getProperty)((0,Sw.unescapeJsonPointer)(W))}`,A=o._`${A} && ${J}`;return A;function N(W,O){return`Cannot access ${W} ${O} levels up, current level is ${w}`}}jQ.getData=FQ});var s4=Z((zQ)=>{Object.defineProperty(zQ,"__esModule",{value:!0});class RQ extends Error{constructor($){super("validation failed");this.errors=$,this.ajv=this.validation=!0}}zQ.default=RQ});var o6=Z((BQ)=>{Object.defineProperty(BQ,"__esModule",{value:!0});var mW=n6();class TQ extends Error{constructor($,w,E,X){super(X||`can't resolve reference ${E} from id ${w}`);this.missingRef=(0,mW.resolveUrl)($,w,E),this.missingSchema=(0,mW.normalizeId)((0,mW.getFullPath)($,this.missingRef))}}BQ.default=TQ});var e4=Z((KQ)=>{Object.defineProperty(KQ,"__esModule",{value:!0});KQ.resolveSchema=KQ.getCompilingSchema=KQ.resolveRef=KQ.compileSchema=KQ.SchemaEnv=void 0;var n1=W0(),Xc=s4(),CE=qw(),m1=n6(),QQ=R0(),Gc=p6();class t6{constructor($){var w;this.refs={},this.dynamicAnchors={};let E;if(typeof $.schema=="object")E=$.schema;this.schema=$.schema,this.schemaId=$.schemaId,this.root=$.root||this,this.baseId=(w=$.baseId)!==null&&w!==void 0?w:(0,m1.normalizeId)(E===null||E===void 0?void 0:E[$.schemaId||"$id"]),this.schemaPath=$.schemaPath,this.localRefs=$.localRefs,this.meta=$.meta,this.$async=E===null||E===void 0?void 0:E.$async,this.refs={}}}KQ.SchemaEnv=t6;function pW($){let w=IQ.call(this,$);if(w)return w;let E=(0,m1.getFullPath)(this.opts.uriResolver,$.root.baseId),{es5:X,lines:G}=this.opts.code,{ownProperties:J}=this.opts,A=new n1.CodeGen(this.scope,{es5:X,lines:G,ownProperties:J}),D;if($.$async)D=A.scopeValue("Error",{ref:Xc.default,code:n1._`require("ajv/dist/runtime/validation_error").default`});let N=A.scopeName("validate");$.validateName=N;let W={gen:A,allErrors:this.opts.allErrors,data:CE.default.data,parentData:CE.default.parentData,parentDataProperty:CE.default.parentDataProperty,dataNames:[CE.default.data],dataPathArr:[n1.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:A.scopeValue("schema",this.opts.code.source===!0?{ref:$.schema,code:(0,n1.stringify)($.schema)}:{ref:$.schema}),validateName:N,ValidationError:D,schema:$.schema,schemaEnv:$,rootId:E,baseId:$.baseId||E,schemaPath:n1.nil,errSchemaPath:$.schemaPath||(this.opts.jtd?"":"#"),errorPath:n1._`""`,opts:this.opts,self:this},O;try{this._compilations.add($),(0,Gc.validateFunctionCode)(W),A.optimize(this.opts.code.optimize);let Y=A.toString();if(O=`${A.scopeRefs(CE.default.scope)}return ${Y}`,this.opts.code.process)O=this.opts.code.process(O,$);let L=Function(`${CE.default.self}`,`${CE.default.scope}`,O)(this,this.scope.get());if(this.scope.value(N,{ref:L}),L.errors=null,L.schema=$.schema,L.schemaEnv=$,$.$async)L.$async=!0;if(this.opts.code.source===!0)L.source={validateName:N,validateCode:Y,scopeValues:A._values};if(this.opts.unevaluated){let{props:F,items:j}=W;if(L.evaluated={props:F instanceof n1.Name?void 0:F,items:j instanceof n1.Name?void 0:j,dynamicProps:F instanceof n1.Name,dynamicItems:j instanceof n1.Name},L.source)L.source.evaluated=(0,n1.stringify)(L.evaluated)}return $.validate=L,$}catch(Y){if(delete $.validate,delete $.validateName,O)this.logger.error("Error compiling schema, function code:",O);throw Y}finally{this._compilations.delete($)}}KQ.compileSchema=pW;function Jc($,w,E){var X;E=(0,m1.resolveUrl)(this.opts.uriResolver,w,E);let G=$.refs[E];if(G)return G;let J=Nc.call(this,$,E);if(J===void 0){let A=(X=$.localRefs)===null||X===void 0?void 0:X[E],{schemaId:D}=this.opts;if(A)J=new t6({schema:A,schemaId:D,root:$,baseId:w})}if(J===void 0)return;return $.refs[E]=Ac.call(this,J)}KQ.resolveRef=Jc;function Ac($){if((0,m1.inlineRef)($.schema,this.opts.inlineRefs))return $.schema;return $.validate?$:pW.call(this,$)}function IQ($){for(let w of this._compilations)if(Dc(w,$))return w}KQ.getCompilingSchema=IQ;function Dc($,w){return $.schema===w.schema&&$.root===w.root&&$.baseId===w.baseId}function Nc($,w){let E;while(typeof(E=this.refs[w])=="string")w=E;return E||this.schemas[w]||a4.call(this,$,w)}function a4($,w){let E=this.opts.uriResolver.parse(w),X=(0,m1._getFullPath)(this.opts.uriResolver,E),G=(0,m1.getFullPath)(this.opts.uriResolver,$.baseId,void 0);if(Object.keys($.schema).length>0&&X===G)return rW.call(this,E,$);let J=(0,m1.normalizeId)(X),A=this.refs[J]||this.schemas[J];if(typeof A=="string"){let D=a4.call(this,$,A);if(typeof(D===null||D===void 0?void 0:D.schema)!=="object")return;return rW.call(this,E,D)}if(typeof(A===null||A===void 0?void 0:A.schema)!=="object")return;if(!A.validate)pW.call(this,A);if(J===(0,m1.normalizeId)(w)){let{schema:D}=A,{schemaId:N}=this.opts,W=D[N];if(W)G=(0,m1.resolveUrl)(this.opts.uriResolver,G,W);return new t6({schema:D,schemaId:N,root:$,baseId:G})}return rW.call(this,E,A)}KQ.resolveSchema=a4;var Wc=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function rW($,{baseId:w,schema:E,root:X}){var G;if(((G=$.fragment)===null||G===void 0?void 0:G[0])!=="/")return;for(let D of $.fragment.slice(1).split("/")){if(typeof E==="boolean")return;let N=E[(0,QQ.unescapeFragment)(D)];if(N===void 0)return;E=N;let W=typeof E==="object"&&E[this.opts.schemaId];if(!Wc.has(D)&&W)w=(0,m1.resolveUrl)(this.opts.uriResolver,w,W)}let J;if(typeof E!="boolean"&&E.$ref&&!(0,QQ.schemaHasRulesButRef)(E,this.RULES)){let D=(0,m1.resolveUrl)(this.opts.uriResolver,w,E.$ref);J=a4.call(this,X,D)}let{schemaId:A}=this.opts;if(J=J||new t6({schema:E,schemaId:A,root:X,baseId:w}),J.schema!==J.root.schema)return J;return}});var PQ=Z((h80,Lc)=>{Lc.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var tW=Z((c80,bQ)=>{var Fc=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),SQ=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function oW($){let w="",E=0,X=0;for(X=0;X<$.length;X++){if(E=$[X].charCodeAt(0),E===48)continue;if(!(E>=48&&E<=57||E>=65&&E<=70||E>=97&&E<=102))return"";w+=$[X];break}for(X+=1;X<$.length;X++){if(E=$[X].charCodeAt(0),!(E>=48&&E<=57||E>=65&&E<=70||E>=97&&E<=102))return"";w+=$[X]}return w}var jc=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function qQ($){return $.length=0,!0}function Mc($,w,E){if($.length){let X=oW($);if(X!=="")w.push(X);else return E.error=!0,!1;$.length=0}return!0}function Rc($){let w=0,E={error:!1,address:"",zone:""},X=[],G=[],J=!1,A=!1,D=Mc;for(let N=0;N<$.length;N++){let W=$[N];if(W==="["||W==="]")continue;if(W===":"){if(J===!0)A=!0;if(!D(G,X,E))break;if(++w>7){E.error=!0;break}if(N>0&&$[N-1]===":")J=!0;X.push(":");continue}else if(W==="%"){if(!D(G,X,E))break;D=qQ}else{G.push(W);continue}}if(G.length)if(D===qQ)E.zone=G.join("");else if(A)X.push(G.join(""));else X.push(oW(G));return E.address=X.join(""),E}function kQ($){if(zc($,":")<2)return{host:$,isIPV6:!1};let w=Rc($);if(!w.error){let{address:E,address:X}=w;if(w.zone)E+="%"+w.zone,X+="%25"+w.zone;return{host:E,isIPV6:!0,escapedHost:X}}else return{host:$,isIPV6:!1}}function zc($,w){let E=0;for(let X=0;X<$.length;X++)if($[X]===w)E++;return E}function Tc($){let w=$,E=[],X=-1,G=0;while(G=w.length){if(G===1)if(w===".")break;else if(w==="/"){E.push("/");break}else{E.push(w);break}else if(G===2){if(w[0]==="."){if(w[1]===".")break;else if(w[1]==="/"){w=w.slice(2);continue}}else if(w[0]==="/"){if(w[1]==="."||w[1]==="/"){E.push("/");break}}}else if(G===3){if(w==="/.."){if(E.length!==0)E.pop();E.push("/");break}}if(w[0]==="."){if(w[1]==="."){if(w[2]==="/"){w=w.slice(3);continue}}else if(w[1]==="/"){w=w.slice(2);continue}}else if(w[0]==="/"){if(w[1]==="."){if(w[2]==="/"){w=w.slice(2);continue}else if(w[2]==="."){if(w[3]==="/"){if(w=w.slice(3),E.length!==0)E.pop();continue}}}}if((X=w.indexOf("/",1))===-1){E.push(w);break}else E.push(w.slice(0,X)),w=w.slice(X)}return E.join("")}function Bc($,w){let E=w!==!0?escape:unescape;if($.scheme!==void 0)$.scheme=E($.scheme);if($.userinfo!==void 0)$.userinfo=E($.userinfo);if($.host!==void 0)$.host=E($.host);if($.path!==void 0)$.path=E($.path);if($.query!==void 0)$.query=E($.query);if($.fragment!==void 0)$.fragment=E($.fragment);return $}function Qc($){let w=[];if($.userinfo!==void 0)w.push($.userinfo),w.push("@");if($.host!==void 0){let E=unescape($.host);if(!SQ(E)){let X=kQ(E);if(X.isIPV6===!0)E=`[${X.escapedHost}]`;else E=$.host}w.push(E)}if(typeof $.port==="number"||typeof $.port==="string")w.push(":"),w.push(String($.port));return w.length?w.join(""):void 0}bQ.exports={nonSimpleDomain:jc,recomposeAuthority:Qc,normalizeComponentEncoding:Bc,removeDotSegments:Tc,isIPv4:SQ,isUUID:Fc,normalizeIPv6:kQ,stringArrayToHexStripped:oW}});var fQ=Z((n80,vQ)=>{var{isUUID:Ic}=tW(),Kc=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Vc=["http","https","ws","wss","urn","urn:uuid"];function Pc($){return Vc.indexOf($)!==-1}function iW($){if($.secure===!0)return!0;else if($.secure===!1)return!1;else if($.scheme)return $.scheme.length===3&&($.scheme[0]==="w"||$.scheme[0]==="W")&&($.scheme[1]==="s"||$.scheme[1]==="S")&&($.scheme[2]==="s"||$.scheme[2]==="S");else return!1}function ZQ($){if(!$.host)$.error=$.error||"HTTP URIs must have a host.";return $}function CQ($){let w=String($.scheme).toLowerCase()==="https";if($.port===(w?443:80)||$.port==="")$.port=void 0;if(!$.path)$.path="/";return $}function qc($){return $.secure=iW($),$.resourceName=($.path||"/")+($.query?"?"+$.query:""),$.path=void 0,$.query=void 0,$}function Sc($){if($.port===(iW($)?443:80)||$.port==="")$.port=void 0;if(typeof $.secure==="boolean")$.scheme=$.secure?"wss":"ws",$.secure=void 0;if($.resourceName){let[w,E]=$.resourceName.split("?");$.path=w&&w!=="/"?w:void 0,$.query=E,$.resourceName=void 0}return $.fragment=void 0,$}function kc($,w){if(!$.path)return $.error="URN can not be parsed",$;let E=$.path.match(Kc);if(E){let X=w.scheme||$.scheme||"urn";$.nid=E[1].toLowerCase(),$.nss=E[2];let G=`${X}:${w.nid||$.nid}`,J=dW(G);if($.path=void 0,J)$=J.parse($,w)}else $.error=$.error||"URN can not be parsed.";return $}function bc($,w){if($.nid===void 0)throw Error("URN without nid cannot be serialized");let E=w.scheme||$.scheme||"urn",X=$.nid.toLowerCase(),G=`${E}:${w.nid||X}`,J=dW(G);if(J)$=J.serialize($,w);let A=$,D=$.nss;return A.path=`${X||w.nid}:${D}`,w.skipEscape=!0,A}function Zc($,w){let E=$;if(E.uuid=E.nss,E.nss=void 0,!w.tolerant&&(!E.uuid||!Ic(E.uuid)))E.error=E.error||"UUID is not valid.";return E}function Cc($){let w=$;return w.nss=($.uuid||"").toLowerCase(),w}var _Q={scheme:"http",domainHost:!0,parse:ZQ,serialize:CQ},_c={scheme:"https",domainHost:_Q.domainHost,parse:ZQ,serialize:CQ},$D={scheme:"ws",domainHost:!0,parse:qc,serialize:Sc},vc={scheme:"wss",domainHost:$D.domainHost,parse:$D.parse,serialize:$D.serialize},fc={scheme:"urn",parse:kc,serialize:bc,skipNormalize:!0},xc={scheme:"urn:uuid",parse:Zc,serialize:Cc,skipNormalize:!0},wD={http:_Q,https:_c,ws:$D,wss:vc,urn:fc,"urn:uuid":xc};Object.setPrototypeOf(wD,null);function dW($){return $&&(wD[$]||wD[$.toLowerCase()])||void 0}vQ.exports={wsIsSecure:iW,SCHEMES:wD,isValidSchemeName:Pc,getSchemeHandler:dW}});var gQ=Z((m80,XD)=>{var{normalizeIPv6:yc,removeDotSegments:i6,recomposeAuthority:gc,normalizeComponentEncoding:ED,isIPv4:uc,nonSimpleDomain:hc}=tW(),{SCHEMES:cc,getSchemeHandler:xQ}=fQ();function nc($,w){if(typeof $==="string")$=Dw(kw($,w),w);else if(typeof $==="object")$=kw(Dw($,w),w);return $}function mc($,w,E){let X=E?Object.assign({scheme:"null"},E):{scheme:"null"},G=yQ(kw($,X),kw(w,X),X,!0);return X.skipEscape=!0,Dw(G,X)}function yQ($,w,E,X){let G={};if(!X)$=kw(Dw($,E),E),w=kw(Dw(w,E),E);if(E=E||{},!E.tolerant&&w.scheme)G.scheme=w.scheme,G.userinfo=w.userinfo,G.host=w.host,G.port=w.port,G.path=i6(w.path||""),G.query=w.query;else{if(w.userinfo!==void 0||w.host!==void 0||w.port!==void 0)G.userinfo=w.userinfo,G.host=w.host,G.port=w.port,G.path=i6(w.path||""),G.query=w.query;else{if(!w.path)if(G.path=$.path,w.query!==void 0)G.query=w.query;else G.query=$.query;else{if(w.path[0]==="/")G.path=i6(w.path);else{if(($.userinfo!==void 0||$.host!==void 0||$.port!==void 0)&&!$.path)G.path="/"+w.path;else if(!$.path)G.path=w.path;else G.path=$.path.slice(0,$.path.lastIndexOf("/")+1)+w.path;G.path=i6(G.path)}G.query=w.query}G.userinfo=$.userinfo,G.host=$.host,G.port=$.port}G.scheme=$.scheme}return G.fragment=w.fragment,G}function rc($,w,E){if(typeof $==="string")$=unescape($),$=Dw(ED(kw($,E),!0),{...E,skipEscape:!0});else if(typeof $==="object")$=Dw(ED($,!0),{...E,skipEscape:!0});if(typeof w==="string")w=unescape(w),w=Dw(ED(kw(w,E),!0),{...E,skipEscape:!0});else if(typeof w==="object")w=Dw(ED(w,!0),{...E,skipEscape:!0});return $.toLowerCase()===w.toLowerCase()}function Dw($,w){let E={host:$.host,scheme:$.scheme,userinfo:$.userinfo,port:$.port,path:$.path,query:$.query,nid:$.nid,nss:$.nss,uuid:$.uuid,fragment:$.fragment,reference:$.reference,resourceName:$.resourceName,secure:$.secure,error:""},X=Object.assign({},w),G=[],J=xQ(X.scheme||E.scheme);if(J&&J.serialize)J.serialize(E,X);if(E.path!==void 0)if(!X.skipEscape){if(E.path=escape(E.path),E.scheme!==void 0)E.path=E.path.split("%3A").join(":")}else E.path=unescape(E.path);if(X.reference!=="suffix"&&E.scheme)G.push(E.scheme,":");let A=gc(E);if(A!==void 0){if(X.reference!=="suffix")G.push("//");if(G.push(A),E.path&&E.path[0]!=="/")G.push("/")}if(E.path!==void 0){let D=E.path;if(!X.absolutePath&&(!J||!J.absolutePath))D=i6(D);if(A===void 0&&D[0]==="/"&&D[1]==="/")D="/%2F"+D.slice(2);G.push(D)}if(E.query!==void 0)G.push("?",E.query);if(E.fragment!==void 0)G.push("#",E.fragment);return G.join("")}var pc=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function kw($,w){let E=Object.assign({},w),X={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},G=!1;if(E.reference==="suffix")if(E.scheme)$=E.scheme+":"+$;else $="//"+$;let J=$.match(pc);if(J){if(X.scheme=J[1],X.userinfo=J[3],X.host=J[4],X.port=parseInt(J[5],10),X.path=J[6]||"",X.query=J[7],X.fragment=J[8],isNaN(X.port))X.port=J[5];if(X.host)if(uc(X.host)===!1){let N=yc(X.host);X.host=N.host.toLowerCase(),G=N.isIPV6}else G=!0;if(X.scheme===void 0&&X.userinfo===void 0&&X.host===void 0&&X.port===void 0&&X.query===void 0&&!X.path)X.reference="same-document";else if(X.scheme===void 0)X.reference="relative";else if(X.fragment===void 0)X.reference="absolute";else X.reference="uri";if(E.reference&&E.reference!=="suffix"&&E.reference!==X.reference)X.error=X.error||"URI is not a "+E.reference+" reference.";let A=xQ(E.scheme||X.scheme);if(!E.unicodeSupport&&(!A||!A.unicodeSupport)){if(X.host&&(E.domainHost||A&&A.domainHost)&&G===!1&&hc(X.host))try{X.host=URL.domainToASCII(X.host.toLowerCase())}catch(D){X.error=X.error||"Host's domain name can not be converted to ASCII: "+D}}if(!A||A&&!A.skipNormalize){if($.indexOf("%")!==-1){if(X.scheme!==void 0)X.scheme=unescape(X.scheme);if(X.host!==void 0)X.host=unescape(X.host)}if(X.path)X.path=escape(unescape(X.path));if(X.fragment)X.fragment=encodeURI(decodeURIComponent(X.fragment))}if(A&&A.parse)A.parse(X,E)}else X.error=X.error||"URI can not be parsed.";return X}var lW={SCHEMES:cc,normalize:nc,resolve:mc,resolveComponent:yQ,equal:rc,serialize:Dw,parse:kw};XD.exports=lW;XD.exports.default=lW;XD.exports.fastUri=lW});var cQ=Z((hQ)=>{Object.defineProperty(hQ,"__esModule",{value:!0});var uQ=gQ();uQ.code='require("ajv/dist/runtime/uri").default';hQ.default=uQ});var dQ=Z((bw)=>{Object.defineProperty(bw,"__esModule",{value:!0});bw.CodeGen=bw.Name=bw.nil=bw.stringify=bw.str=bw._=bw.KeywordCxt=void 0;var tc=p6();Object.defineProperty(bw,"KeywordCxt",{enumerable:!0,get:function(){return tc.KeywordCxt}});var tX=W0();Object.defineProperty(bw,"_",{enumerable:!0,get:function(){return tX._}});Object.defineProperty(bw,"str",{enumerable:!0,get:function(){return tX.str}});Object.defineProperty(bw,"stringify",{enumerable:!0,get:function(){return tX.stringify}});Object.defineProperty(bw,"nil",{enumerable:!0,get:function(){return tX.nil}});Object.defineProperty(bw,"Name",{enumerable:!0,get:function(){return tX.Name}});Object.defineProperty(bw,"CodeGen",{enumerable:!0,get:function(){return tX.CodeGen}});var ic=s4(),oQ=o6(),dc=kW(),d6=e4(),lc=W0(),l6=n6(),GD=c6(),aW=R0(),nQ=PQ(),sc=cQ(),tQ=($,w)=>new RegExp($,w);tQ.code="new RegExp";var ac=["removeAdditional","useDefaults","coerceTypes"],ec=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),$n={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},wn={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},mQ=200;function En($){var w,E,X,G,J,A,D,N,W,O,Y,H,L,F,j,M,z,B,Q,k,v,C,n,T0,f0;let c0=$.strict,d0=(w=$.code)===null||w===void 0?void 0:w.optimize,K0=d0===!0||d0===void 0?1:d0||0,U$=(X=(E=$.code)===null||E===void 0?void 0:E.regExp)!==null&&X!==void 0?X:tQ,O1=(G=$.uriResolver)!==null&&G!==void 0?G:sc.default;return{strictSchema:(A=(J=$.strictSchema)!==null&&J!==void 0?J:c0)!==null&&A!==void 0?A:!0,strictNumbers:(N=(D=$.strictNumbers)!==null&&D!==void 0?D:c0)!==null&&N!==void 0?N:!0,strictTypes:(O=(W=$.strictTypes)!==null&&W!==void 0?W:c0)!==null&&O!==void 0?O:"log",strictTuples:(H=(Y=$.strictTuples)!==null&&Y!==void 0?Y:c0)!==null&&H!==void 0?H:"log",strictRequired:(F=(L=$.strictRequired)!==null&&L!==void 0?L:c0)!==null&&F!==void 0?F:!1,code:$.code?{...$.code,optimize:K0,regExp:U$}:{optimize:K0,regExp:U$},loopRequired:(j=$.loopRequired)!==null&&j!==void 0?j:mQ,loopEnum:(M=$.loopEnum)!==null&&M!==void 0?M:mQ,meta:(z=$.meta)!==null&&z!==void 0?z:!0,messages:(B=$.messages)!==null&&B!==void 0?B:!0,inlineRefs:(Q=$.inlineRefs)!==null&&Q!==void 0?Q:!0,schemaId:(k=$.schemaId)!==null&&k!==void 0?k:"$id",addUsedSchema:(v=$.addUsedSchema)!==null&&v!==void 0?v:!0,validateSchema:(C=$.validateSchema)!==null&&C!==void 0?C:!0,validateFormats:(n=$.validateFormats)!==null&&n!==void 0?n:!0,unicodeRegExp:(T0=$.unicodeRegExp)!==null&&T0!==void 0?T0:!0,int32range:(f0=$.int32range)!==null&&f0!==void 0?f0:!0,uriResolver:O1}}class JD{constructor($={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,$=this.opts={...$,...En($)};let{es5:w,lines:E}=this.opts.code;this.scope=new lc.ValueScope({scope:{},prefixes:ec,es5:w,lines:E}),this.logger=Nn($.logger);let X=$.validateFormats;if($.validateFormats=!1,this.RULES=(0,dc.getRules)(),rQ.call(this,$n,$,"NOT SUPPORTED"),rQ.call(this,wn,$,"DEPRECATED","warn"),this._metaOpts=An.call(this),$.formats)Gn.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),$.keywords)Jn.call(this,$.keywords);if(typeof $.meta=="object")this.addMetaSchema($.meta);Xn.call(this),$.validateFormats=X}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:$,meta:w,schemaId:E}=this.opts,X=nQ;if(E==="id")X={...nQ},X.id=X.$id,delete X.$id;if(w&&$)this.addMetaSchema(X,X[E],!1)}defaultMeta(){let{meta:$,schemaId:w}=this.opts;return this.opts.defaultMeta=typeof $=="object"?$[w]||$:void 0}validate($,w){let E;if(typeof $=="string"){if(E=this.getSchema($),!E)throw Error(`no schema with key or ref "${$}"`)}else E=this.compile($);let X=E(w);if(!("$async"in E))this.errors=E.errors;return X}compile($,w){let E=this._addSchema($,w);return E.validate||this._compileSchemaEnv(E)}compileAsync($,w){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:E}=this.opts;return X.call(this,$,w);async function X(W,O){await G.call(this,W.$schema);let Y=this._addSchema(W,O);return Y.validate||J.call(this,Y)}async function G(W){if(W&&!this.getSchema(W))await X.call(this,{$ref:W},!0)}async function J(W){try{return this._compileSchemaEnv(W)}catch(O){if(!(O instanceof oQ.default))throw O;return A.call(this,O),await D.call(this,O.missingSchema),J.call(this,W)}}function A({missingSchema:W,missingRef:O}){if(this.refs[W])throw Error(`AnySchema ${W} is loaded but ${O} cannot be resolved`)}async function D(W){let O=await N.call(this,W);if(!this.refs[W])await G.call(this,O.$schema);if(!this.refs[W])this.addSchema(O,W,w)}async function N(W){let O=this._loading[W];if(O)return O;try{return await(this._loading[W]=E(W))}finally{delete this._loading[W]}}}addSchema($,w,E,X=this.opts.validateSchema){if(Array.isArray($)){for(let J of $)this.addSchema(J,void 0,E,X);return this}let G;if(typeof $==="object"){let{schemaId:J}=this.opts;if(G=$[J],G!==void 0&&typeof G!="string")throw Error(`schema ${J} must be string`)}return w=(0,l6.normalizeId)(w||G),this._checkUnique(w),this.schemas[w]=this._addSchema($,E,w,X,!0),this}addMetaSchema($,w,E=this.opts.validateSchema){return this.addSchema($,w,!0,E),this}validateSchema($,w){if(typeof $=="boolean")return!0;let E;if(E=$.$schema,E!==void 0&&typeof E!="string")throw Error("$schema must be a string");if(E=E||this.opts.defaultMeta||this.defaultMeta(),!E)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let X=this.validate(E,$);if(!X&&w){let G="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(G);else throw Error(G)}return X}getSchema($){let w;while(typeof(w=pQ.call(this,$))=="string")$=w;if(w===void 0){let{schemaId:E}=this.opts,X=new d6.SchemaEnv({schema:{},schemaId:E});if(w=d6.resolveSchema.call(this,X,$),!w)return;this.refs[$]=w}return w.validate||this._compileSchemaEnv(w)}removeSchema($){if($ instanceof RegExp)return this._removeAllSchemas(this.schemas,$),this._removeAllSchemas(this.refs,$),this;switch(typeof $){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let w=pQ.call(this,$);if(typeof w=="object")this._cache.delete(w.schema);return delete this.schemas[$],delete this.refs[$],this}case"object":{let w=$;this._cache.delete(w);let E=$[this.opts.schemaId];if(E)E=(0,l6.normalizeId)(E),delete this.schemas[E],delete this.refs[E];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary($){for(let w of $)this.addKeyword(w);return this}addKeyword($,w){let E;if(typeof $=="string"){if(E=$,typeof w=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),w.keyword=E}else if(typeof $=="object"&&w===void 0){if(w=$,E=w.keyword,Array.isArray(E)&&!E.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(On.call(this,E,w),!w)return(0,aW.eachItem)(E,(G)=>sW.call(this,G)),this;Yn.call(this,w);let X={...w,type:(0,GD.getJSONTypes)(w.type),schemaType:(0,GD.getJSONTypes)(w.schemaType)};return(0,aW.eachItem)(E,X.type.length===0?(G)=>sW.call(this,G,X):(G)=>X.type.forEach((J)=>sW.call(this,G,X,J))),this}getKeyword($){let w=this.RULES.all[$];return typeof w=="object"?w.definition:!!w}removeKeyword($){let{RULES:w}=this;delete w.keywords[$],delete w.all[$];for(let E of w.rules){let X=E.rules.findIndex((G)=>G.keyword===$);if(X>=0)E.rules.splice(X,1)}return this}addFormat($,w){if(typeof w=="string")w=new RegExp(w);return this.formats[$]=w,this}errorsText($=this.errors,{separator:w=", ",dataVar:E="data"}={}){if(!$||$.length===0)return"No errors";return $.map((X)=>`${E}${X.instancePath} ${X.message}`).reduce((X,G)=>X+w+G)}$dataMetaSchema($,w){let E=this.RULES.all;$=JSON.parse(JSON.stringify($));for(let X of w){let G=X.split("/").slice(1),J=$;for(let A of G)J=J[A];for(let A in E){let D=E[A];if(typeof D!="object")continue;let{$data:N}=D.definition,W=J[A];if(N&&W)J[A]=iQ(W)}}return $}_removeAllSchemas($,w){for(let E in $){let X=$[E];if(!w||w.test(E)){if(typeof X=="string")delete $[E];else if(X&&!X.meta)this._cache.delete(X.schema),delete $[E]}}}_addSchema($,w,E,X=this.opts.validateSchema,G=this.opts.addUsedSchema){let J,{schemaId:A}=this.opts;if(typeof $=="object")J=$[A];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof $!="boolean")throw Error("schema must be object or boolean");let D=this._cache.get($);if(D!==void 0)return D;E=(0,l6.normalizeId)(J||E);let N=l6.getSchemaRefs.call(this,$,E);if(D=new d6.SchemaEnv({schema:$,schemaId:A,meta:w,baseId:E,localRefs:N}),this._cache.set(D.schema,D),G&&!E.startsWith("#")){if(E)this._checkUnique(E);this.refs[E]=D}if(X)this.validateSchema($,!0);return D}_checkUnique($){if(this.schemas[$]||this.refs[$])throw Error(`schema with key or id "${$}" already exists`)}_compileSchemaEnv($){if($.meta)this._compileMetaSchema($);else d6.compileSchema.call(this,$);if(!$.validate)throw Error("ajv implementation error");return $.validate}_compileMetaSchema($){let w=this.opts;this.opts=this._metaOpts;try{d6.compileSchema.call(this,$)}finally{this.opts=w}}}JD.ValidationError=ic.default;JD.MissingRefError=oQ.default;bw.default=JD;function rQ($,w,E,X="error"){for(let G in $){let J=G;if(J in w)this.logger[X](`${E}: option ${G}. ${$[J]}`)}}function pQ($){return $=(0,l6.normalizeId)($),this.schemas[$]||this.refs[$]}function Xn(){let $=this.opts.schemas;if(!$)return;if(Array.isArray($))this.addSchema($);else for(let w in $)this.addSchema($[w],w)}function Gn(){for(let $ in this.opts.formats){let w=this.opts.formats[$];if(w)this.addFormat($,w)}}function Jn($){if(Array.isArray($)){this.addVocabulary($);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let w in $){let E=$[w];if(!E.keyword)E.keyword=w;this.addKeyword(E)}}function An(){let $={...this.opts};for(let w of ac)delete $[w];return $}var Dn={log(){},warn(){},error(){}};function Nn($){if($===!1)return Dn;if($===void 0)return console;if($.log&&$.warn&&$.error)return $;throw Error("logger must implement log, warn and error methods")}var Wn=/^[a-z_$][a-z0-9_$:-]*$/i;function On($,w){let{RULES:E}=this;if((0,aW.eachItem)($,(X)=>{if(E.keywords[X])throw Error(`Keyword ${X} is already defined`);if(!Wn.test(X))throw Error(`Keyword ${X} has invalid name`)}),!w)return;if(w.$data&&!(("code"in w)||("validate"in w)))throw Error('$data keyword must have "code" or "validate" function')}function sW($,w,E){var X;let G=w===null||w===void 0?void 0:w.post;if(E&&G)throw Error('keyword with "post" flag cannot have "type"');let{RULES:J}=this,A=G?J.post:J.rules.find(({type:N})=>N===E);if(!A)A={type:E,rules:[]},J.rules.push(A);if(J.keywords[$]=!0,!w)return;let D={keyword:$,definition:{...w,type:(0,GD.getJSONTypes)(w.type),schemaType:(0,GD.getJSONTypes)(w.schemaType)}};if(w.before)Un.call(this,A,D,w.before);else A.rules.push(D);J.all[$]=D,(X=w.implements)===null||X===void 0||X.forEach((N)=>this.addKeyword(N))}function Un($,w,E){let X=$.rules.findIndex((G)=>G.keyword===E);if(X>=0)$.rules.splice(X,0,w);else $.rules.push(w),this.logger.warn(`rule ${E} is not defined`)}function Yn($){let{metaSchema:w}=$;if(w===void 0)return;if($.$data&&this.opts.$data)w=iQ(w);$.validateSchema=this.compile(w,!0)}var Hn={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function iQ($){return{anyOf:[$,Hn]}}});var sQ=Z((lQ)=>{Object.defineProperty(lQ,"__esModule",{value:!0});var jn={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};lQ.default=jn});var XI=Z((wI)=>{Object.defineProperty(wI,"__esModule",{value:!0});wI.callRef=wI.getValidate=void 0;var Rn=o6(),aQ=I1(),w1=W0(),iX=qw(),eQ=e4(),AD=R0(),zn={keyword:"$ref",schemaType:"string",code($){let{gen:w,schema:E,it:X}=$,{baseId:G,schemaEnv:J,validateName:A,opts:D,self:N}=X,{root:W}=J;if((E==="#"||E==="#/")&&G===W.baseId)return Y();let O=eQ.resolveRef.call(N,W,G,E);if(O===void 0)throw new Rn.default(X.opts.uriResolver,G,E);if(O instanceof eQ.SchemaEnv)return H(O);return L(O);function Y(){if(J===W)return DD($,A,J,J.$async);let F=w.scopeValue("root",{ref:W});return DD($,w1._`${F}.validate`,W,W.$async)}function H(F){let j=$I($,F);DD($,j,F,F.$async)}function L(F){let j=w.scopeValue("schema",D.code.source===!0?{ref:F,code:(0,w1.stringify)(F)}:{ref:F}),M=w.name("valid"),z=$.subschema({schema:F,dataTypes:[],schemaPath:w1.nil,topSchemaRef:j,errSchemaPath:E},M);$.mergeEvaluated(z),$.ok(M)}}};function $I($,w){let{gen:E}=$;return w.validate?E.scopeValue("validate",{ref:w.validate}):w1._`${E.scopeValue("wrapper",{ref:w})}.validate`}wI.getValidate=$I;function DD($,w,E,X){let{gen:G,it:J}=$,{allErrors:A,schemaEnv:D,opts:N}=J,W=N.passContext?iX.default.this:w1.nil;if(X)O();else Y();function O(){if(!D.$async)throw Error("async schema referenced by sync schema");let F=G.let("valid");G.try(()=>{if(G.code(w1._`await ${(0,aQ.callValidateCode)($,w,W)}`),L(w),!A)G.assign(F,!0)},(j)=>{if(G.if(w1._`!(${j} instanceof ${J.ValidationError})`,()=>G.throw(j)),H(j),!A)G.assign(F,!1)}),$.ok(F)}function Y(){$.result((0,aQ.callValidateCode)($,w,W),()=>L(w),()=>H(w))}function H(F){let j=w1._`${F}.errors`;G.assign(iX.default.vErrors,w1._`${iX.default.vErrors} === null ? ${j} : ${iX.default.vErrors}.concat(${j})`),G.assign(iX.default.errors,w1._`${iX.default.vErrors}.length`)}function L(F){var j;if(!J.opts.unevaluated)return;let M=(j=E===null||E===void 0?void 0:E.validate)===null||j===void 0?void 0:j.evaluated;if(J.props!==!0)if(M&&!M.dynamicProps){if(M.props!==void 0)J.props=AD.mergeEvaluated.props(G,M.props,J.props)}else{let z=G.var("props",w1._`${F}.evaluated.props`);J.props=AD.mergeEvaluated.props(G,z,J.props,w1.Name)}if(J.items!==!0)if(M&&!M.dynamicItems){if(M.items!==void 0)J.items=AD.mergeEvaluated.items(G,M.items,J.items)}else{let z=G.var("items",w1._`${F}.evaluated.items`);J.items=AD.mergeEvaluated.items(G,z,J.items,w1.Name)}}}wI.callRef=DD;wI.default=zn});var JI=Z((GI)=>{Object.defineProperty(GI,"__esModule",{value:!0});var Qn=sQ(),In=XI(),Kn=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Qn.default,In.default];GI.default=Kn});var DI=Z((AI)=>{Object.defineProperty(AI,"__esModule",{value:!0});var ND=W0(),GE=ND.operators,WD={maximum:{okStr:"<=",ok:GE.LTE,fail:GE.GT},minimum:{okStr:">=",ok:GE.GTE,fail:GE.LT},exclusiveMaximum:{okStr:"<",ok:GE.LT,fail:GE.GTE},exclusiveMinimum:{okStr:">",ok:GE.GT,fail:GE.LTE}},Pn={message:({keyword:$,schemaCode:w})=>ND.str`must be ${WD[$].okStr} ${w}`,params:({keyword:$,schemaCode:w})=>ND._`{comparison: ${WD[$].okStr}, limit: ${w}}`},qn={keyword:Object.keys(WD),type:"number",schemaType:"number",$data:!0,error:Pn,code($){let{keyword:w,data:E,schemaCode:X}=$;$.fail$data(ND._`${E} ${WD[w].fail} ${X} || isNaN(${E})`)}};AI.default=qn});var WI=Z((NI)=>{Object.defineProperty(NI,"__esModule",{value:!0});var s6=W0(),kn={message:({schemaCode:$})=>s6.str`must be multiple of ${$}`,params:({schemaCode:$})=>s6._`{multipleOf: ${$}}`},bn={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:kn,code($){let{gen:w,data:E,schemaCode:X,it:G}=$,J=G.opts.multipleOfPrecision,A=w.let("res"),D=J?s6._`Math.abs(Math.round(${A}) - ${A}) > 1e-${J}`:s6._`${A} !== parseInt(${A})`;$.fail$data(s6._`(${X} === 0 || (${A} = ${E}/${X}, ${D}))`)}};NI.default=bn});var YI=Z((UI)=>{Object.defineProperty(UI,"__esModule",{value:!0});function OI($){let w=$.length,E=0,X=0,G;while(X<w)if(E++,G=$.charCodeAt(X++),G>=55296&&G<=56319&&X<w){if(G=$.charCodeAt(X),(G&64512)===56320)X++}return E}UI.default=OI;OI.code='require("ajv/dist/runtime/ucs2length").default'});var LI=Z((HI)=>{Object.defineProperty(HI,"__esModule",{value:!0});var _E=W0(),_n=R0(),vn=YI(),fn={message({keyword:$,schemaCode:w}){let E=$==="maxLength"?"more":"fewer";return _E.str`must NOT have ${E} than ${w} characters`},params:({schemaCode:$})=>_E._`{limit: ${$}}`},xn={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:fn,code($){let{keyword:w,data:E,schemaCode:X,it:G}=$,J=w==="maxLength"?_E.operators.GT:_E.operators.LT,A=G.opts.unicode===!1?_E._`${E}.length`:_E._`${(0,_n.useFunc)($.gen,vn.default)}(${E})`;$.fail$data(_E._`${A} ${J} ${X}`)}};HI.default=xn});var jI=Z((FI)=>{Object.defineProperty(FI,"__esModule",{value:!0});var gn=I1(),un=R0(),dX=W0(),hn={message:({schemaCode:$})=>dX.str`must match pattern "${$}"`,params:({schemaCode:$})=>dX._`{pattern: ${$}}`},cn={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:hn,code($){let{gen:w,data:E,$data:X,schema:G,schemaCode:J,it:A}=$,D=A.opts.unicodeRegExp?"u":"";if(X){let{regExp:N}=A.opts.code,W=N.code==="new RegExp"?dX._`new RegExp`:(0,un.useFunc)(w,N),O=w.let("valid");w.try(()=>w.assign(O,dX._`${W}(${J}, ${D}).test(${E})`),()=>w.assign(O,!1)),$.fail$data(dX._`!${O}`)}else{let N=(0,gn.usePattern)($,G);$.fail$data(dX._`!${N}.test(${E})`)}}};FI.default=cn});var RI=Z((MI)=>{Object.defineProperty(MI,"__esModule",{value:!0});var a6=W0(),mn={message({keyword:$,schemaCode:w}){let E=$==="maxProperties"?"more":"fewer";return a6.str`must NOT have ${E} than ${w} properties`},params:({schemaCode:$})=>a6._`{limit: ${$}}`},rn={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:mn,code($){let{keyword:w,data:E,schemaCode:X}=$,G=w==="maxProperties"?a6.operators.GT:a6.operators.LT;$.fail$data(a6._`Object.keys(${E}).length ${G} ${X}`)}};MI.default=rn});var TI=Z((zI)=>{Object.defineProperty(zI,"__esModule",{value:!0});var e6=I1(),$J=W0(),on=R0(),tn={message:({params:{missingProperty:$}})=>$J.str`must have required property '${$}'`,params:({params:{missingProperty:$}})=>$J._`{missingProperty: ${$}}`},dn={keyword:"required",type:"object",schemaType:"array",$data:!0,error:tn,code($){let{gen:w,schema:E,schemaCode:X,data:G,$data:J,it:A}=$,{opts:D}=A;if(!J&&E.length===0)return;let N=E.length>=D.loopRequired;if(A.allErrors)W();else O();if(D.strictRequired){let L=$.parentSchema.properties,{definedProperties:F}=$.it;for(let j of E)if((L===null||L===void 0?void 0:L[j])===void 0&&!F.has(j)){let M=A.schemaEnv.baseId+A.errSchemaPath,z=`required property "${j}" is not defined at "${M}" (strictRequired)`;(0,on.checkStrictMode)(A,z,A.opts.strictRequired)}}function W(){if(N||J)$.block$data($J.nil,Y);else for(let L of E)(0,e6.checkReportMissingProp)($,L)}function O(){let L=w.let("missing");if(N||J){let F=w.let("valid",!0);$.block$data(F,()=>H(L,F)),$.ok(F)}else w.if((0,e6.checkMissingProp)($,E,L)),(0,e6.reportMissingProp)($,L),w.else()}function Y(){w.forOf("prop",X,(L)=>{$.setParams({missingProperty:L}),w.if((0,e6.noPropertyInData)(w,G,L,D.ownProperties),()=>$.error())})}function H(L,F){$.setParams({missingProperty:L}),w.forOf(L,X,()=>{w.assign(F,(0,e6.propertyInData)(w,G,L,D.ownProperties)),w.if((0,$J.not)(F),()=>{$.error(),w.break()})},$J.nil)}}};zI.default=dn});var QI=Z((BI)=>{Object.defineProperty(BI,"__esModule",{value:!0});var wJ=W0(),sn={message({keyword:$,schemaCode:w}){let E=$==="maxItems"?"more":"fewer";return wJ.str`must NOT have ${E} than ${w} items`},params:({schemaCode:$})=>wJ._`{limit: ${$}}`},an={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:sn,code($){let{keyword:w,data:E,schemaCode:X}=$,G=w==="maxItems"?wJ.operators.GT:wJ.operators.LT;$.fail$data(wJ._`${E}.length ${G} ${X}`)}};BI.default=an});var OD=Z((KI)=>{Object.defineProperty(KI,"__esModule",{value:!0});var II=yW();II.code='require("ajv/dist/runtime/equal").default';KI.default=II});var PI=Z((VI)=>{Object.defineProperty(VI,"__esModule",{value:!0});var eW=c6(),K$=W0(),wm=R0(),Em=OD(),Xm={message:({params:{i:$,j:w}})=>K$.str`must NOT have duplicate items (items ## ${w} and ${$} are identical)`,params:({params:{i:$,j:w}})=>K$._`{i: ${$}, j: ${w}}`},Gm={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Xm,code($){let{gen:w,data:E,$data:X,schema:G,parentSchema:J,schemaCode:A,it:D}=$;if(!X&&!G)return;let N=w.let("valid"),W=J.items?(0,eW.getSchemaTypes)(J.items):[];$.block$data(N,O,K$._`${A} === false`),$.ok(N);function O(){let F=w.let("i",K$._`${E}.length`),j=w.let("j");$.setParams({i:F,j}),w.assign(N,!0),w.if(K$._`${F} > 1`,()=>(Y()?H:L)(F,j))}function Y(){return W.length>0&&!W.some((F)=>F==="object"||F==="array")}function H(F,j){let M=w.name("item"),z=(0,eW.checkDataTypes)(W,M,D.opts.strictNumbers,eW.DataType.Wrong),B=w.const("indices",K$._`{}`);w.for(K$._`;${F}--;`,()=>{if(w.let(M,K$._`${E}[${F}]`),w.if(z,K$._`continue`),W.length>1)w.if(K$._`typeof ${M} == "string"`,K$._`${M} += "_"`);w.if(K$._`typeof ${B}[${M}] == "number"`,()=>{w.assign(j,K$._`${B}[${M}]`),$.error(),w.assign(N,!1).break()}).code(K$._`${B}[${M}] = ${F}`)})}function L(F,j){let M=(0,wm.useFunc)(w,Em.default),z=w.name("outer");w.label(z).for(K$._`;${F}--;`,()=>w.for(K$._`${j} = ${F}; ${j}--;`,()=>w.if(K$._`${M}(${E}[${F}], ${E}[${j}])`,()=>{$.error(),w.assign(N,!1).break(z)})))}}};VI.default=Gm});var SI=Z((qI)=>{Object.defineProperty(qI,"__esModule",{value:!0});var $O=W0(),Am=R0(),Dm=OD(),Nm={message:"must be equal to constant",params:({schemaCode:$})=>$O._`{allowedValue: ${$}}`},Wm={keyword:"const",$data:!0,error:Nm,code($){let{gen:w,data:E,$data:X,schemaCode:G,schema:J}=$;if(X||J&&typeof J=="object")$.fail$data($O._`!${(0,Am.useFunc)(w,Dm.default)}(${E}, ${G})`);else $.fail($O._`${J} !== ${E}`)}};qI.default=Wm});var bI=Z((kI)=>{Object.defineProperty(kI,"__esModule",{value:!0});var EJ=W0(),Um=R0(),Ym=OD(),Hm={message:"must be equal to one of the allowed values",params:({schemaCode:$})=>EJ._`{allowedValues: ${$}}`},Lm={keyword:"enum",schemaType:"array",$data:!0,error:Hm,code($){let{gen:w,data:E,$data:X,schema:G,schemaCode:J,it:A}=$;if(!X&&G.length===0)throw Error("enum must have non-empty array");let D=G.length>=A.opts.loopEnum,N,W=()=>N!==null&&N!==void 0?N:N=(0,Um.useFunc)(w,Ym.default),O;if(D||X)O=w.let("valid"),$.block$data(O,Y);else{if(!Array.isArray(G))throw Error("ajv implementation error");let L=w.const("vSchema",J);O=(0,EJ.or)(...G.map((F,j)=>H(L,j)))}$.pass(O);function Y(){w.assign(O,!1),w.forOf("v",J,(L)=>w.if(EJ._`${W()}(${E}, ${L})`,()=>w.assign(O,!0).break()))}function H(L,F){let j=G[F];return typeof j==="object"&&j!==null?EJ._`${W()}(${E}, ${L}[${F}])`:EJ._`${E} === ${j}`}}};kI.default=Lm});var CI=Z((ZI)=>{Object.defineProperty(ZI,"__esModule",{value:!0});var jm=DI(),Mm=WI(),Rm=LI(),zm=jI(),Tm=RI(),Bm=TI(),Qm=QI(),Im=PI(),Km=SI(),Vm=bI(),Pm=[jm.default,Mm.default,Rm.default,zm.default,Tm.default,Bm.default,Qm.default,Im.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Km.default,Vm.default];ZI.default=Pm});var EO=Z((vI)=>{Object.defineProperty(vI,"__esModule",{value:!0});vI.validateAdditionalItems=void 0;var vE=W0(),wO=R0(),Sm={message:({params:{len:$}})=>vE.str`must NOT have more than ${$} items`,params:({params:{len:$}})=>vE._`{limit: ${$}}`},km={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Sm,code($){let{parentSchema:w,it:E}=$,{items:X}=w;if(!Array.isArray(X)){(0,wO.checkStrictMode)(E,'"additionalItems" is ignored when "items" is not an array of schemas');return}_I($,X)}};function _I($,w){let{gen:E,schema:X,data:G,keyword:J,it:A}=$;A.items=!0;let D=E.const("len",vE._`${G}.length`);if(X===!1)$.setParams({len:w.length}),$.pass(vE._`${D} <= ${w.length}`);else if(typeof X=="object"&&!(0,wO.alwaysValidSchema)(A,X)){let W=E.var("valid",vE._`${D} <= ${w.length}`);E.if((0,vE.not)(W),()=>N(W)),$.ok(W)}function N(W){E.forRange("i",w.length,D,(O)=>{if($.subschema({keyword:J,dataProp:O,dataPropType:wO.Type.Num},W),!A.allErrors)E.if((0,vE.not)(W),()=>E.break())})}}vI.validateAdditionalItems=_I;vI.default=km});var XO=Z((gI)=>{Object.defineProperty(gI,"__esModule",{value:!0});gI.validateTuple=void 0;var xI=W0(),UD=R0(),Zm=I1(),Cm={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code($){let{schema:w,it:E}=$;if(Array.isArray(w))return yI($,"additionalItems",w);if(E.items=!0,(0,UD.alwaysValidSchema)(E,w))return;$.ok((0,Zm.validateArray)($))}};function yI($,w,E=$.schema){let{gen:X,parentSchema:G,data:J,keyword:A,it:D}=$;if(O(G),D.opts.unevaluated&&E.length&&D.items!==!0)D.items=UD.mergeEvaluated.items(X,E.length,D.items);let N=X.name("valid"),W=X.const("len",xI._`${J}.length`);E.forEach((Y,H)=>{if((0,UD.alwaysValidSchema)(D,Y))return;X.if(xI._`${W} > ${H}`,()=>$.subschema({keyword:A,schemaProp:H,dataProp:H},N)),$.ok(N)});function O(Y){let{opts:H,errSchemaPath:L}=D,F=E.length,j=F===Y.minItems&&(F===Y.maxItems||Y[w]===!1);if(H.strictTuples&&!j){let M=`"${A}" is ${F}-tuple, but minItems or maxItems/${w} are not specified or different at path "${L}"`;(0,UD.checkStrictMode)(D,M,H.strictTuples)}}}gI.validateTuple=yI;gI.default=Cm});var cI=Z((hI)=>{Object.defineProperty(hI,"__esModule",{value:!0});var vm=XO(),fm={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:($)=>(0,vm.validateTuple)($,"items")};hI.default=fm});var rI=Z((mI)=>{Object.defineProperty(mI,"__esModule",{value:!0});var nI=W0(),ym=R0(),gm=I1(),um=EO(),hm={message:({params:{len:$}})=>nI.str`must NOT have more than ${$} items`,params:({params:{len:$}})=>nI._`{limit: ${$}}`},cm={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:hm,code($){let{schema:w,parentSchema:E,it:X}=$,{prefixItems:G}=E;if(X.items=!0,(0,ym.alwaysValidSchema)(X,w))return;if(G)(0,um.validateAdditionalItems)($,G);else $.ok((0,gm.validateArray)($))}};mI.default=cm});var oI=Z((pI)=>{Object.defineProperty(pI,"__esModule",{value:!0});var K1=W0(),YD=R0(),mm={message:({params:{min:$,max:w}})=>w===void 0?K1.str`must contain at least ${$} valid item(s)`:K1.str`must contain at least ${$} and no more than ${w} valid item(s)`,params:({params:{min:$,max:w}})=>w===void 0?K1._`{minContains: ${$}}`:K1._`{minContains: ${$}, maxContains: ${w}}`},rm={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:mm,code($){let{gen:w,schema:E,parentSchema:X,data:G,it:J}=$,A,D,{minContains:N,maxContains:W}=X;if(J.opts.next)A=N===void 0?1:N,D=W;else A=1;let O=w.const("len",K1._`${G}.length`);if($.setParams({min:A,max:D}),D===void 0&&A===0){(0,YD.checkStrictMode)(J,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(D!==void 0&&A>D){(0,YD.checkStrictMode)(J,'"minContains" > "maxContains" is always invalid'),$.fail();return}if((0,YD.alwaysValidSchema)(J,E)){let j=K1._`${O} >= ${A}`;if(D!==void 0)j=K1._`${j} && ${O} <= ${D}`;$.pass(j);return}J.items=!0;let Y=w.name("valid");if(D===void 0&&A===1)L(Y,()=>w.if(Y,()=>w.break()));else if(A===0){if(w.let(Y,!0),D!==void 0)w.if(K1._`${G}.length > 0`,H)}else w.let(Y,!1),H();$.result(Y,()=>$.reset());function H(){let j=w.name("_valid"),M=w.let("count",0);L(j,()=>w.if(j,()=>F(M)))}function L(j,M){w.forRange("i",0,O,(z)=>{$.subschema({keyword:"contains",dataProp:z,dataPropType:YD.Type.Num,compositeRule:!0},j),M()})}function F(j){if(w.code(K1._`${j}++`),D===void 0)w.if(K1._`${j} >= ${A}`,()=>w.assign(Y,!0).break());else if(w.if(K1._`${j} > ${D}`,()=>w.assign(Y,!1).break()),A===1)w.assign(Y,!0);else w.if(K1._`${j} >= ${A}`,()=>w.assign(Y,!0))}}};pI.default=rm});var aI=Z((dI)=>{Object.defineProperty(dI,"__esModule",{value:!0});dI.validateSchemaDeps=dI.validatePropertyDeps=dI.error=void 0;var GO=W0(),om=R0(),XJ=I1();dI.error={message:({params:{property:$,depsCount:w,deps:E}})=>{let X=w===1?"property":"properties";return GO.str`must have ${X} ${E} when property ${$} is present`},params:({params:{property:$,depsCount:w,deps:E,missingProperty:X}})=>GO._`{property: ${$},
|
|
574
|
+
|| ${A} === "boolean" || ${G} === null`).assign(D,D0._`[${G}]`)}}}function Vu({gen:$,parentData:w,parentDataProperty:E},X){$.if(D0._`${w} !== undefined`,()=>$.assign(D0._`${w}[${E}]`,X))}function vW($,w,E,X=pX.Correct){let G=X===pX.Correct?D0.operators.EQ:D0.operators.NEQ,J;switch($){case"null":return D0._`${w} ${G} null`;case"array":J=D0._`Array.isArray(${w})`;break;case"object":J=D0._`${w} && typeof ${w} == "object" && !Array.isArray(${w})`;break;case"integer":J=A(D0._`!(${w} % 1) && !isNaN(${w})`);break;case"number":J=A();break;default:return D0._`typeof ${w} ${G} ${$}`}return X===pX.Correct?J:(0,D0.not)(J);function A(D=D0.nil){return(0,D0.and)(D0._`typeof ${w} == "number"`,D,E?D0._`isFinite(${w})`:D0.nil)}}CB.checkDataType=vW;function fW($,w,E,X){if($.length===1)return vW($[0],w,E,X);let G,J=(0,kB.toHash)($);if(J.array&&J.object){let A=D0._`typeof ${w} != "object"`;G=J.null?A:D0._`!${w} || ${A}`,delete J.null,delete J.array,delete J.object}else G=D0.nil;if(J.number)delete J.integer;for(let A in J)G=(0,D0.and)(G,vW(A,w,E,X));return G}CB.checkDataTypes=fW;var Pu={message:({schema:$})=>`must be ${$}`,params:({schema:$,schemaValue:w})=>typeof $=="string"?D0._`{type: ${$}}`:D0._`{type: ${w}}`};function xW($){let w=qu($);(0,Tu.reportError)(w,Pu)}CB.reportTypeError=xW;function qu($){let{gen:w,data:E,schema:X}=$,G=(0,kB.schemaRefOrVal)($,X,"type");return{gen:w,keyword:"type",data:E,schema:X.type,schemaCode:G,schemaValue:G,parentSchema:X,params:{},it:$}}});var yB=Z((fB)=>{Object.defineProperty(fB,"__esModule",{value:!0});fB.assignDefaults=void 0;var oX=W0(),vu=R0();function fu($,w){let{properties:E,items:X}=$.schema;if(w==="object"&&E)for(let G in E)vB($,G,E[G].default);else if(w==="array"&&Array.isArray(X))X.forEach((G,J)=>vB($,J,G.default))}fB.assignDefaults=fu;function vB($,w,E){let{gen:X,compositeRule:G,data:J,opts:A}=$;if(E===void 0)return;let D=oX._`${J}${(0,oX.getProperty)(w)}`;if(G){(0,vu.checkStrictMode)($,`default is ignored for: ${D}`);return}let N=oX._`${D} === undefined`;if(A.useDefaults==="empty")N=oX._`${N} || ${D} === null || ${D} === ""`;X.if(N,oX._`${D} = ${(0,oX.stringify)(E)}`)}});var I1=Z((hB)=>{Object.defineProperty(hB,"__esModule",{value:!0});hB.validateUnion=hB.validateArray=hB.usePattern=hB.callValidateCode=hB.schemaProperties=hB.allSchemaProperties=hB.noPropertyInData=hB.propertyInData=hB.isOwnProperty=hB.hasPropFunc=hB.reportMissingProp=hB.checkMissingProp=hB.checkReportMissingProp=void 0;var h0=W0(),yW=R0(),EE=qw(),xu=R0();function yu($,w){let{gen:E,data:X,it:G}=$;E.if(uW(E,X,w,G.opts.ownProperties),()=>{$.setParams({missingProperty:h0._`${w}`},!0),$.error()})}hB.checkReportMissingProp=yu;function gu({gen:$,data:w,it:{opts:E}},X,G){return(0,h0.or)(...X.map((J)=>(0,h0.and)(uW($,w,J,E.ownProperties),h0._`${G} = ${J}`)))}hB.checkMissingProp=gu;function uu($,w){$.setParams({missingProperty:w},!0),$.error()}hB.reportMissingProp=uu;function gB($){return $.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:h0._`Object.prototype.hasOwnProperty`})}hB.hasPropFunc=gB;function gW($,w,E){return h0._`${gB($)}.call(${w}, ${E})`}hB.isOwnProperty=gW;function hu($,w,E,X){let G=h0._`${w}${(0,h0.getProperty)(E)} !== undefined`;return X?h0._`${G} && ${gW($,w,E)}`:G}hB.propertyInData=hu;function uW($,w,E,X){let G=h0._`${w}${(0,h0.getProperty)(E)} === undefined`;return X?(0,h0.or)(G,(0,h0.not)(gW($,w,E))):G}hB.noPropertyInData=uW;function uB($){return $?Object.keys($).filter((w)=>w!=="__proto__"):[]}hB.allSchemaProperties=uB;function cu($,w){return uB(w).filter((E)=>!(0,yW.alwaysValidSchema)($,w[E]))}hB.schemaProperties=cu;function nu({schemaCode:$,data:w,it:{gen:E,topSchemaRef:X,schemaPath:G,errorPath:J},it:A},D,N,W){let O=W?h0._`${$}, ${w}, ${X}${G}`:w,Y=[[EE.default.instancePath,(0,h0.strConcat)(EE.default.instancePath,J)],[EE.default.parentData,A.parentData],[EE.default.parentDataProperty,A.parentDataProperty],[EE.default.rootData,EE.default.rootData]];if(A.opts.dynamicRef)Y.push([EE.default.dynamicAnchors,EE.default.dynamicAnchors]);let H=h0._`${O}, ${E.object(...Y)}`;return N!==h0.nil?h0._`${D}.call(${N}, ${H})`:h0._`${D}(${H})`}hB.callValidateCode=nu;var mu=h0._`new RegExp`;function ru({gen:$,it:{opts:w}},E){let X=w.unicodeRegExp?"u":"",{regExp:G}=w.code,J=G(E,X);return $.scopeValue("pattern",{key:J.toString(),ref:J,code:h0._`${G.code==="new RegExp"?mu:(0,xu.useFunc)($,G)}(${E}, ${X})`})}hB.usePattern=ru;function pu($){let{gen:w,data:E,keyword:X,it:G}=$,J=w.name("valid");if(G.allErrors){let D=w.let("valid",!0);return A(()=>w.assign(D,!1)),D}return w.var(J,!0),A(()=>w.break()),J;function A(D){let N=w.const("len",h0._`${E}.length`);w.forRange("i",0,N,(W)=>{$.subschema({keyword:X,dataProp:W,dataPropType:yW.Type.Num},J),w.if((0,h0.not)(J),D)})}}hB.validateArray=pu;function ou($){let{gen:w,schema:E,keyword:X,it:G}=$;if(!Array.isArray(E))throw Error("ajv implementation error");if(E.some((N)=>(0,yW.alwaysValidSchema)(G,N))&&!G.opts.unevaluated)return;let A=w.let("valid",!1),D=w.name("_valid");w.block(()=>E.forEach((N,W)=>{let O=$.subschema({keyword:X,schemaProp:W,compositeRule:!0},D);if(w.assign(A,h0._`${A} || ${D}`),!$.mergeValidEvaluated(O,D))w.if((0,h0.not)(A))})),$.result(A,()=>$.reset(),()=>$.error(!0))}hB.validateUnion=ou});var oB=Z((rB)=>{Object.defineProperty(rB,"__esModule",{value:!0});rB.validateKeywordUsage=rB.validSchemaType=rB.funcKeywordCode=rB.macroKeywordCode=void 0;var n$=W0(),ZE=qw(),Jh=I1(),Ah=c6();function Dh($,w){let{gen:E,keyword:X,schema:G,parentSchema:J,it:A}=$,D=w.macro.call(A.self,G,J,A),N=mB(E,X,D);if(A.opts.validateSchema!==!1)A.self.validateSchema(D,!0);let W=E.name("valid");$.subschema({schema:D,schemaPath:n$.nil,errSchemaPath:`${A.errSchemaPath}/${X}`,topSchemaRef:N,compositeRule:!0},W),$.pass(W,()=>$.error(!0))}rB.macroKeywordCode=Dh;function Nh($,w){var E;let{gen:X,keyword:G,schema:J,parentSchema:A,$data:D,it:N}=$;Oh(N,w);let W=!D&&w.compile?w.compile.call(N.self,J,A,N):w.validate,O=mB(X,G,W),Y=X.let("valid");$.block$data(Y,H),$.ok((E=w.valid)!==null&&E!==void 0?E:Y);function H(){if(w.errors===!1){if(j(),w.modifying)nB($);M(()=>$.error())}else{let z=w.async?L():F();if(w.modifying)nB($);M(()=>Wh($,z))}}function L(){let z=X.let("ruleErrs",null);return X.try(()=>j(n$._`await `),(B)=>X.assign(Y,!1).if(n$._`${B} instanceof ${N.ValidationError}`,()=>X.assign(z,n$._`${B}.errors`),()=>X.throw(B))),z}function F(){let z=n$._`${O}.errors`;return X.assign(z,null),j(n$.nil),z}function j(z=w.async?n$._`await `:n$.nil){let B=N.opts.passContext?ZE.default.this:ZE.default.self,Q=!(("compile"in w)&&!D||w.schema===!1);X.assign(Y,n$._`${z}${(0,Jh.callValidateCode)($,O,B,Q)}`,w.modifying)}function M(z){var B;X.if((0,n$.not)((B=w.valid)!==null&&B!==void 0?B:Y),z)}}rB.funcKeywordCode=Nh;function nB($){let{gen:w,data:E,it:X}=$;w.if(X.parentData,()=>w.assign(E,n$._`${X.parentData}[${X.parentDataProperty}]`))}function Wh($,w){let{gen:E}=$;E.if(n$._`Array.isArray(${w})`,()=>{E.assign(ZE.default.vErrors,n$._`${ZE.default.vErrors} === null ? ${w} : ${ZE.default.vErrors}.concat(${w})`).assign(ZE.default.errors,n$._`${ZE.default.vErrors}.length`),(0,Ah.extendErrors)($)},()=>$.error())}function Oh({schemaEnv:$},w){if(w.async&&!$.$async)throw Error("async keyword in sync schema")}function mB($,w,E){if(E===void 0)throw Error(`keyword "${w}" failed to compile`);return $.scopeValue("keyword",typeof E=="function"?{ref:E}:{ref:E,code:(0,n$.stringify)(E)})}function Uh($,w,E=!1){return!w.length||w.some((X)=>X==="array"?Array.isArray($):X==="object"?$&&typeof $=="object"&&!Array.isArray($):typeof $==X||E&&typeof $>"u")}rB.validSchemaType=Uh;function Yh({schema:$,opts:w,self:E,errSchemaPath:X},G,J){if(Array.isArray(G.keyword)?!G.keyword.includes(J):G.keyword!==J)throw Error("ajv implementation error");let A=G.dependencies;if(A===null||A===void 0?void 0:A.some((D)=>!Object.prototype.hasOwnProperty.call($,D)))throw Error(`parent schema must have dependencies of ${J}: ${A.join(",")}`);if(G.validateSchema){if(!G.validateSchema($[J])){let N=`keyword "${J}" value is invalid at path "${X}": `+E.errorsText(G.validateSchema.errors);if(w.validateSchema==="log")E.logger.error(N);else throw Error(N)}}}rB.validateKeywordUsage=Yh});var lB=Z((iB)=>{Object.defineProperty(iB,"__esModule",{value:!0});iB.extendSubschemaMode=iB.extendSubschemaData=iB.getSubschema=void 0;var Aw=W0(),tB=R0();function jh($,{keyword:w,schemaProp:E,schema:X,schemaPath:G,errSchemaPath:J,topSchemaRef:A}){if(w!==void 0&&X!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(w!==void 0){let D=$.schema[w];return E===void 0?{schema:D,schemaPath:Aw._`${$.schemaPath}${(0,Aw.getProperty)(w)}`,errSchemaPath:`${$.errSchemaPath}/${w}`}:{schema:D[E],schemaPath:Aw._`${$.schemaPath}${(0,Aw.getProperty)(w)}${(0,Aw.getProperty)(E)}`,errSchemaPath:`${$.errSchemaPath}/${w}/${(0,tB.escapeFragment)(E)}`}}if(X!==void 0){if(G===void 0||J===void 0||A===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:X,schemaPath:G,topSchemaRef:A,errSchemaPath:J}}throw Error('either "keyword" or "schema" must be passed')}iB.getSubschema=jh;function Mh($,w,{dataProp:E,dataPropType:X,data:G,dataTypes:J,propertyName:A}){if(G!==void 0&&E!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:D}=w;if(E!==void 0){let{errorPath:W,dataPathArr:O,opts:Y}=w,H=D.let("data",Aw._`${w.data}${(0,Aw.getProperty)(E)}`,!0);N(H),$.errorPath=Aw.str`${W}${(0,tB.getErrorPath)(E,X,Y.jsPropertySyntax)}`,$.parentDataProperty=Aw._`${E}`,$.dataPathArr=[...O,$.parentDataProperty]}if(G!==void 0){let W=G instanceof Aw.Name?G:D.let("data",G,!0);if(N(W),A!==void 0)$.propertyName=A}if(J)$.dataTypes=J;function N(W){$.data=W,$.dataLevel=w.dataLevel+1,$.dataTypes=[],w.definedProperties=new Set,$.parentData=w.data,$.dataNames=[...w.dataNames,W]}}iB.extendSubschemaData=Mh;function Rh($,{jtdDiscriminator:w,jtdMetadata:E,compositeRule:X,createErrors:G,allErrors:J}){if(X!==void 0)$.compositeRule=X;if(G!==void 0)$.createErrors=G;if(J!==void 0)$.allErrors=J;$.jtdDiscriminator=w,$.jtdMetadata=E}iB.extendSubschemaMode=Rh});var hW=Z((h80,sB)=>{sB.exports=function $(w,E){if(w===E)return!0;if(w&&E&&typeof w=="object"&&typeof E=="object"){if(w.constructor!==E.constructor)return!1;var X,G,J;if(Array.isArray(w)){if(X=w.length,X!=E.length)return!1;for(G=X;G--!==0;)if(!$(w[G],E[G]))return!1;return!0}if(w.constructor===RegExp)return w.source===E.source&&w.flags===E.flags;if(w.valueOf!==Object.prototype.valueOf)return w.valueOf()===E.valueOf();if(w.toString!==Object.prototype.toString)return w.toString()===E.toString();if(J=Object.keys(w),X=J.length,X!==Object.keys(E).length)return!1;for(G=X;G--!==0;)if(!Object.prototype.hasOwnProperty.call(E,J[G]))return!1;for(G=X;G--!==0;){var A=J[G];if(!$(w[A],E[A]))return!1}return!0}return w!==w&&E!==E}});var eB=Z((c80,aB)=>{var XE=aB.exports=function($,w,E){if(typeof w=="function")E=w,w={};E=w.cb||E;var X=typeof E=="function"?E:E.pre||function(){},G=E.post||function(){};s4(w,X,G,$,"",$)};XE.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};XE.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};XE.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};XE.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function s4($,w,E,X,G,J,A,D,N,W){if(X&&typeof X=="object"&&!Array.isArray(X)){w(X,G,J,A,D,N,W);for(var O in X){var Y=X[O];if(Array.isArray(Y)){if(O in XE.arrayKeywords)for(var H=0;H<Y.length;H++)s4($,w,E,Y[H],G+"/"+O+"/"+H,J,G,O,X,H)}else if(O in XE.propsKeywords){if(Y&&typeof Y=="object")for(var L in Y)s4($,w,E,Y[L],G+"/"+O+"/"+Bh(L),J,G,O,X,L)}else if(O in XE.keywords||$.allKeys&&!(O in XE.skipKeywords))s4($,w,E,Y,G+"/"+O,J,G,O,X)}E(X,G,J,A,D,N,W)}}function Bh($){return $.replace(/~/g,"~0").replace(/\//g,"~1")}});var m6=Z((XQ)=>{Object.defineProperty(XQ,"__esModule",{value:!0});XQ.getSchemaRefs=XQ.resolveUrl=XQ.normalizeId=XQ._getFullPath=XQ.getFullPath=XQ.inlineRef=void 0;var Qh=R0(),Ih=hW(),Kh=eB(),Vh=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Ph($,w=!0){if(typeof $=="boolean")return!0;if(w===!0)return!cW($);if(!w)return!1;return $Q($)<=w}XQ.inlineRef=Ph;var qh=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function cW($){for(let w in $){if(qh.has(w))return!0;let E=$[w];if(Array.isArray(E)&&E.some(cW))return!0;if(typeof E=="object"&&cW(E))return!0}return!1}function $Q($){let w=0;for(let E in $){if(E==="$ref")return 1/0;if(w++,Vh.has(E))continue;if(typeof $[E]=="object")(0,Qh.eachItem)($[E],(X)=>w+=$Q(X));if(w===1/0)return 1/0}return w}function wQ($,w="",E){if(E!==!1)w=tX(w);let X=$.parse(w);return EQ($,X)}XQ.getFullPath=wQ;function EQ($,w){return $.serialize(w).split("#")[0]+"#"}XQ._getFullPath=EQ;var Sh=/#\/?$/;function tX($){return $?$.replace(Sh,""):""}XQ.normalizeId=tX;function kh($,w,E){return E=tX(E),$.resolve(w,E)}XQ.resolveUrl=kh;var bh=/^[a-z_][-a-z0-9._]*$/i;function Zh($,w){if(typeof $=="boolean")return{};let{schemaId:E,uriResolver:X}=this.opts,G=tX($[E]||w),J={"":G},A=wQ(X,G,!1),D={},N=new Set;return Kh($,{allKeys:!0},(Y,H,L,F)=>{if(F===void 0)return;let j=A+H,M=J[F];if(typeof Y[E]=="string")M=z.call(this,Y[E]);B.call(this,Y.$anchor),B.call(this,Y.$dynamicAnchor),J[H]=M;function z(Q){let k=this.opts.uriResolver.resolve;if(Q=tX(M?k(M,Q):Q),N.has(Q))throw O(Q);N.add(Q);let v=this.refs[Q];if(typeof v=="string")v=this.refs[v];if(typeof v=="object")W(Y,v.schema,Q);else if(Q!==tX(j))if(Q[0]==="#")W(Y,D[Q],Q),D[Q]=Y;else this.refs[Q]=j;return Q}function B(Q){if(typeof Q=="string"){if(!bh.test(Q))throw Error(`invalid anchor "${Q}"`);z.call(this,`#${Q}`)}}}),D;function W(Y,H,L){if(H!==void 0&&!Ih(Y,H))throw O(L)}function O(Y){return Error(`reference "${Y}" resolves to more than one schema`)}}XQ.getSchemaRefs=Zh});var o6=Z((zQ)=>{Object.defineProperty(zQ,"__esModule",{value:!0});zQ.getData=zQ.KeywordCxt=zQ.validateFunctionCode=void 0;var WQ=QB(),JQ=n6(),mW=_W(),a4=n6(),yh=yB(),p6=oB(),nW=lB(),o=W0(),w0=qw(),gh=m6(),Sw=R0(),r6=c6();function uh($){if(YQ($)){if(HQ($),UQ($)){nh($);return}}OQ($,()=>(0,WQ.topBoolOrEmptySchema)($))}zQ.validateFunctionCode=uh;function OQ({gen:$,validateName:w,schema:E,schemaEnv:X,opts:G},J){if(G.code.es5)$.func(w,o._`${w0.default.data}, ${w0.default.valCxt}`,X.$async,()=>{$.code(o._`"use strict"; ${AQ(E,G)}`),ch($,G),$.code(J)});else $.func(w,o._`${w0.default.data}, ${hh(G)}`,X.$async,()=>$.code(AQ(E,G)).code(J))}function hh($){return o._`{${w0.default.instancePath}="", ${w0.default.parentData}, ${w0.default.parentDataProperty}, ${w0.default.rootData}=${w0.default.data}${$.dynamicRef?o._`, ${w0.default.dynamicAnchors}={}`:o.nil}}={}`}function ch($,w){$.if(w0.default.valCxt,()=>{if($.var(w0.default.instancePath,o._`${w0.default.valCxt}.${w0.default.instancePath}`),$.var(w0.default.parentData,o._`${w0.default.valCxt}.${w0.default.parentData}`),$.var(w0.default.parentDataProperty,o._`${w0.default.valCxt}.${w0.default.parentDataProperty}`),$.var(w0.default.rootData,o._`${w0.default.valCxt}.${w0.default.rootData}`),w.dynamicRef)$.var(w0.default.dynamicAnchors,o._`${w0.default.valCxt}.${w0.default.dynamicAnchors}`)},()=>{if($.var(w0.default.instancePath,o._`""`),$.var(w0.default.parentData,o._`undefined`),$.var(w0.default.parentDataProperty,o._`undefined`),$.var(w0.default.rootData,w0.default.data),w.dynamicRef)$.var(w0.default.dynamicAnchors,o._`{}`)})}function nh($){let{schema:w,opts:E,gen:X}=$;OQ($,()=>{if(E.$comment&&w.$comment)FQ($);if(th($),X.let(w0.default.vErrors,null),X.let(w0.default.errors,0),E.unevaluated)mh($);LQ($),lh($)});return}function mh($){let{gen:w,validateName:E}=$;$.evaluated=w.const("evaluated",o._`${E}.evaluated`),w.if(o._`${$.evaluated}.dynamicProps`,()=>w.assign(o._`${$.evaluated}.props`,o._`undefined`)),w.if(o._`${$.evaluated}.dynamicItems`,()=>w.assign(o._`${$.evaluated}.items`,o._`undefined`))}function AQ($,w){let E=typeof $=="object"&&$[w.schemaId];return E&&(w.code.source||w.code.process)?o._`/*# sourceURL=${E} */`:o.nil}function rh($,w){if(YQ($)){if(HQ($),UQ($)){ph($,w);return}}(0,WQ.boolOrEmptySchema)($,w)}function UQ({schema:$,self:w}){if(typeof $=="boolean")return!$;for(let E in $)if(w.RULES.all[E])return!0;return!1}function YQ($){return typeof $.schema!="boolean"}function ph($,w){let{schema:E,gen:X,opts:G}=$;if(G.$comment&&E.$comment)FQ($);ih($),dh($);let J=X.const("_errs",w0.default.errors);LQ($,J),X.var(w,o._`${J} === ${w0.default.errors}`)}function HQ($){(0,Sw.checkUnknownRules)($),oh($)}function LQ($,w){if($.opts.jtd)return DQ($,[],!1,w);let E=(0,JQ.getSchemaTypes)($.schema),X=(0,JQ.coerceAndCheckDataType)($,E);DQ($,E,!X,w)}function oh($){let{schema:w,errSchemaPath:E,opts:X,self:G}=$;if(w.$ref&&X.ignoreKeywordsWithRef&&(0,Sw.schemaHasRulesButRef)(w,G.RULES))G.logger.warn(`$ref: keywords ignored in schema at path "${E}"`)}function th($){let{schema:w,opts:E}=$;if(w.default!==void 0&&E.useDefaults&&E.strictSchema)(0,Sw.checkStrictMode)($,"default is ignored in the schema root")}function ih($){let w=$.schema[$.opts.schemaId];if(w)$.baseId=(0,gh.resolveUrl)($.opts.uriResolver,$.baseId,w)}function dh($){if($.schema.$async&&!$.schemaEnv.$async)throw Error("async schema in sync schema")}function FQ({gen:$,schemaEnv:w,schema:E,errSchemaPath:X,opts:G}){let J=E.$comment;if(G.$comment===!0)$.code(o._`${w0.default.self}.logger.log(${J})`);else if(typeof G.$comment=="function"){let A=o.str`${X}/$comment`,D=$.scopeValue("root",{ref:w.root});$.code(o._`${w0.default.self}.opts.$comment(${J}, ${A}, ${D}.schema)`)}}function lh($){let{gen:w,schemaEnv:E,validateName:X,ValidationError:G,opts:J}=$;if(E.$async)w.if(o._`${w0.default.errors} === 0`,()=>w.return(w0.default.data),()=>w.throw(o._`new ${G}(${w0.default.vErrors})`));else{if(w.assign(o._`${X}.errors`,w0.default.vErrors),J.unevaluated)sh($);w.return(o._`${w0.default.errors} === 0`)}}function sh({gen:$,evaluated:w,props:E,items:X}){if(E instanceof o.Name)$.assign(o._`${w}.props`,E);if(X instanceof o.Name)$.assign(o._`${w}.items`,X)}function DQ($,w,E,X){let{gen:G,schema:J,data:A,allErrors:D,opts:N,self:W}=$,{RULES:O}=W;if(J.$ref&&(N.ignoreKeywordsWithRef||!(0,Sw.schemaHasRulesButRef)(J,O))){G.block(()=>MQ($,"$ref",O.all.$ref.definition));return}if(!N.jtd)ah($,w);G.block(()=>{for(let H of O.rules)Y(H);Y(O.post)});function Y(H){if(!(0,mW.shouldUseGroup)(J,H))return;if(H.type){if(G.if((0,a4.checkDataType)(H.type,A,N.strictNumbers)),NQ($,H),w.length===1&&w[0]===H.type&&E)G.else(),(0,a4.reportTypeError)($);G.endIf()}else NQ($,H);if(!D)G.if(o._`${w0.default.errors} === ${X||0}`)}}function NQ($,w){let{gen:E,schema:X,opts:{useDefaults:G}}=$;if(G)(0,yh.assignDefaults)($,w.type);E.block(()=>{for(let J of w.rules)if((0,mW.shouldUseRule)(X,J))MQ($,J.keyword,J.definition,w.type)})}function ah($,w){if($.schemaEnv.meta||!$.opts.strictTypes)return;if(eh($,w),!$.opts.allowUnionTypes)$c($,w);wc($,$.dataTypes)}function eh($,w){if(!w.length)return;if(!$.dataTypes.length){$.dataTypes=w;return}w.forEach((E)=>{if(!jQ($.dataTypes,E))rW($,`type "${E}" not allowed by context "${$.dataTypes.join(",")}"`)}),Xc($,w)}function $c($,w){if(w.length>1&&!(w.length===2&&w.includes("null")))rW($,"use allowUnionTypes to allow union type keyword")}function wc($,w){let E=$.self.RULES.all;for(let X in E){let G=E[X];if(typeof G=="object"&&(0,mW.shouldUseRule)($.schema,G)){let{type:J}=G.definition;if(J.length&&!J.some((A)=>Ec(w,A)))rW($,`missing type "${J.join(",")}" for keyword "${X}"`)}}}function Ec($,w){return $.includes(w)||w==="number"&&$.includes("integer")}function jQ($,w){return $.includes(w)||w==="integer"&&$.includes("number")}function Xc($,w){let E=[];for(let X of $.dataTypes)if(jQ(w,X))E.push(X);else if(w.includes("integer")&&X==="number")E.push("integer");$.dataTypes=E}function rW($,w){let E=$.schemaEnv.baseId+$.errSchemaPath;w+=` at "${E}" (strictTypes)`,(0,Sw.checkStrictMode)($,w,$.opts.strictTypes)}class pW{constructor($,w,E){if((0,p6.validateKeywordUsage)($,w,E),this.gen=$.gen,this.allErrors=$.allErrors,this.keyword=E,this.data=$.data,this.schema=$.schema[E],this.$data=w.$data&&$.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Sw.schemaRefOrVal)($,this.schema,E,this.$data),this.schemaType=w.schemaType,this.parentSchema=$.schema,this.params={},this.it=$,this.def=w,this.$data)this.schemaCode=$.gen.const("vSchema",RQ(this.$data,$));else if(this.schemaCode=this.schemaValue,!(0,p6.validSchemaType)(this.schema,w.schemaType,w.allowUndefined))throw Error(`${E} value must be ${JSON.stringify(w.schemaType)}`);if("code"in w?w.trackErrors:w.errors!==!1)this.errsCount=$.gen.const("_errs",w0.default.errors)}result($,w,E){this.failResult((0,o.not)($),w,E)}failResult($,w,E){if(this.gen.if($),E)E();else this.error();if(w){if(this.gen.else(),w(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass($,w){this.failResult((0,o.not)($),void 0,w)}fail($){if($===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if($),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data($){if(!this.$data)return this.fail($);let{schemaCode:w}=this;this.fail(o._`${w} !== undefined && (${(0,o.or)(this.invalid$data(),$)})`)}error($,w,E){if(w){this.setParams(w),this._error($,E),this.setParams({});return}this._error($,E)}_error($,w){($?r6.reportExtraError:r6.reportError)(this,this.def.error,w)}$dataError(){(0,r6.reportError)(this,this.def.$dataError||r6.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,r6.resetErrorsCount)(this.gen,this.errsCount)}ok($){if(!this.allErrors)this.gen.if($)}setParams($,w){if(w)Object.assign(this.params,$);else this.params=$}block$data($,w,E=o.nil){this.gen.block(()=>{this.check$data($,E),w()})}check$data($=o.nil,w=o.nil){if(!this.$data)return;let{gen:E,schemaCode:X,schemaType:G,def:J}=this;if(E.if((0,o.or)(o._`${X} === undefined`,w)),$!==o.nil)E.assign($,!0);if(G.length||J.validateSchema){if(E.elseIf(this.invalid$data()),this.$dataError(),$!==o.nil)E.assign($,!1)}E.else()}invalid$data(){let{gen:$,schemaCode:w,schemaType:E,def:X,it:G}=this;return(0,o.or)(J(),A());function J(){if(E.length){if(!(w instanceof o.Name))throw Error("ajv implementation error");let D=Array.isArray(E)?E:[E];return o._`${(0,a4.checkDataTypes)(D,w,G.opts.strictNumbers,a4.DataType.Wrong)}`}return o.nil}function A(){if(X.validateSchema){let D=$.scopeValue("validate$data",{ref:X.validateSchema});return o._`!${D}(${w})`}return o.nil}}subschema($,w){let E=(0,nW.getSubschema)(this.it,$);(0,nW.extendSubschemaData)(E,this.it,$),(0,nW.extendSubschemaMode)(E,$);let X={...this.it,...E,items:void 0,props:void 0};return rh(X,w),X}mergeEvaluated($,w){let{it:E,gen:X}=this;if(!E.opts.unevaluated)return;if(E.props!==!0&&$.props!==void 0)E.props=Sw.mergeEvaluated.props(X,$.props,E.props,w);if(E.items!==!0&&$.items!==void 0)E.items=Sw.mergeEvaluated.items(X,$.items,E.items,w)}mergeValidEvaluated($,w){let{it:E,gen:X}=this;if(E.opts.unevaluated&&(E.props!==!0||E.items!==!0))return X.if(w,()=>this.mergeEvaluated($,o.Name)),!0}}zQ.KeywordCxt=pW;function MQ($,w,E,X){let G=new pW($,E,w);if("code"in E)E.code(G,X);else if(G.$data&&E.validate)(0,p6.funcKeywordCode)(G,E);else if("macro"in E)(0,p6.macroKeywordCode)(G,E);else if(E.compile||E.validate)(0,p6.funcKeywordCode)(G,E)}var Gc=/^\/(?:[^~]|~0|~1)*$/,Jc=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function RQ($,{dataLevel:w,dataNames:E,dataPathArr:X}){let G,J;if($==="")return w0.default.rootData;if($[0]==="/"){if(!Gc.test($))throw Error(`Invalid JSON-pointer: ${$}`);G=$,J=w0.default.rootData}else{let W=Jc.exec($);if(!W)throw Error(`Invalid JSON-pointer: ${$}`);let O=+W[1];if(G=W[2],G==="#"){if(O>=w)throw Error(N("property/index",O));return X[w-O]}if(O>w)throw Error(N("data",O));if(J=E[w-O],!G)return J}let A=J,D=G.split("/");for(let W of D)if(W)J=o._`${J}${(0,o.getProperty)((0,Sw.unescapeJsonPointer)(W))}`,A=o._`${A} && ${J}`;return A;function N(W,O){return`Cannot access ${W} ${O} levels up, current level is ${w}`}}zQ.getData=RQ});var e4=Z((QQ)=>{Object.defineProperty(QQ,"__esModule",{value:!0});class BQ extends Error{constructor($){super("validation failed");this.errors=$,this.ajv=this.validation=!0}}QQ.default=BQ});var t6=Z((KQ)=>{Object.defineProperty(KQ,"__esModule",{value:!0});var oW=m6();class IQ extends Error{constructor($,w,E,X){super(X||`can't resolve reference ${E} from id ${w}`);this.missingRef=(0,oW.resolveUrl)($,w,E),this.missingSchema=(0,oW.normalizeId)((0,oW.getFullPath)($,this.missingRef))}}KQ.default=IQ});var wD=Z((qQ)=>{Object.defineProperty(qQ,"__esModule",{value:!0});qQ.resolveSchema=qQ.getCompilingSchema=qQ.resolveRef=qQ.compileSchema=qQ.SchemaEnv=void 0;var n1=W0(),Oc=e4(),CE=qw(),m1=m6(),VQ=R0(),Uc=o6();class i6{constructor($){var w;this.refs={},this.dynamicAnchors={};let E;if(typeof $.schema=="object")E=$.schema;this.schema=$.schema,this.schemaId=$.schemaId,this.root=$.root||this,this.baseId=(w=$.baseId)!==null&&w!==void 0?w:(0,m1.normalizeId)(E===null||E===void 0?void 0:E[$.schemaId||"$id"]),this.schemaPath=$.schemaPath,this.localRefs=$.localRefs,this.meta=$.meta,this.$async=E===null||E===void 0?void 0:E.$async,this.refs={}}}qQ.SchemaEnv=i6;function iW($){let w=PQ.call(this,$);if(w)return w;let E=(0,m1.getFullPath)(this.opts.uriResolver,$.root.baseId),{es5:X,lines:G}=this.opts.code,{ownProperties:J}=this.opts,A=new n1.CodeGen(this.scope,{es5:X,lines:G,ownProperties:J}),D;if($.$async)D=A.scopeValue("Error",{ref:Oc.default,code:n1._`require("ajv/dist/runtime/validation_error").default`});let N=A.scopeName("validate");$.validateName=N;let W={gen:A,allErrors:this.opts.allErrors,data:CE.default.data,parentData:CE.default.parentData,parentDataProperty:CE.default.parentDataProperty,dataNames:[CE.default.data],dataPathArr:[n1.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:A.scopeValue("schema",this.opts.code.source===!0?{ref:$.schema,code:(0,n1.stringify)($.schema)}:{ref:$.schema}),validateName:N,ValidationError:D,schema:$.schema,schemaEnv:$,rootId:E,baseId:$.baseId||E,schemaPath:n1.nil,errSchemaPath:$.schemaPath||(this.opts.jtd?"":"#"),errorPath:n1._`""`,opts:this.opts,self:this},O;try{this._compilations.add($),(0,Uc.validateFunctionCode)(W),A.optimize(this.opts.code.optimize);let Y=A.toString();if(O=`${A.scopeRefs(CE.default.scope)}return ${Y}`,this.opts.code.process)O=this.opts.code.process(O,$);let L=Function(`${CE.default.self}`,`${CE.default.scope}`,O)(this,this.scope.get());if(this.scope.value(N,{ref:L}),L.errors=null,L.schema=$.schema,L.schemaEnv=$,$.$async)L.$async=!0;if(this.opts.code.source===!0)L.source={validateName:N,validateCode:Y,scopeValues:A._values};if(this.opts.unevaluated){let{props:F,items:j}=W;if(L.evaluated={props:F instanceof n1.Name?void 0:F,items:j instanceof n1.Name?void 0:j,dynamicProps:F instanceof n1.Name,dynamicItems:j instanceof n1.Name},L.source)L.source.evaluated=(0,n1.stringify)(L.evaluated)}return $.validate=L,$}catch(Y){if(delete $.validate,delete $.validateName,O)this.logger.error("Error compiling schema, function code:",O);throw Y}finally{this._compilations.delete($)}}qQ.compileSchema=iW;function Yc($,w,E){var X;E=(0,m1.resolveUrl)(this.opts.uriResolver,w,E);let G=$.refs[E];if(G)return G;let J=Fc.call(this,$,E);if(J===void 0){let A=(X=$.localRefs)===null||X===void 0?void 0:X[E],{schemaId:D}=this.opts;if(A)J=new i6({schema:A,schemaId:D,root:$,baseId:w})}if(J===void 0)return;return $.refs[E]=Hc.call(this,J)}qQ.resolveRef=Yc;function Hc($){if((0,m1.inlineRef)($.schema,this.opts.inlineRefs))return $.schema;return $.validate?$:iW.call(this,$)}function PQ($){for(let w of this._compilations)if(Lc(w,$))return w}qQ.getCompilingSchema=PQ;function Lc($,w){return $.schema===w.schema&&$.root===w.root&&$.baseId===w.baseId}function Fc($,w){let E;while(typeof(E=this.refs[w])=="string")w=E;return E||this.schemas[w]||$D.call(this,$,w)}function $D($,w){let E=this.opts.uriResolver.parse(w),X=(0,m1._getFullPath)(this.opts.uriResolver,E),G=(0,m1.getFullPath)(this.opts.uriResolver,$.baseId,void 0);if(Object.keys($.schema).length>0&&X===G)return tW.call(this,E,$);let J=(0,m1.normalizeId)(X),A=this.refs[J]||this.schemas[J];if(typeof A=="string"){let D=$D.call(this,$,A);if(typeof(D===null||D===void 0?void 0:D.schema)!=="object")return;return tW.call(this,E,D)}if(typeof(A===null||A===void 0?void 0:A.schema)!=="object")return;if(!A.validate)iW.call(this,A);if(J===(0,m1.normalizeId)(w)){let{schema:D}=A,{schemaId:N}=this.opts,W=D[N];if(W)G=(0,m1.resolveUrl)(this.opts.uriResolver,G,W);return new i6({schema:D,schemaId:N,root:$,baseId:G})}return tW.call(this,E,A)}qQ.resolveSchema=$D;var jc=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function tW($,{baseId:w,schema:E,root:X}){var G;if(((G=$.fragment)===null||G===void 0?void 0:G[0])!=="/")return;for(let D of $.fragment.slice(1).split("/")){if(typeof E==="boolean")return;let N=E[(0,VQ.unescapeFragment)(D)];if(N===void 0)return;E=N;let W=typeof E==="object"&&E[this.opts.schemaId];if(!jc.has(D)&&W)w=(0,m1.resolveUrl)(this.opts.uriResolver,w,W)}let J;if(typeof E!="boolean"&&E.$ref&&!(0,VQ.schemaHasRulesButRef)(E,this.RULES)){let D=(0,m1.resolveUrl)(this.opts.uriResolver,w,E.$ref);J=$D.call(this,X,D)}let{schemaId:A}=this.opts;if(J=J||new i6({schema:E,schemaId:A,root:X,baseId:w}),J.schema!==J.root.schema)return J;return}});var kQ=Z((t80,Bc)=>{Bc.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var lW=Z((i80,_Q)=>{var Qc=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),ZQ=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function dW($){let w="",E=0,X=0;for(X=0;X<$.length;X++){if(E=$[X].charCodeAt(0),E===48)continue;if(!(E>=48&&E<=57||E>=65&&E<=70||E>=97&&E<=102))return"";w+=$[X];break}for(X+=1;X<$.length;X++){if(E=$[X].charCodeAt(0),!(E>=48&&E<=57||E>=65&&E<=70||E>=97&&E<=102))return"";w+=$[X]}return w}var Ic=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function bQ($){return $.length=0,!0}function Kc($,w,E){if($.length){let X=dW($);if(X!=="")w.push(X);else return E.error=!0,!1;$.length=0}return!0}function Vc($){let w=0,E={error:!1,address:"",zone:""},X=[],G=[],J=!1,A=!1,D=Kc;for(let N=0;N<$.length;N++){let W=$[N];if(W==="["||W==="]")continue;if(W===":"){if(J===!0)A=!0;if(!D(G,X,E))break;if(++w>7){E.error=!0;break}if(N>0&&$[N-1]===":")J=!0;X.push(":");continue}else if(W==="%"){if(!D(G,X,E))break;D=bQ}else{G.push(W);continue}}if(G.length)if(D===bQ)E.zone=G.join("");else if(A)X.push(G.join(""));else X.push(dW(G));return E.address=X.join(""),E}function CQ($){if(Pc($,":")<2)return{host:$,isIPV6:!1};let w=Vc($);if(!w.error){let{address:E,address:X}=w;if(w.zone)E+="%"+w.zone,X+="%25"+w.zone;return{host:E,isIPV6:!0,escapedHost:X}}else return{host:$,isIPV6:!1}}function Pc($,w){let E=0;for(let X=0;X<$.length;X++)if($[X]===w)E++;return E}function qc($){let w=$,E=[],X=-1,G=0;while(G=w.length){if(G===1)if(w===".")break;else if(w==="/"){E.push("/");break}else{E.push(w);break}else if(G===2){if(w[0]==="."){if(w[1]===".")break;else if(w[1]==="/"){w=w.slice(2);continue}}else if(w[0]==="/"){if(w[1]==="."||w[1]==="/"){E.push("/");break}}}else if(G===3){if(w==="/.."){if(E.length!==0)E.pop();E.push("/");break}}if(w[0]==="."){if(w[1]==="."){if(w[2]==="/"){w=w.slice(3);continue}}else if(w[1]==="/"){w=w.slice(2);continue}}else if(w[0]==="/"){if(w[1]==="."){if(w[2]==="/"){w=w.slice(2);continue}else if(w[2]==="."){if(w[3]==="/"){if(w=w.slice(3),E.length!==0)E.pop();continue}}}}if((X=w.indexOf("/",1))===-1){E.push(w);break}else E.push(w.slice(0,X)),w=w.slice(X)}return E.join("")}function Sc($,w){let E=w!==!0?escape:unescape;if($.scheme!==void 0)$.scheme=E($.scheme);if($.userinfo!==void 0)$.userinfo=E($.userinfo);if($.host!==void 0)$.host=E($.host);if($.path!==void 0)$.path=E($.path);if($.query!==void 0)$.query=E($.query);if($.fragment!==void 0)$.fragment=E($.fragment);return $}function kc($){let w=[];if($.userinfo!==void 0)w.push($.userinfo),w.push("@");if($.host!==void 0){let E=unescape($.host);if(!ZQ(E)){let X=CQ(E);if(X.isIPV6===!0)E=`[${X.escapedHost}]`;else E=$.host}w.push(E)}if(typeof $.port==="number"||typeof $.port==="string")w.push(":"),w.push(String($.port));return w.length?w.join(""):void 0}_Q.exports={nonSimpleDomain:Ic,recomposeAuthority:kc,normalizeComponentEncoding:Sc,removeDotSegments:qc,isIPv4:ZQ,isUUID:Qc,normalizeIPv6:CQ,stringArrayToHexStripped:dW}});var gQ=Z((d80,yQ)=>{var{isUUID:bc}=lW(),Zc=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Cc=["http","https","ws","wss","urn","urn:uuid"];function _c($){return Cc.indexOf($)!==-1}function sW($){if($.secure===!0)return!0;else if($.secure===!1)return!1;else if($.scheme)return $.scheme.length===3&&($.scheme[0]==="w"||$.scheme[0]==="W")&&($.scheme[1]==="s"||$.scheme[1]==="S")&&($.scheme[2]==="s"||$.scheme[2]==="S");else return!1}function vQ($){if(!$.host)$.error=$.error||"HTTP URIs must have a host.";return $}function fQ($){let w=String($.scheme).toLowerCase()==="https";if($.port===(w?443:80)||$.port==="")$.port=void 0;if(!$.path)$.path="/";return $}function vc($){return $.secure=sW($),$.resourceName=($.path||"/")+($.query?"?"+$.query:""),$.path=void 0,$.query=void 0,$}function fc($){if($.port===(sW($)?443:80)||$.port==="")$.port=void 0;if(typeof $.secure==="boolean")$.scheme=$.secure?"wss":"ws",$.secure=void 0;if($.resourceName){let[w,E]=$.resourceName.split("?");$.path=w&&w!=="/"?w:void 0,$.query=E,$.resourceName=void 0}return $.fragment=void 0,$}function xc($,w){if(!$.path)return $.error="URN can not be parsed",$;let E=$.path.match(Zc);if(E){let X=w.scheme||$.scheme||"urn";$.nid=E[1].toLowerCase(),$.nss=E[2];let G=`${X}:${w.nid||$.nid}`,J=aW(G);if($.path=void 0,J)$=J.parse($,w)}else $.error=$.error||"URN can not be parsed.";return $}function yc($,w){if($.nid===void 0)throw Error("URN without nid cannot be serialized");let E=w.scheme||$.scheme||"urn",X=$.nid.toLowerCase(),G=`${E}:${w.nid||X}`,J=aW(G);if(J)$=J.serialize($,w);let A=$,D=$.nss;return A.path=`${X||w.nid}:${D}`,w.skipEscape=!0,A}function gc($,w){let E=$;if(E.uuid=E.nss,E.nss=void 0,!w.tolerant&&(!E.uuid||!bc(E.uuid)))E.error=E.error||"UUID is not valid.";return E}function uc($){let w=$;return w.nss=($.uuid||"").toLowerCase(),w}var xQ={scheme:"http",domainHost:!0,parse:vQ,serialize:fQ},hc={scheme:"https",domainHost:xQ.domainHost,parse:vQ,serialize:fQ},ED={scheme:"ws",domainHost:!0,parse:vc,serialize:fc},cc={scheme:"wss",domainHost:ED.domainHost,parse:ED.parse,serialize:ED.serialize},nc={scheme:"urn",parse:xc,serialize:yc,skipNormalize:!0},mc={scheme:"urn:uuid",parse:gc,serialize:uc,skipNormalize:!0},XD={http:xQ,https:hc,ws:ED,wss:cc,urn:nc,"urn:uuid":mc};Object.setPrototypeOf(XD,null);function aW($){return $&&(XD[$]||XD[$.toLowerCase()])||void 0}yQ.exports={wsIsSecure:sW,SCHEMES:XD,isValidSchemeName:_c,getSchemeHandler:aW}});var cQ=Z((l80,JD)=>{var{normalizeIPv6:rc,removeDotSegments:d6,recomposeAuthority:pc,normalizeComponentEncoding:GD,isIPv4:oc,nonSimpleDomain:tc}=lW(),{SCHEMES:ic,getSchemeHandler:uQ}=gQ();function dc($,w){if(typeof $==="string")$=Dw(kw($,w),w);else if(typeof $==="object")$=kw(Dw($,w),w);return $}function lc($,w,E){let X=E?Object.assign({scheme:"null"},E):{scheme:"null"},G=hQ(kw($,X),kw(w,X),X,!0);return X.skipEscape=!0,Dw(G,X)}function hQ($,w,E,X){let G={};if(!X)$=kw(Dw($,E),E),w=kw(Dw(w,E),E);if(E=E||{},!E.tolerant&&w.scheme)G.scheme=w.scheme,G.userinfo=w.userinfo,G.host=w.host,G.port=w.port,G.path=d6(w.path||""),G.query=w.query;else{if(w.userinfo!==void 0||w.host!==void 0||w.port!==void 0)G.userinfo=w.userinfo,G.host=w.host,G.port=w.port,G.path=d6(w.path||""),G.query=w.query;else{if(!w.path)if(G.path=$.path,w.query!==void 0)G.query=w.query;else G.query=$.query;else{if(w.path[0]==="/")G.path=d6(w.path);else{if(($.userinfo!==void 0||$.host!==void 0||$.port!==void 0)&&!$.path)G.path="/"+w.path;else if(!$.path)G.path=w.path;else G.path=$.path.slice(0,$.path.lastIndexOf("/")+1)+w.path;G.path=d6(G.path)}G.query=w.query}G.userinfo=$.userinfo,G.host=$.host,G.port=$.port}G.scheme=$.scheme}return G.fragment=w.fragment,G}function sc($,w,E){if(typeof $==="string")$=unescape($),$=Dw(GD(kw($,E),!0),{...E,skipEscape:!0});else if(typeof $==="object")$=Dw(GD($,!0),{...E,skipEscape:!0});if(typeof w==="string")w=unescape(w),w=Dw(GD(kw(w,E),!0),{...E,skipEscape:!0});else if(typeof w==="object")w=Dw(GD(w,!0),{...E,skipEscape:!0});return $.toLowerCase()===w.toLowerCase()}function Dw($,w){let E={host:$.host,scheme:$.scheme,userinfo:$.userinfo,port:$.port,path:$.path,query:$.query,nid:$.nid,nss:$.nss,uuid:$.uuid,fragment:$.fragment,reference:$.reference,resourceName:$.resourceName,secure:$.secure,error:""},X=Object.assign({},w),G=[],J=uQ(X.scheme||E.scheme);if(J&&J.serialize)J.serialize(E,X);if(E.path!==void 0)if(!X.skipEscape){if(E.path=escape(E.path),E.scheme!==void 0)E.path=E.path.split("%3A").join(":")}else E.path=unescape(E.path);if(X.reference!=="suffix"&&E.scheme)G.push(E.scheme,":");let A=pc(E);if(A!==void 0){if(X.reference!=="suffix")G.push("//");if(G.push(A),E.path&&E.path[0]!=="/")G.push("/")}if(E.path!==void 0){let D=E.path;if(!X.absolutePath&&(!J||!J.absolutePath))D=d6(D);if(A===void 0&&D[0]==="/"&&D[1]==="/")D="/%2F"+D.slice(2);G.push(D)}if(E.query!==void 0)G.push("?",E.query);if(E.fragment!==void 0)G.push("#",E.fragment);return G.join("")}var ac=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function kw($,w){let E=Object.assign({},w),X={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},G=!1;if(E.reference==="suffix")if(E.scheme)$=E.scheme+":"+$;else $="//"+$;let J=$.match(ac);if(J){if(X.scheme=J[1],X.userinfo=J[3],X.host=J[4],X.port=parseInt(J[5],10),X.path=J[6]||"",X.query=J[7],X.fragment=J[8],isNaN(X.port))X.port=J[5];if(X.host)if(oc(X.host)===!1){let N=rc(X.host);X.host=N.host.toLowerCase(),G=N.isIPV6}else G=!0;if(X.scheme===void 0&&X.userinfo===void 0&&X.host===void 0&&X.port===void 0&&X.query===void 0&&!X.path)X.reference="same-document";else if(X.scheme===void 0)X.reference="relative";else if(X.fragment===void 0)X.reference="absolute";else X.reference="uri";if(E.reference&&E.reference!=="suffix"&&E.reference!==X.reference)X.error=X.error||"URI is not a "+E.reference+" reference.";let A=uQ(E.scheme||X.scheme);if(!E.unicodeSupport&&(!A||!A.unicodeSupport)){if(X.host&&(E.domainHost||A&&A.domainHost)&&G===!1&&tc(X.host))try{X.host=URL.domainToASCII(X.host.toLowerCase())}catch(D){X.error=X.error||"Host's domain name can not be converted to ASCII: "+D}}if(!A||A&&!A.skipNormalize){if($.indexOf("%")!==-1){if(X.scheme!==void 0)X.scheme=unescape(X.scheme);if(X.host!==void 0)X.host=unescape(X.host)}if(X.path)X.path=escape(unescape(X.path));if(X.fragment)X.fragment=encodeURI(decodeURIComponent(X.fragment))}if(A&&A.parse)A.parse(X,E)}else X.error=X.error||"URI can not be parsed.";return X}var eW={SCHEMES:ic,normalize:dc,resolve:lc,resolveComponent:hQ,equal:sc,serialize:Dw,parse:kw};JD.exports=eW;JD.exports.default=eW;JD.exports.fastUri=eW});var rQ=Z((mQ)=>{Object.defineProperty(mQ,"__esModule",{value:!0});var nQ=cQ();nQ.code='require("ajv/dist/runtime/uri").default';mQ.default=nQ});var aQ=Z((bw)=>{Object.defineProperty(bw,"__esModule",{value:!0});bw.CodeGen=bw.Name=bw.nil=bw.stringify=bw.str=bw._=bw.KeywordCxt=void 0;var $n=o6();Object.defineProperty(bw,"KeywordCxt",{enumerable:!0,get:function(){return $n.KeywordCxt}});var iX=W0();Object.defineProperty(bw,"_",{enumerable:!0,get:function(){return iX._}});Object.defineProperty(bw,"str",{enumerable:!0,get:function(){return iX.str}});Object.defineProperty(bw,"stringify",{enumerable:!0,get:function(){return iX.stringify}});Object.defineProperty(bw,"nil",{enumerable:!0,get:function(){return iX.nil}});Object.defineProperty(bw,"Name",{enumerable:!0,get:function(){return iX.Name}});Object.defineProperty(bw,"CodeGen",{enumerable:!0,get:function(){return iX.CodeGen}});var wn=e4(),dQ=t6(),En=CW(),l6=wD(),Xn=W0(),s6=m6(),AD=n6(),wO=R0(),pQ=kQ(),Gn=rQ(),lQ=($,w)=>new RegExp($,w);lQ.code="new RegExp";var Jn=["removeAdditional","useDefaults","coerceTypes"],An=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Dn={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},Nn={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},oQ=200;function Wn($){var w,E,X,G,J,A,D,N,W,O,Y,H,L,F,j,M,z,B,Q,k,v,C,n,T0,f0;let c0=$.strict,d0=(w=$.code)===null||w===void 0?void 0:w.optimize,K0=d0===!0||d0===void 0?1:d0||0,U$=(X=(E=$.code)===null||E===void 0?void 0:E.regExp)!==null&&X!==void 0?X:lQ,O1=(G=$.uriResolver)!==null&&G!==void 0?G:Gn.default;return{strictSchema:(A=(J=$.strictSchema)!==null&&J!==void 0?J:c0)!==null&&A!==void 0?A:!0,strictNumbers:(N=(D=$.strictNumbers)!==null&&D!==void 0?D:c0)!==null&&N!==void 0?N:!0,strictTypes:(O=(W=$.strictTypes)!==null&&W!==void 0?W:c0)!==null&&O!==void 0?O:"log",strictTuples:(H=(Y=$.strictTuples)!==null&&Y!==void 0?Y:c0)!==null&&H!==void 0?H:"log",strictRequired:(F=(L=$.strictRequired)!==null&&L!==void 0?L:c0)!==null&&F!==void 0?F:!1,code:$.code?{...$.code,optimize:K0,regExp:U$}:{optimize:K0,regExp:U$},loopRequired:(j=$.loopRequired)!==null&&j!==void 0?j:oQ,loopEnum:(M=$.loopEnum)!==null&&M!==void 0?M:oQ,meta:(z=$.meta)!==null&&z!==void 0?z:!0,messages:(B=$.messages)!==null&&B!==void 0?B:!0,inlineRefs:(Q=$.inlineRefs)!==null&&Q!==void 0?Q:!0,schemaId:(k=$.schemaId)!==null&&k!==void 0?k:"$id",addUsedSchema:(v=$.addUsedSchema)!==null&&v!==void 0?v:!0,validateSchema:(C=$.validateSchema)!==null&&C!==void 0?C:!0,validateFormats:(n=$.validateFormats)!==null&&n!==void 0?n:!0,unicodeRegExp:(T0=$.unicodeRegExp)!==null&&T0!==void 0?T0:!0,int32range:(f0=$.int32range)!==null&&f0!==void 0?f0:!0,uriResolver:O1}}class DD{constructor($={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,$=this.opts={...$,...Wn($)};let{es5:w,lines:E}=this.opts.code;this.scope=new Xn.ValueScope({scope:{},prefixes:An,es5:w,lines:E}),this.logger=Fn($.logger);let X=$.validateFormats;if($.validateFormats=!1,this.RULES=(0,En.getRules)(),tQ.call(this,Dn,$,"NOT SUPPORTED"),tQ.call(this,Nn,$,"DEPRECATED","warn"),this._metaOpts=Hn.call(this),$.formats)Un.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),$.keywords)Yn.call(this,$.keywords);if(typeof $.meta=="object")this.addMetaSchema($.meta);On.call(this),$.validateFormats=X}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:$,meta:w,schemaId:E}=this.opts,X=pQ;if(E==="id")X={...pQ},X.id=X.$id,delete X.$id;if(w&&$)this.addMetaSchema(X,X[E],!1)}defaultMeta(){let{meta:$,schemaId:w}=this.opts;return this.opts.defaultMeta=typeof $=="object"?$[w]||$:void 0}validate($,w){let E;if(typeof $=="string"){if(E=this.getSchema($),!E)throw Error(`no schema with key or ref "${$}"`)}else E=this.compile($);let X=E(w);if(!("$async"in E))this.errors=E.errors;return X}compile($,w){let E=this._addSchema($,w);return E.validate||this._compileSchemaEnv(E)}compileAsync($,w){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:E}=this.opts;return X.call(this,$,w);async function X(W,O){await G.call(this,W.$schema);let Y=this._addSchema(W,O);return Y.validate||J.call(this,Y)}async function G(W){if(W&&!this.getSchema(W))await X.call(this,{$ref:W},!0)}async function J(W){try{return this._compileSchemaEnv(W)}catch(O){if(!(O instanceof dQ.default))throw O;return A.call(this,O),await D.call(this,O.missingSchema),J.call(this,W)}}function A({missingSchema:W,missingRef:O}){if(this.refs[W])throw Error(`AnySchema ${W} is loaded but ${O} cannot be resolved`)}async function D(W){let O=await N.call(this,W);if(!this.refs[W])await G.call(this,O.$schema);if(!this.refs[W])this.addSchema(O,W,w)}async function N(W){let O=this._loading[W];if(O)return O;try{return await(this._loading[W]=E(W))}finally{delete this._loading[W]}}}addSchema($,w,E,X=this.opts.validateSchema){if(Array.isArray($)){for(let J of $)this.addSchema(J,void 0,E,X);return this}let G;if(typeof $==="object"){let{schemaId:J}=this.opts;if(G=$[J],G!==void 0&&typeof G!="string")throw Error(`schema ${J} must be string`)}return w=(0,s6.normalizeId)(w||G),this._checkUnique(w),this.schemas[w]=this._addSchema($,E,w,X,!0),this}addMetaSchema($,w,E=this.opts.validateSchema){return this.addSchema($,w,!0,E),this}validateSchema($,w){if(typeof $=="boolean")return!0;let E;if(E=$.$schema,E!==void 0&&typeof E!="string")throw Error("$schema must be a string");if(E=E||this.opts.defaultMeta||this.defaultMeta(),!E)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let X=this.validate(E,$);if(!X&&w){let G="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(G);else throw Error(G)}return X}getSchema($){let w;while(typeof(w=iQ.call(this,$))=="string")$=w;if(w===void 0){let{schemaId:E}=this.opts,X=new l6.SchemaEnv({schema:{},schemaId:E});if(w=l6.resolveSchema.call(this,X,$),!w)return;this.refs[$]=w}return w.validate||this._compileSchemaEnv(w)}removeSchema($){if($ instanceof RegExp)return this._removeAllSchemas(this.schemas,$),this._removeAllSchemas(this.refs,$),this;switch(typeof $){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let w=iQ.call(this,$);if(typeof w=="object")this._cache.delete(w.schema);return delete this.schemas[$],delete this.refs[$],this}case"object":{let w=$;this._cache.delete(w);let E=$[this.opts.schemaId];if(E)E=(0,s6.normalizeId)(E),delete this.schemas[E],delete this.refs[E];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary($){for(let w of $)this.addKeyword(w);return this}addKeyword($,w){let E;if(typeof $=="string"){if(E=$,typeof w=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),w.keyword=E}else if(typeof $=="object"&&w===void 0){if(w=$,E=w.keyword,Array.isArray(E)&&!E.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(Mn.call(this,E,w),!w)return(0,wO.eachItem)(E,(G)=>$O.call(this,G)),this;zn.call(this,w);let X={...w,type:(0,AD.getJSONTypes)(w.type),schemaType:(0,AD.getJSONTypes)(w.schemaType)};return(0,wO.eachItem)(E,X.type.length===0?(G)=>$O.call(this,G,X):(G)=>X.type.forEach((J)=>$O.call(this,G,X,J))),this}getKeyword($){let w=this.RULES.all[$];return typeof w=="object"?w.definition:!!w}removeKeyword($){let{RULES:w}=this;delete w.keywords[$],delete w.all[$];for(let E of w.rules){let X=E.rules.findIndex((G)=>G.keyword===$);if(X>=0)E.rules.splice(X,1)}return this}addFormat($,w){if(typeof w=="string")w=new RegExp(w);return this.formats[$]=w,this}errorsText($=this.errors,{separator:w=", ",dataVar:E="data"}={}){if(!$||$.length===0)return"No errors";return $.map((X)=>`${E}${X.instancePath} ${X.message}`).reduce((X,G)=>X+w+G)}$dataMetaSchema($,w){let E=this.RULES.all;$=JSON.parse(JSON.stringify($));for(let X of w){let G=X.split("/").slice(1),J=$;for(let A of G)J=J[A];for(let A in E){let D=E[A];if(typeof D!="object")continue;let{$data:N}=D.definition,W=J[A];if(N&&W)J[A]=sQ(W)}}return $}_removeAllSchemas($,w){for(let E in $){let X=$[E];if(!w||w.test(E)){if(typeof X=="string")delete $[E];else if(X&&!X.meta)this._cache.delete(X.schema),delete $[E]}}}_addSchema($,w,E,X=this.opts.validateSchema,G=this.opts.addUsedSchema){let J,{schemaId:A}=this.opts;if(typeof $=="object")J=$[A];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof $!="boolean")throw Error("schema must be object or boolean");let D=this._cache.get($);if(D!==void 0)return D;E=(0,s6.normalizeId)(J||E);let N=s6.getSchemaRefs.call(this,$,E);if(D=new l6.SchemaEnv({schema:$,schemaId:A,meta:w,baseId:E,localRefs:N}),this._cache.set(D.schema,D),G&&!E.startsWith("#")){if(E)this._checkUnique(E);this.refs[E]=D}if(X)this.validateSchema($,!0);return D}_checkUnique($){if(this.schemas[$]||this.refs[$])throw Error(`schema with key or id "${$}" already exists`)}_compileSchemaEnv($){if($.meta)this._compileMetaSchema($);else l6.compileSchema.call(this,$);if(!$.validate)throw Error("ajv implementation error");return $.validate}_compileMetaSchema($){let w=this.opts;this.opts=this._metaOpts;try{l6.compileSchema.call(this,$)}finally{this.opts=w}}}DD.ValidationError=wn.default;DD.MissingRefError=dQ.default;bw.default=DD;function tQ($,w,E,X="error"){for(let G in $){let J=G;if(J in w)this.logger[X](`${E}: option ${G}. ${$[J]}`)}}function iQ($){return $=(0,s6.normalizeId)($),this.schemas[$]||this.refs[$]}function On(){let $=this.opts.schemas;if(!$)return;if(Array.isArray($))this.addSchema($);else for(let w in $)this.addSchema($[w],w)}function Un(){for(let $ in this.opts.formats){let w=this.opts.formats[$];if(w)this.addFormat($,w)}}function Yn($){if(Array.isArray($)){this.addVocabulary($);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let w in $){let E=$[w];if(!E.keyword)E.keyword=w;this.addKeyword(E)}}function Hn(){let $={...this.opts};for(let w of Jn)delete $[w];return $}var Ln={log(){},warn(){},error(){}};function Fn($){if($===!1)return Ln;if($===void 0)return console;if($.log&&$.warn&&$.error)return $;throw Error("logger must implement log, warn and error methods")}var jn=/^[a-z_$][a-z0-9_$:-]*$/i;function Mn($,w){let{RULES:E}=this;if((0,wO.eachItem)($,(X)=>{if(E.keywords[X])throw Error(`Keyword ${X} is already defined`);if(!jn.test(X))throw Error(`Keyword ${X} has invalid name`)}),!w)return;if(w.$data&&!(("code"in w)||("validate"in w)))throw Error('$data keyword must have "code" or "validate" function')}function $O($,w,E){var X;let G=w===null||w===void 0?void 0:w.post;if(E&&G)throw Error('keyword with "post" flag cannot have "type"');let{RULES:J}=this,A=G?J.post:J.rules.find(({type:N})=>N===E);if(!A)A={type:E,rules:[]},J.rules.push(A);if(J.keywords[$]=!0,!w)return;let D={keyword:$,definition:{...w,type:(0,AD.getJSONTypes)(w.type),schemaType:(0,AD.getJSONTypes)(w.schemaType)}};if(w.before)Rn.call(this,A,D,w.before);else A.rules.push(D);J.all[$]=D,(X=w.implements)===null||X===void 0||X.forEach((N)=>this.addKeyword(N))}function Rn($,w,E){let X=$.rules.findIndex((G)=>G.keyword===E);if(X>=0)$.rules.splice(X,0,w);else $.rules.push(w),this.logger.warn(`rule ${E} is not defined`)}function zn($){let{metaSchema:w}=$;if(w===void 0)return;if($.$data&&this.opts.$data)w=sQ(w);$.validateSchema=this.compile(w,!0)}var Tn={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function sQ($){return{anyOf:[$,Tn]}}});var $I=Z((eQ)=>{Object.defineProperty(eQ,"__esModule",{value:!0});var In={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};eQ.default=In});var AI=Z((GI)=>{Object.defineProperty(GI,"__esModule",{value:!0});GI.callRef=GI.getValidate=void 0;var Vn=t6(),wI=I1(),w1=W0(),dX=qw(),EI=wD(),ND=R0(),Pn={keyword:"$ref",schemaType:"string",code($){let{gen:w,schema:E,it:X}=$,{baseId:G,schemaEnv:J,validateName:A,opts:D,self:N}=X,{root:W}=J;if((E==="#"||E==="#/")&&G===W.baseId)return Y();let O=EI.resolveRef.call(N,W,G,E);if(O===void 0)throw new Vn.default(X.opts.uriResolver,G,E);if(O instanceof EI.SchemaEnv)return H(O);return L(O);function Y(){if(J===W)return WD($,A,J,J.$async);let F=w.scopeValue("root",{ref:W});return WD($,w1._`${F}.validate`,W,W.$async)}function H(F){let j=XI($,F);WD($,j,F,F.$async)}function L(F){let j=w.scopeValue("schema",D.code.source===!0?{ref:F,code:(0,w1.stringify)(F)}:{ref:F}),M=w.name("valid"),z=$.subschema({schema:F,dataTypes:[],schemaPath:w1.nil,topSchemaRef:j,errSchemaPath:E},M);$.mergeEvaluated(z),$.ok(M)}}};function XI($,w){let{gen:E}=$;return w.validate?E.scopeValue("validate",{ref:w.validate}):w1._`${E.scopeValue("wrapper",{ref:w})}.validate`}GI.getValidate=XI;function WD($,w,E,X){let{gen:G,it:J}=$,{allErrors:A,schemaEnv:D,opts:N}=J,W=N.passContext?dX.default.this:w1.nil;if(X)O();else Y();function O(){if(!D.$async)throw Error("async schema referenced by sync schema");let F=G.let("valid");G.try(()=>{if(G.code(w1._`await ${(0,wI.callValidateCode)($,w,W)}`),L(w),!A)G.assign(F,!0)},(j)=>{if(G.if(w1._`!(${j} instanceof ${J.ValidationError})`,()=>G.throw(j)),H(j),!A)G.assign(F,!1)}),$.ok(F)}function Y(){$.result((0,wI.callValidateCode)($,w,W),()=>L(w),()=>H(w))}function H(F){let j=w1._`${F}.errors`;G.assign(dX.default.vErrors,w1._`${dX.default.vErrors} === null ? ${j} : ${dX.default.vErrors}.concat(${j})`),G.assign(dX.default.errors,w1._`${dX.default.vErrors}.length`)}function L(F){var j;if(!J.opts.unevaluated)return;let M=(j=E===null||E===void 0?void 0:E.validate)===null||j===void 0?void 0:j.evaluated;if(J.props!==!0)if(M&&!M.dynamicProps){if(M.props!==void 0)J.props=ND.mergeEvaluated.props(G,M.props,J.props)}else{let z=G.var("props",w1._`${F}.evaluated.props`);J.props=ND.mergeEvaluated.props(G,z,J.props,w1.Name)}if(J.items!==!0)if(M&&!M.dynamicItems){if(M.items!==void 0)J.items=ND.mergeEvaluated.items(G,M.items,J.items)}else{let z=G.var("items",w1._`${F}.evaluated.items`);J.items=ND.mergeEvaluated.items(G,z,J.items,w1.Name)}}}GI.callRef=WD;GI.default=Pn});var NI=Z((DI)=>{Object.defineProperty(DI,"__esModule",{value:!0});var kn=$I(),bn=AI(),Zn=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",kn.default,bn.default];DI.default=Zn});var OI=Z((WI)=>{Object.defineProperty(WI,"__esModule",{value:!0});var OD=W0(),GE=OD.operators,UD={maximum:{okStr:"<=",ok:GE.LTE,fail:GE.GT},minimum:{okStr:">=",ok:GE.GTE,fail:GE.LT},exclusiveMaximum:{okStr:"<",ok:GE.LT,fail:GE.GTE},exclusiveMinimum:{okStr:">",ok:GE.GT,fail:GE.LTE}},_n={message:({keyword:$,schemaCode:w})=>OD.str`must be ${UD[$].okStr} ${w}`,params:({keyword:$,schemaCode:w})=>OD._`{comparison: ${UD[$].okStr}, limit: ${w}}`},vn={keyword:Object.keys(UD),type:"number",schemaType:"number",$data:!0,error:_n,code($){let{keyword:w,data:E,schemaCode:X}=$;$.fail$data(OD._`${E} ${UD[w].fail} ${X} || isNaN(${E})`)}};WI.default=vn});var YI=Z((UI)=>{Object.defineProperty(UI,"__esModule",{value:!0});var a6=W0(),xn={message:({schemaCode:$})=>a6.str`must be multiple of ${$}`,params:({schemaCode:$})=>a6._`{multipleOf: ${$}}`},yn={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:xn,code($){let{gen:w,data:E,schemaCode:X,it:G}=$,J=G.opts.multipleOfPrecision,A=w.let("res"),D=J?a6._`Math.abs(Math.round(${A}) - ${A}) > 1e-${J}`:a6._`${A} !== parseInt(${A})`;$.fail$data(a6._`(${X} === 0 || (${A} = ${E}/${X}, ${D}))`)}};UI.default=yn});var FI=Z((LI)=>{Object.defineProperty(LI,"__esModule",{value:!0});function HI($){let w=$.length,E=0,X=0,G;while(X<w)if(E++,G=$.charCodeAt(X++),G>=55296&&G<=56319&&X<w){if(G=$.charCodeAt(X),(G&64512)===56320)X++}return E}LI.default=HI;HI.code='require("ajv/dist/runtime/ucs2length").default'});var MI=Z((jI)=>{Object.defineProperty(jI,"__esModule",{value:!0});var _E=W0(),hn=R0(),cn=FI(),nn={message({keyword:$,schemaCode:w}){let E=$==="maxLength"?"more":"fewer";return _E.str`must NOT have ${E} than ${w} characters`},params:({schemaCode:$})=>_E._`{limit: ${$}}`},mn={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:nn,code($){let{keyword:w,data:E,schemaCode:X,it:G}=$,J=w==="maxLength"?_E.operators.GT:_E.operators.LT,A=G.opts.unicode===!1?_E._`${E}.length`:_E._`${(0,hn.useFunc)($.gen,cn.default)}(${E})`;$.fail$data(_E._`${A} ${J} ${X}`)}};jI.default=mn});var zI=Z((RI)=>{Object.defineProperty(RI,"__esModule",{value:!0});var pn=I1(),on=R0(),lX=W0(),tn={message:({schemaCode:$})=>lX.str`must match pattern "${$}"`,params:({schemaCode:$})=>lX._`{pattern: ${$}}`},dn={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:tn,code($){let{gen:w,data:E,$data:X,schema:G,schemaCode:J,it:A}=$,D=A.opts.unicodeRegExp?"u":"";if(X){let{regExp:N}=A.opts.code,W=N.code==="new RegExp"?lX._`new RegExp`:(0,on.useFunc)(w,N),O=w.let("valid");w.try(()=>w.assign(O,lX._`${W}(${J}, ${D}).test(${E})`),()=>w.assign(O,!1)),$.fail$data(lX._`!${O}`)}else{let N=(0,pn.usePattern)($,G);$.fail$data(lX._`!${N}.test(${E})`)}}};RI.default=dn});var BI=Z((TI)=>{Object.defineProperty(TI,"__esModule",{value:!0});var e6=W0(),sn={message({keyword:$,schemaCode:w}){let E=$==="maxProperties"?"more":"fewer";return e6.str`must NOT have ${E} than ${w} properties`},params:({schemaCode:$})=>e6._`{limit: ${$}}`},an={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:sn,code($){let{keyword:w,data:E,schemaCode:X}=$,G=w==="maxProperties"?e6.operators.GT:e6.operators.LT;$.fail$data(e6._`Object.keys(${E}).length ${G} ${X}`)}};TI.default=an});var II=Z((QI)=>{Object.defineProperty(QI,"__esModule",{value:!0});var $J=I1(),wJ=W0(),$m=R0(),wm={message:({params:{missingProperty:$}})=>wJ.str`must have required property '${$}'`,params:({params:{missingProperty:$}})=>wJ._`{missingProperty: ${$}}`},Em={keyword:"required",type:"object",schemaType:"array",$data:!0,error:wm,code($){let{gen:w,schema:E,schemaCode:X,data:G,$data:J,it:A}=$,{opts:D}=A;if(!J&&E.length===0)return;let N=E.length>=D.loopRequired;if(A.allErrors)W();else O();if(D.strictRequired){let L=$.parentSchema.properties,{definedProperties:F}=$.it;for(let j of E)if((L===null||L===void 0?void 0:L[j])===void 0&&!F.has(j)){let M=A.schemaEnv.baseId+A.errSchemaPath,z=`required property "${j}" is not defined at "${M}" (strictRequired)`;(0,$m.checkStrictMode)(A,z,A.opts.strictRequired)}}function W(){if(N||J)$.block$data(wJ.nil,Y);else for(let L of E)(0,$J.checkReportMissingProp)($,L)}function O(){let L=w.let("missing");if(N||J){let F=w.let("valid",!0);$.block$data(F,()=>H(L,F)),$.ok(F)}else w.if((0,$J.checkMissingProp)($,E,L)),(0,$J.reportMissingProp)($,L),w.else()}function Y(){w.forOf("prop",X,(L)=>{$.setParams({missingProperty:L}),w.if((0,$J.noPropertyInData)(w,G,L,D.ownProperties),()=>$.error())})}function H(L,F){$.setParams({missingProperty:L}),w.forOf(L,X,()=>{w.assign(F,(0,$J.propertyInData)(w,G,L,D.ownProperties)),w.if((0,wJ.not)(F),()=>{$.error(),w.break()})},wJ.nil)}}};QI.default=Em});var VI=Z((KI)=>{Object.defineProperty(KI,"__esModule",{value:!0});var EJ=W0(),Gm={message({keyword:$,schemaCode:w}){let E=$==="maxItems"?"more":"fewer";return EJ.str`must NOT have ${E} than ${w} items`},params:({schemaCode:$})=>EJ._`{limit: ${$}}`},Jm={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Gm,code($){let{keyword:w,data:E,schemaCode:X}=$,G=w==="maxItems"?EJ.operators.GT:EJ.operators.LT;$.fail$data(EJ._`${E}.length ${G} ${X}`)}};KI.default=Jm});var YD=Z((qI)=>{Object.defineProperty(qI,"__esModule",{value:!0});var PI=hW();PI.code='require("ajv/dist/runtime/equal").default';qI.default=PI});var kI=Z((SI)=>{Object.defineProperty(SI,"__esModule",{value:!0});var EO=n6(),K$=W0(),Nm=R0(),Wm=YD(),Om={message:({params:{i:$,j:w}})=>K$.str`must NOT have duplicate items (items ## ${w} and ${$} are identical)`,params:({params:{i:$,j:w}})=>K$._`{i: ${$}, j: ${w}}`},Um={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Om,code($){let{gen:w,data:E,$data:X,schema:G,parentSchema:J,schemaCode:A,it:D}=$;if(!X&&!G)return;let N=w.let("valid"),W=J.items?(0,EO.getSchemaTypes)(J.items):[];$.block$data(N,O,K$._`${A} === false`),$.ok(N);function O(){let F=w.let("i",K$._`${E}.length`),j=w.let("j");$.setParams({i:F,j}),w.assign(N,!0),w.if(K$._`${F} > 1`,()=>(Y()?H:L)(F,j))}function Y(){return W.length>0&&!W.some((F)=>F==="object"||F==="array")}function H(F,j){let M=w.name("item"),z=(0,EO.checkDataTypes)(W,M,D.opts.strictNumbers,EO.DataType.Wrong),B=w.const("indices",K$._`{}`);w.for(K$._`;${F}--;`,()=>{if(w.let(M,K$._`${E}[${F}]`),w.if(z,K$._`continue`),W.length>1)w.if(K$._`typeof ${M} == "string"`,K$._`${M} += "_"`);w.if(K$._`typeof ${B}[${M}] == "number"`,()=>{w.assign(j,K$._`${B}[${M}]`),$.error(),w.assign(N,!1).break()}).code(K$._`${B}[${M}] = ${F}`)})}function L(F,j){let M=(0,Nm.useFunc)(w,Wm.default),z=w.name("outer");w.label(z).for(K$._`;${F}--;`,()=>w.for(K$._`${j} = ${F}; ${j}--;`,()=>w.if(K$._`${M}(${E}[${F}], ${E}[${j}])`,()=>{$.error(),w.assign(N,!1).break(z)})))}}};SI.default=Um});var ZI=Z((bI)=>{Object.defineProperty(bI,"__esModule",{value:!0});var XO=W0(),Hm=R0(),Lm=YD(),Fm={message:"must be equal to constant",params:({schemaCode:$})=>XO._`{allowedValue: ${$}}`},jm={keyword:"const",$data:!0,error:Fm,code($){let{gen:w,data:E,$data:X,schemaCode:G,schema:J}=$;if(X||J&&typeof J=="object")$.fail$data(XO._`!${(0,Hm.useFunc)(w,Lm.default)}(${E}, ${G})`);else $.fail(XO._`${J} !== ${E}`)}};bI.default=jm});var _I=Z((CI)=>{Object.defineProperty(CI,"__esModule",{value:!0});var XJ=W0(),Rm=R0(),zm=YD(),Tm={message:"must be equal to one of the allowed values",params:({schemaCode:$})=>XJ._`{allowedValues: ${$}}`},Bm={keyword:"enum",schemaType:"array",$data:!0,error:Tm,code($){let{gen:w,data:E,$data:X,schema:G,schemaCode:J,it:A}=$;if(!X&&G.length===0)throw Error("enum must have non-empty array");let D=G.length>=A.opts.loopEnum,N,W=()=>N!==null&&N!==void 0?N:N=(0,Rm.useFunc)(w,zm.default),O;if(D||X)O=w.let("valid"),$.block$data(O,Y);else{if(!Array.isArray(G))throw Error("ajv implementation error");let L=w.const("vSchema",J);O=(0,XJ.or)(...G.map((F,j)=>H(L,j)))}$.pass(O);function Y(){w.assign(O,!1),w.forOf("v",J,(L)=>w.if(XJ._`${W()}(${E}, ${L})`,()=>w.assign(O,!0).break()))}function H(L,F){let j=G[F];return typeof j==="object"&&j!==null?XJ._`${W()}(${E}, ${L}[${F}])`:XJ._`${E} === ${j}`}}};CI.default=Bm});var fI=Z((vI)=>{Object.defineProperty(vI,"__esModule",{value:!0});var Im=OI(),Km=YI(),Vm=MI(),Pm=zI(),qm=BI(),Sm=II(),km=VI(),bm=kI(),Zm=ZI(),Cm=_I(),_m=[Im.default,Km.default,Vm.default,Pm.default,qm.default,Sm.default,km.default,bm.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Zm.default,Cm.default];vI.default=_m});var JO=Z((yI)=>{Object.defineProperty(yI,"__esModule",{value:!0});yI.validateAdditionalItems=void 0;var vE=W0(),GO=R0(),fm={message:({params:{len:$}})=>vE.str`must NOT have more than ${$} items`,params:({params:{len:$}})=>vE._`{limit: ${$}}`},xm={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:fm,code($){let{parentSchema:w,it:E}=$,{items:X}=w;if(!Array.isArray(X)){(0,GO.checkStrictMode)(E,'"additionalItems" is ignored when "items" is not an array of schemas');return}xI($,X)}};function xI($,w){let{gen:E,schema:X,data:G,keyword:J,it:A}=$;A.items=!0;let D=E.const("len",vE._`${G}.length`);if(X===!1)$.setParams({len:w.length}),$.pass(vE._`${D} <= ${w.length}`);else if(typeof X=="object"&&!(0,GO.alwaysValidSchema)(A,X)){let W=E.var("valid",vE._`${D} <= ${w.length}`);E.if((0,vE.not)(W),()=>N(W)),$.ok(W)}function N(W){E.forRange("i",w.length,D,(O)=>{if($.subschema({keyword:J,dataProp:O,dataPropType:GO.Type.Num},W),!A.allErrors)E.if((0,vE.not)(W),()=>E.break())})}}yI.validateAdditionalItems=xI;yI.default=xm});var AO=Z((cI)=>{Object.defineProperty(cI,"__esModule",{value:!0});cI.validateTuple=void 0;var uI=W0(),HD=R0(),gm=I1(),um={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code($){let{schema:w,it:E}=$;if(Array.isArray(w))return hI($,"additionalItems",w);if(E.items=!0,(0,HD.alwaysValidSchema)(E,w))return;$.ok((0,gm.validateArray)($))}};function hI($,w,E=$.schema){let{gen:X,parentSchema:G,data:J,keyword:A,it:D}=$;if(O(G),D.opts.unevaluated&&E.length&&D.items!==!0)D.items=HD.mergeEvaluated.items(X,E.length,D.items);let N=X.name("valid"),W=X.const("len",uI._`${J}.length`);E.forEach((Y,H)=>{if((0,HD.alwaysValidSchema)(D,Y))return;X.if(uI._`${W} > ${H}`,()=>$.subschema({keyword:A,schemaProp:H,dataProp:H},N)),$.ok(N)});function O(Y){let{opts:H,errSchemaPath:L}=D,F=E.length,j=F===Y.minItems&&(F===Y.maxItems||Y[w]===!1);if(H.strictTuples&&!j){let M=`"${A}" is ${F}-tuple, but minItems or maxItems/${w} are not specified or different at path "${L}"`;(0,HD.checkStrictMode)(D,M,H.strictTuples)}}}cI.validateTuple=hI;cI.default=um});var rI=Z((mI)=>{Object.defineProperty(mI,"__esModule",{value:!0});var cm=AO(),nm={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:($)=>(0,cm.validateTuple)($,"items")};mI.default=nm});var tI=Z((oI)=>{Object.defineProperty(oI,"__esModule",{value:!0});var pI=W0(),rm=R0(),pm=I1(),om=JO(),tm={message:({params:{len:$}})=>pI.str`must NOT have more than ${$} items`,params:({params:{len:$}})=>pI._`{limit: ${$}}`},im={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:tm,code($){let{schema:w,parentSchema:E,it:X}=$,{prefixItems:G}=E;if(X.items=!0,(0,rm.alwaysValidSchema)(X,w))return;if(G)(0,om.validateAdditionalItems)($,G);else $.ok((0,pm.validateArray)($))}};oI.default=im});var dI=Z((iI)=>{Object.defineProperty(iI,"__esModule",{value:!0});var K1=W0(),LD=R0(),lm={message:({params:{min:$,max:w}})=>w===void 0?K1.str`must contain at least ${$} valid item(s)`:K1.str`must contain at least ${$} and no more than ${w} valid item(s)`,params:({params:{min:$,max:w}})=>w===void 0?K1._`{minContains: ${$}}`:K1._`{minContains: ${$}, maxContains: ${w}}`},sm={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:lm,code($){let{gen:w,schema:E,parentSchema:X,data:G,it:J}=$,A,D,{minContains:N,maxContains:W}=X;if(J.opts.next)A=N===void 0?1:N,D=W;else A=1;let O=w.const("len",K1._`${G}.length`);if($.setParams({min:A,max:D}),D===void 0&&A===0){(0,LD.checkStrictMode)(J,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(D!==void 0&&A>D){(0,LD.checkStrictMode)(J,'"minContains" > "maxContains" is always invalid'),$.fail();return}if((0,LD.alwaysValidSchema)(J,E)){let j=K1._`${O} >= ${A}`;if(D!==void 0)j=K1._`${j} && ${O} <= ${D}`;$.pass(j);return}J.items=!0;let Y=w.name("valid");if(D===void 0&&A===1)L(Y,()=>w.if(Y,()=>w.break()));else if(A===0){if(w.let(Y,!0),D!==void 0)w.if(K1._`${G}.length > 0`,H)}else w.let(Y,!1),H();$.result(Y,()=>$.reset());function H(){let j=w.name("_valid"),M=w.let("count",0);L(j,()=>w.if(j,()=>F(M)))}function L(j,M){w.forRange("i",0,O,(z)=>{$.subschema({keyword:"contains",dataProp:z,dataPropType:LD.Type.Num,compositeRule:!0},j),M()})}function F(j){if(w.code(K1._`${j}++`),D===void 0)w.if(K1._`${j} >= ${A}`,()=>w.assign(Y,!0).break());else if(w.if(K1._`${j} > ${D}`,()=>w.assign(Y,!1).break()),A===1)w.assign(Y,!0);else w.if(K1._`${j} >= ${A}`,()=>w.assign(Y,!0))}}};iI.default=sm});var wK=Z((aI)=>{Object.defineProperty(aI,"__esModule",{value:!0});aI.validateSchemaDeps=aI.validatePropertyDeps=aI.error=void 0;var DO=W0(),em=R0(),GJ=I1();aI.error={message:({params:{property:$,depsCount:w,deps:E}})=>{let X=w===1?"property":"properties";return DO.str`must have ${X} ${E} when property ${$} is present`},params:({params:{property:$,depsCount:w,deps:E,missingProperty:X}})=>DO._`{property: ${$},
|
|
575
575
|
missingProperty: ${X},
|
|
576
576
|
depsCount: ${w},
|
|
577
|
-
deps: ${E}}`};var tm={keyword:"dependencies",type:"object",schemaType:"object",error:dI.error,code($){let[w,E]=im($);tI($,w),iI($,E)}};function im({schema:$}){let w={},E={};for(let X in $){if(X==="__proto__")continue;let G=Array.isArray($[X])?w:E;G[X]=$[X]}return[w,E]}function tI($,w=$.schema){let{gen:E,data:X,it:G}=$;if(Object.keys(w).length===0)return;let J=E.let("missing");for(let A in w){let D=w[A];if(D.length===0)continue;let N=(0,XJ.propertyInData)(E,X,A,G.opts.ownProperties);if($.setParams({property:A,depsCount:D.length,deps:D.join(", ")}),G.allErrors)E.if(N,()=>{for(let W of D)(0,XJ.checkReportMissingProp)($,W)});else E.if(GO._`${N} && (${(0,XJ.checkMissingProp)($,D,J)})`),(0,XJ.reportMissingProp)($,J),E.else()}}dI.validatePropertyDeps=tI;function iI($,w=$.schema){let{gen:E,data:X,keyword:G,it:J}=$,A=E.name("valid");for(let D in w){if((0,om.alwaysValidSchema)(J,w[D]))continue;E.if((0,XJ.propertyInData)(E,X,D,J.opts.ownProperties),()=>{let N=$.subschema({keyword:G,schemaProp:D},A);$.mergeValidEvaluated(N,A)},()=>E.var(A,!0)),$.ok(A)}}dI.validateSchemaDeps=iI;dI.default=tm});var wK=Z(($K)=>{Object.defineProperty($K,"__esModule",{value:!0});var eI=W0(),sm=R0(),am={message:"property name must be valid",params:({params:$})=>eI._`{propertyName: ${$.propertyName}}`},em={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:am,code($){let{gen:w,schema:E,data:X,it:G}=$;if((0,sm.alwaysValidSchema)(G,E))return;let J=w.name("valid");w.forIn("key",X,(A)=>{$.setParams({propertyName:A}),$.subschema({keyword:"propertyNames",data:A,dataTypes:["string"],propertyName:A,compositeRule:!0},J),w.if((0,eI.not)(J),()=>{if($.error(!0),!G.allErrors)w.break()})}),$.ok(J)}};$K.default=em});var JO=Z((EK)=>{Object.defineProperty(EK,"__esModule",{value:!0});var HD=I1(),r1=W0(),wr=qw(),LD=R0(),Er={message:"must NOT have additional properties",params:({params:$})=>r1._`{additionalProperty: ${$.additionalProperty}}`},Xr={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Er,code($){let{gen:w,schema:E,parentSchema:X,data:G,errsCount:J,it:A}=$;if(!J)throw Error("ajv implementation error");let{allErrors:D,opts:N}=A;if(A.props=!0,N.removeAdditional!=="all"&&(0,LD.alwaysValidSchema)(A,E))return;let W=(0,HD.allSchemaProperties)(X.properties),O=(0,HD.allSchemaProperties)(X.patternProperties);Y(),$.ok(r1._`${J} === ${wr.default.errors}`);function Y(){w.forIn("key",G,(M)=>{if(!W.length&&!O.length)F(M);else w.if(H(M),()=>F(M))})}function H(M){let z;if(W.length>8){let B=(0,LD.schemaRefOrVal)(A,X.properties,"properties");z=(0,HD.isOwnProperty)(w,B,M)}else if(W.length)z=(0,r1.or)(...W.map((B)=>r1._`${M} === ${B}`));else z=r1.nil;if(O.length)z=(0,r1.or)(z,...O.map((B)=>r1._`${(0,HD.usePattern)($,B)}.test(${M})`));return(0,r1.not)(z)}function L(M){w.code(r1._`delete ${G}[${M}]`)}function F(M){if(N.removeAdditional==="all"||N.removeAdditional&&E===!1){L(M);return}if(E===!1){if($.setParams({additionalProperty:M}),$.error(),!D)w.break();return}if(typeof E=="object"&&!(0,LD.alwaysValidSchema)(A,E)){let z=w.name("valid");if(N.removeAdditional==="failing")j(M,z,!1),w.if((0,r1.not)(z),()=>{$.reset(),L(M)});else if(j(M,z),!D)w.if((0,r1.not)(z),()=>w.break())}}function j(M,z,B){let Q={keyword:"additionalProperties",dataProp:M,dataPropType:LD.Type.Str};if(B===!1)Object.assign(Q,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(Q,z)}}};EK.default=Xr});var AK=Z((JK)=>{Object.defineProperty(JK,"__esModule",{value:!0});var Jr=p6(),XK=I1(),AO=R0(),GK=JO(),Ar={keyword:"properties",type:"object",schemaType:"object",code($){let{gen:w,schema:E,parentSchema:X,data:G,it:J}=$;if(J.opts.removeAdditional==="all"&&X.additionalProperties===void 0)GK.default.code(new Jr.KeywordCxt(J,GK.default,"additionalProperties"));let A=(0,XK.allSchemaProperties)(E);for(let Y of A)J.definedProperties.add(Y);if(J.opts.unevaluated&&A.length&&J.props!==!0)J.props=AO.mergeEvaluated.props(w,(0,AO.toHash)(A),J.props);let D=A.filter((Y)=>!(0,AO.alwaysValidSchema)(J,E[Y]));if(D.length===0)return;let N=w.name("valid");for(let Y of D){if(W(Y))O(Y);else{if(w.if((0,XK.propertyInData)(w,G,Y,J.opts.ownProperties)),O(Y),!J.allErrors)w.else().var(N,!0);w.endIf()}$.it.definedProperties.add(Y),$.ok(N)}function W(Y){return J.opts.useDefaults&&!J.compositeRule&&E[Y].default!==void 0}function O(Y){$.subschema({keyword:"properties",schemaProp:Y,dataProp:Y},N)}}};JK.default=Ar});var UK=Z((OK)=>{Object.defineProperty(OK,"__esModule",{value:!0});var DK=I1(),FD=W0(),NK=R0(),WK=R0(),Nr={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:w,schema:E,data:X,parentSchema:G,it:J}=$,{opts:A}=J,D=(0,DK.allSchemaProperties)(E),N=D.filter((j)=>(0,NK.alwaysValidSchema)(J,E[j]));if(D.length===0||N.length===D.length&&(!J.opts.unevaluated||J.props===!0))return;let W=A.strictSchema&&!A.allowMatchingProperties&&G.properties,O=w.name("valid");if(J.props!==!0&&!(J.props instanceof FD.Name))J.props=(0,WK.evaluatedPropsToName)(w,J.props);let{props:Y}=J;H();function H(){for(let j of D){if(W)L(j);if(J.allErrors)F(j);else w.var(O,!0),F(j),w.if(O)}}function L(j){for(let M in W)if(new RegExp(j).test(M))(0,NK.checkStrictMode)(J,`property ${M} matches pattern ${j} (use allowMatchingProperties)`)}function F(j){w.forIn("key",X,(M)=>{w.if(FD._`${(0,DK.usePattern)($,j)}.test(${M})`,()=>{let z=N.includes(j);if(!z)$.subschema({keyword:"patternProperties",schemaProp:j,dataProp:M,dataPropType:WK.Type.Str},O);if(J.opts.unevaluated&&Y!==!0)w.assign(FD._`${Y}[${M}]`,!0);else if(!z&&!J.allErrors)w.if((0,FD.not)(O),()=>w.break())})})}}};OK.default=Nr});var HK=Z((YK)=>{Object.defineProperty(YK,"__esModule",{value:!0});var Or=R0(),Ur={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code($){let{gen:w,schema:E,it:X}=$;if((0,Or.alwaysValidSchema)(X,E)){$.fail();return}let G=w.name("valid");$.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},G),$.failResult(G,()=>$.reset(),()=>$.error())},error:{message:"must NOT be valid"}};YK.default=Ur});var FK=Z((LK)=>{Object.defineProperty(LK,"__esModule",{value:!0});var Hr=I1(),Lr={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Hr.validateUnion,error:{message:"must match a schema in anyOf"}};LK.default=Lr});var MK=Z((jK)=>{Object.defineProperty(jK,"__esModule",{value:!0});var jD=W0(),jr=R0(),Mr={message:"must match exactly one schema in oneOf",params:({params:$})=>jD._`{passingSchemas: ${$.passing}}`},Rr={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Mr,code($){let{gen:w,schema:E,parentSchema:X,it:G}=$;if(!Array.isArray(E))throw Error("ajv implementation error");if(G.opts.discriminator&&X.discriminator)return;let J=E,A=w.let("valid",!1),D=w.let("passing",null),N=w.name("_valid");$.setParams({passing:D}),w.block(W),$.result(A,()=>$.reset(),()=>$.error(!0));function W(){J.forEach((O,Y)=>{let H;if((0,jr.alwaysValidSchema)(G,O))w.var(N,!0);else H=$.subschema({keyword:"oneOf",schemaProp:Y,compositeRule:!0},N);if(Y>0)w.if(jD._`${N} && ${A}`).assign(A,!1).assign(D,jD._`[${D}, ${Y}]`).else();w.if(N,()=>{if(w.assign(A,!0),w.assign(D,Y),H)$.mergeEvaluated(H,jD.Name)})})}}};jK.default=Rr});var zK=Z((RK)=>{Object.defineProperty(RK,"__esModule",{value:!0});var Tr=R0(),Br={keyword:"allOf",schemaType:"array",code($){let{gen:w,schema:E,it:X}=$;if(!Array.isArray(E))throw Error("ajv implementation error");let G=w.name("valid");E.forEach((J,A)=>{if((0,Tr.alwaysValidSchema)(X,J))return;let D=$.subschema({keyword:"allOf",schemaProp:A},G);$.ok(G),$.mergeEvaluated(D)})}};RK.default=Br});var IK=Z((QK)=>{Object.defineProperty(QK,"__esModule",{value:!0});var MD=W0(),BK=R0(),Ir={message:({params:$})=>MD.str`must match "${$.ifClause}" schema`,params:({params:$})=>MD._`{failingKeyword: ${$.ifClause}}`},Kr={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Ir,code($){let{gen:w,parentSchema:E,it:X}=$;if(E.then===void 0&&E.else===void 0)(0,BK.checkStrictMode)(X,'"if" without "then" and "else" is ignored');let G=TK(X,"then"),J=TK(X,"else");if(!G&&!J)return;let A=w.let("valid",!0),D=w.name("_valid");if(N(),$.reset(),G&&J){let O=w.let("ifClause");$.setParams({ifClause:O}),w.if(D,W("then",O),W("else",O))}else if(G)w.if(D,W("then"));else w.if((0,MD.not)(D),W("else"));$.pass(A,()=>$.error(!0));function N(){let O=$.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},D);$.mergeEvaluated(O)}function W(O,Y){return()=>{let H=$.subschema({keyword:O},D);if(w.assign(A,D),$.mergeValidEvaluated(H,A),Y)w.assign(Y,MD._`${O}`);else $.setParams({ifClause:O})}}}};function TK($,w){let E=$.schema[w];return E!==void 0&&!(0,BK.alwaysValidSchema)($,E)}QK.default=Kr});var VK=Z((KK)=>{Object.defineProperty(KK,"__esModule",{value:!0});var Pr=R0(),qr={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:$,parentSchema:w,it:E}){if(w.if===void 0)(0,Pr.checkStrictMode)(E,`"${$}" without "if" is ignored`)}};KK.default=qr});var qK=Z((PK)=>{Object.defineProperty(PK,"__esModule",{value:!0});var kr=EO(),br=cI(),Zr=XO(),Cr=rI(),_r=oI(),vr=aI(),fr=wK(),xr=JO(),yr=AK(),gr=UK(),ur=HK(),hr=FK(),cr=MK(),nr=zK(),mr=IK(),rr=VK();function pr($=!1){let w=[ur.default,hr.default,cr.default,nr.default,mr.default,rr.default,fr.default,xr.default,vr.default,yr.default,gr.default];if($)w.push(br.default,Cr.default);else w.push(kr.default,Zr.default);return w.push(_r.default),w}PK.default=pr});var kK=Z((SK)=>{Object.defineProperty(SK,"__esModule",{value:!0});var J$=W0(),tr={message:({schemaCode:$})=>J$.str`must match format "${$}"`,params:({schemaCode:$})=>J$._`{format: ${$}}`},ir={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:tr,code($,w){let{gen:E,data:X,$data:G,schema:J,schemaCode:A,it:D}=$,{opts:N,errSchemaPath:W,schemaEnv:O,self:Y}=D;if(!N.validateFormats)return;if(G)H();else L();function H(){let F=E.scopeValue("formats",{ref:Y.formats,code:N.code.formats}),j=E.const("fDef",J$._`${F}[${A}]`),M=E.let("fType"),z=E.let("format");E.if(J$._`typeof ${j} == "object" && !(${j} instanceof RegExp)`,()=>E.assign(M,J$._`${j}.type || "string"`).assign(z,J$._`${j}.validate`),()=>E.assign(M,J$._`"string"`).assign(z,j)),$.fail$data((0,J$.or)(B(),Q()));function B(){if(N.strictSchema===!1)return J$.nil;return J$._`${A} && !${z}`}function Q(){let k=O.$async?J$._`(${j}.async ? await ${z}(${X}) : ${z}(${X}))`:J$._`${z}(${X})`,v=J$._`(typeof ${z} == "function" ? ${k} : ${z}.test(${X}))`;return J$._`${z} && ${z} !== true && ${M} === ${w} && !${v}`}}function L(){let F=Y.formats[J];if(!F){B();return}if(F===!0)return;let[j,M,z]=Q(F);if(j===w)$.pass(k());function B(){if(N.strictSchema===!1){Y.logger.warn(v());return}throw Error(v());function v(){return`unknown format "${J}" ignored in schema at path "${W}"`}}function Q(v){let C=v instanceof RegExp?(0,J$.regexpCode)(v):N.code.formats?J$._`${N.code.formats}${(0,J$.getProperty)(J)}`:void 0,n=E.scopeValue("formats",{key:J,ref:v,code:C});if(typeof v=="object"&&!(v instanceof RegExp))return[v.type||"string",v.validate,J$._`${n}.validate`];return["string",v,n]}function k(){if(typeof F=="object"&&!(F instanceof RegExp)&&F.async){if(!O.$async)throw Error("async format in sync schema");return J$._`await ${z}(${X})`}return typeof M=="function"?J$._`${z}(${X})`:J$._`${z}.test(${X})`}}}};SK.default=ir});var ZK=Z((bK)=>{Object.defineProperty(bK,"__esModule",{value:!0});var lr=kK(),sr=[lr.default];bK.default=sr});var vK=Z((CK)=>{Object.defineProperty(CK,"__esModule",{value:!0});CK.contentVocabulary=CK.metadataVocabulary=void 0;CK.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];CK.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var yK=Z((xK)=>{Object.defineProperty(xK,"__esModule",{value:!0});var $p=JI(),wp=CI(),Ep=qK(),Xp=ZK(),fK=vK(),Gp=[$p.default,wp.default,(0,Ep.default)(),Xp.default,fK.metadataVocabulary,fK.contentVocabulary];xK.default=Gp});var cK=Z((uK)=>{Object.defineProperty(uK,"__esModule",{value:!0});uK.DiscrError=void 0;var gK;(function($){$.Tag="tag",$.Mapping="mapping"})(gK||(uK.DiscrError=gK={}))});var rK=Z((mK)=>{Object.defineProperty(mK,"__esModule",{value:!0});var lX=W0(),DO=cK(),nK=e4(),Ap=o6(),Dp=R0(),Np={message:({params:{discrError:$,tagName:w}})=>$===DO.DiscrError.Tag?`tag "${w}" must be string`:`value of tag "${w}" must be in oneOf`,params:({params:{discrError:$,tag:w,tagName:E}})=>lX._`{error: ${$}, tag: ${E}, tagValue: ${w}}`},Wp={keyword:"discriminator",type:"object",schemaType:"object",error:Np,code($){let{gen:w,data:E,schema:X,parentSchema:G,it:J}=$,{oneOf:A}=G;if(!J.opts.discriminator)throw Error("discriminator: requires discriminator option");let D=X.propertyName;if(typeof D!="string")throw Error("discriminator: requires propertyName");if(X.mapping)throw Error("discriminator: mapping is not supported");if(!A)throw Error("discriminator: requires oneOf keyword");let N=w.let("valid",!1),W=w.const("tag",lX._`${E}${(0,lX.getProperty)(D)}`);w.if(lX._`typeof ${W} == "string"`,()=>O(),()=>$.error(!1,{discrError:DO.DiscrError.Tag,tag:W,tagName:D})),$.ok(N);function O(){let L=H();w.if(!1);for(let F in L)w.elseIf(lX._`${W} === ${F}`),w.assign(N,Y(L[F]));w.else(),$.error(!1,{discrError:DO.DiscrError.Mapping,tag:W,tagName:D}),w.endIf()}function Y(L){let F=w.name("valid"),j=$.subschema({keyword:"oneOf",schemaProp:L},F);return $.mergeEvaluated(j,lX.Name),F}function H(){var L;let F={},j=z(G),M=!0;for(let k=0;k<A.length;k++){let v=A[k];if((v===null||v===void 0?void 0:v.$ref)&&!(0,Dp.schemaHasRulesButRef)(v,J.self.RULES)){let n=v.$ref;if(v=nK.resolveRef.call(J.self,J.schemaEnv.root,J.baseId,n),v instanceof nK.SchemaEnv)v=v.schema;if(v===void 0)throw new Ap.default(J.opts.uriResolver,J.baseId,n)}let C=(L=v===null||v===void 0?void 0:v.properties)===null||L===void 0?void 0:L[D];if(typeof C!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${D}"`);M=M&&(j||z(v)),B(C,k)}if(!M)throw Error(`discriminator: "${D}" must be required`);return F;function z({required:k}){return Array.isArray(k)&&k.includes(D)}function B(k,v){if(k.const)Q(k.const,v);else if(k.enum)for(let C of k.enum)Q(C,v);else throw Error(`discriminator: "properties/${D}" must have "const" or "enum"`)}function Q(k,v){if(typeof k!="string"||k in F)throw Error(`discriminator: "${D}" values must be unique strings`);F[k]=v}}}};mK.default=Wp});var pK=Z((yN0,Up)=>{Up.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var WO=Z((E1,NO)=>{Object.defineProperty(E1,"__esModule",{value:!0});E1.MissingRefError=E1.ValidationError=E1.CodeGen=E1.Name=E1.nil=E1.stringify=E1.str=E1._=E1.KeywordCxt=E1.Ajv=void 0;var Yp=dQ(),Hp=yK(),Lp=rK(),oK=pK(),Fp=["/properties"],RD="http://json-schema.org/draft-07/schema";class GJ extends Yp.default{_addVocabularies(){if(super._addVocabularies(),Hp.default.forEach(($)=>this.addVocabulary($)),this.opts.discriminator)this.addKeyword(Lp.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let $=this.opts.$data?this.$dataMetaSchema(oK,Fp):oK;this.addMetaSchema($,RD,!1),this.refs["http://json-schema.org/schema"]=RD}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(RD)?RD:void 0)}}E1.Ajv=GJ;NO.exports=E1=GJ;NO.exports.Ajv=GJ;Object.defineProperty(E1,"__esModule",{value:!0});E1.default=GJ;var jp=p6();Object.defineProperty(E1,"KeywordCxt",{enumerable:!0,get:function(){return jp.KeywordCxt}});var sX=W0();Object.defineProperty(E1,"_",{enumerable:!0,get:function(){return sX._}});Object.defineProperty(E1,"str",{enumerable:!0,get:function(){return sX.str}});Object.defineProperty(E1,"stringify",{enumerable:!0,get:function(){return sX.stringify}});Object.defineProperty(E1,"nil",{enumerable:!0,get:function(){return sX.nil}});Object.defineProperty(E1,"Name",{enumerable:!0,get:function(){return sX.Name}});Object.defineProperty(E1,"CodeGen",{enumerable:!0,get:function(){return sX.CodeGen}});var Mp=s4();Object.defineProperty(E1,"ValidationError",{enumerable:!0,get:function(){return Mp.default}});var Rp=o6();Object.defineProperty(E1,"MissingRefError",{enumerable:!0,get:function(){return Rp.default}})});var EV=Z(($V)=>{Object.defineProperty($V,"__esModule",{value:!0});$V.formatNames=$V.fastFormats=$V.fullFormats=void 0;function Nw($,w){return{validate:$,compare:w}}$V.fullFormats={date:Nw(lK,HO),time:Nw(UO(!0),LO),"date-time":Nw(tK(!0),aK),"iso-time":Nw(UO(),sK),"iso-date-time":Nw(tK(),eK),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Pp,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:_p,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:qp,int32:{type:"number",validate:bp},int64:{type:"number",validate:Zp},float:{type:"number",validate:dK},double:{type:"number",validate:dK},password:!0,binary:!0};$V.fastFormats={...$V.fullFormats,date:Nw(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,HO),time:Nw(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,LO),"date-time":Nw(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,aK),"iso-time":Nw(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,sK),"iso-date-time":Nw(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,eK),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};$V.formatNames=Object.keys($V.fullFormats);function Bp($){return $%4===0&&($%100!==0||$%400===0)}var Qp=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Ip=[0,31,28,31,30,31,30,31,31,30,31,30,31];function lK($){let w=Qp.exec($);if(!w)return!1;let E=+w[1],X=+w[2],G=+w[3];return X>=1&&X<=12&&G>=1&&G<=(X===2&&Bp(E)?29:Ip[X])}function HO($,w){if(!($&&w))return;if($>w)return 1;if($<w)return-1;return 0}var OO=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function UO($){return function(E){let X=OO.exec(E);if(!X)return!1;let G=+X[1],J=+X[2],A=+X[3],D=X[4],N=X[5]==="-"?-1:1,W=+(X[6]||0),O=+(X[7]||0);if(W>23||O>59||$&&!D)return!1;if(G<=23&&J<=59&&A<60)return!0;let Y=J-O*N,H=G-W*N-(Y<0?1:0);return(H===23||H===-1)&&(Y===59||Y===-1)&&A<61}}function LO($,w){if(!($&&w))return;let E=new Date("2020-01-01T"+$).valueOf(),X=new Date("2020-01-01T"+w).valueOf();if(!(E&&X))return;return E-X}function sK($,w){if(!($&&w))return;let E=OO.exec($),X=OO.exec(w);if(!(E&&X))return;if($=E[1]+E[2]+E[3],w=X[1]+X[2]+X[3],$>w)return 1;if($<w)return-1;return 0}var YO=/t|\s/i;function tK($){let w=UO($);return function(X){let G=X.split(YO);return G.length===2&&lK(G[0])&&w(G[1])}}function aK($,w){if(!($&&w))return;let E=new Date($).valueOf(),X=new Date(w).valueOf();if(!(E&&X))return;return E-X}function eK($,w){if(!($&&w))return;let[E,X]=$.split(YO),[G,J]=w.split(YO),A=HO(E,G);if(A===void 0)return;return A||LO(X,J)}var Kp=/\/|:/,Vp=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function Pp($){return Kp.test($)&&Vp.test($)}var iK=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function qp($){return iK.lastIndex=0,iK.test($)}var Sp=-2147483648,kp=2147483647;function bp($){return Number.isInteger($)&&$<=kp&&$>=Sp}function Zp($){return Number.isInteger($)}function dK(){return!0}var Cp=/[^\\]\\Z/;function _p($){if(Cp.test($))return!1;try{return new RegExp($),!0}catch(w){return!1}}});var GV=Z((XV)=>{Object.defineProperty(XV,"__esModule",{value:!0});XV.formatLimitDefinition=void 0;var fp=WO(),p1=W0(),JE=p1.operators,zD={formatMaximum:{okStr:"<=",ok:JE.LTE,fail:JE.GT},formatMinimum:{okStr:">=",ok:JE.GTE,fail:JE.LT},formatExclusiveMaximum:{okStr:"<",ok:JE.LT,fail:JE.GTE},formatExclusiveMinimum:{okStr:">",ok:JE.GT,fail:JE.LTE}},xp={message:({keyword:$,schemaCode:w})=>p1.str`should be ${zD[$].okStr} ${w}`,params:({keyword:$,schemaCode:w})=>p1._`{comparison: ${zD[$].okStr}, limit: ${w}}`};XV.formatLimitDefinition={keyword:Object.keys(zD),type:"string",schemaType:"string",$data:!0,error:xp,code($){let{gen:w,data:E,schemaCode:X,keyword:G,it:J}=$,{opts:A,self:D}=J;if(!A.validateFormats)return;let N=new fp.KeywordCxt(J,D.RULES.all.format.definition,"format");if(N.$data)W();else O();function W(){let H=w.scopeValue("formats",{ref:D.formats,code:A.code.formats}),L=w.const("fmt",p1._`${H}[${N.schemaCode}]`);$.fail$data((0,p1.or)(p1._`typeof ${L} != "object"`,p1._`${L} instanceof RegExp`,p1._`typeof ${L}.compare != "function"`,Y(L)))}function O(){let H=N.schema,L=D.formats[H];if(!L||L===!0)return;if(typeof L!="object"||L instanceof RegExp||typeof L.compare!="function")throw Error(`"${G}": format "${H}" does not define "compare" function`);let F=w.scopeValue("formats",{key:H,ref:L,code:A.code.formats?p1._`${A.code.formats}${(0,p1.getProperty)(H)}`:void 0});$.fail$data(Y(F))}function Y(H){return p1._`${H}.compare(${E}, ${X}) ${zD[G].fail} 0`}},dependencies:["format"]};var yp=($)=>{return $.addKeyword(XV.formatLimitDefinition),$};XV.default=yp});var NV=Z((JJ,DV)=>{Object.defineProperty(JJ,"__esModule",{value:!0});var aX=EV(),up=GV(),MO=W0(),JV=new MO.Name("fullFormats"),hp=new MO.Name("fastFormats"),RO=($,w={keywords:!0})=>{if(Array.isArray(w))return AV($,w,aX.fullFormats,JV),$;let[E,X]=w.mode==="fast"?[aX.fastFormats,hp]:[aX.fullFormats,JV],G=w.formats||aX.formatNames;if(AV($,G,E,X),w.keywords)(0,up.default)($);return $};RO.get=($,w="full")=>{let X=(w==="fast"?aX.fastFormats:aX.fullFormats)[$];if(!X)throw Error(`Unknown format "${$}"`);return X};function AV($,w,E,X){var G,J;(G=(J=$.opts.code).formats)!==null&&G!==void 0||(J.formats=MO._`require("ajv-formats/dist/formats").${X}`);for(let A of w)$.addFormat(A,E[A])}DV.exports=JJ=RO;Object.defineProperty(JJ,"__esModule",{value:!0});JJ.default=RO});function cp(){let $=new WV.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return OV.default($),$}class zO{constructor($){this._ajv=$??cp()}getValidator($){let w="$id"in $&&typeof $.$id==="string"?this._ajv.getSchema($.$id)??this._ajv.compile($):this._ajv.compile($);return(E)=>{if(w(E))return{valid:!0,data:E,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(w.errors)}}}}var WV,OV;var UV=R(()=>{WV=AJ(WO(),1),OV=AJ(NV(),1)});class TO{constructor($){this._server=$}requestStream($,w,E){return this._server.requestStream($,w,E)}createMessageStream($,w){let E=this._server.getClientCapabilities();if(($.tools||$.toolChoice)&&!E?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if($.messages.length>0){let X=$.messages[$.messages.length-1],G=Array.isArray(X.content)?X.content:[X.content],J=G.some((W)=>W.type==="tool_result"),A=$.messages.length>1?$.messages[$.messages.length-2]:void 0,D=A?Array.isArray(A.content)?A.content:[A.content]:[],N=D.some((W)=>W.type==="tool_use");if(J){if(G.some((W)=>W.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!N)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(N){let W=new Set(D.filter((Y)=>Y.type==="tool_use").map((Y)=>Y.id)),O=new Set(G.filter((Y)=>Y.type==="tool_result").map((Y)=>Y.toolUseId));if(W.size!==O.size||![...W].every((Y)=>O.has(Y)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:$},f6,w)}elicitInputStream($,w){let E=this._server.getClientCapabilities(),X=$.mode??"form";switch(X){case"url":{if(!E?.elicitation?.url)throw Error("Client does not support url elicitation.");break}case"form":{if(!E?.elicitation?.form)throw Error("Client does not support form elicitation.");break}}let G=X==="form"&&$.mode===void 0?{...$,mode:"form"}:$;return this.requestStream({method:"elicitation/create",params:G},uX,w)}async getTask($,w){return this._server.getTask({taskId:$},w)}async getTaskResult($,w,E){return this._server.getTaskResult({taskId:$},w,E)}async listTasks($,w){return this._server.listTasks($?{cursor:$}:void 0,w)}async cancelTask($,w){return this._server.cancelTask({taskId:$},w)}}var YV=R(()=>{hX()});function HV($,w,E){if(!$)throw Error(`${E} does not support task creation (required for ${w})`);switch(w){case"tools/call":if(!$.tools?.call)throw Error(`${E} does not support task creation for tools/call (required for ${w})`);break;default:break}}function LV($,w,E){if(!$)throw Error(`${E} does not support task creation (required for ${w})`);switch(w){case"sampling/createMessage":if(!$.sampling?.createMessage)throw Error(`${E} does not support task creation for sampling/createMessage (required for ${w})`);break;case"elicitation/create":if(!$.elicitation?.create)throw Error(`${E} does not support task creation for elicitation/create (required for ${w})`);break;default:break}}var BO;var FV=R(()=>{CT();hX();UV();F4();YV();BO=class BO extends FW{constructor($,w){super(w);if(this._serverInfo=$,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(v6.options.map((E,X)=>[E,X])),this.isMessageIgnored=(E,X)=>{let G=this._loggingLevels.get(X);return G?this.LOG_LEVEL_SEVERITY.get(E)<this.LOG_LEVEL_SEVERITY.get(G):!1},this._capabilities=w?.capabilities??{},this._instructions=w?.instructions,this._jsonSchemaValidator=w?.jsonSchemaValidator??new zO,this.setRequestHandler(C5,(E)=>this._oninitialize(E)),this.setNotificationHandler(_5,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(c5,async(E,X)=>{let G=X.sessionId||X.requestInfo?.headers["mcp-session-id"]||void 0,{level:J}=E.params,A=v6.safeParse(J);if(A.success)this._loggingLevels.set(G,A.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new TO(this)};return this._experimental}registerCapabilities($){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=ZT(this._capabilities,$)}setRequestHandler($,w){let X=L4($)?.method;if(!X)throw Error("Schema is missing a method literal");let G;if(fX(X)){let A=X;G=A._zod?.def?.value??A.value}else{let A=X;G=A._def?.value??A.value}if(typeof G!=="string")throw Error("Schema method literal must be a string");if(G==="tools/call"){let A=async(D,N)=>{let W=lw(_6,D);if(!W.success){let L=W.error instanceof Error?W.error.message:String(W.error);throw new A0(L0.InvalidParams,`Invalid tools/call request: ${L}`)}let{params:O}=W.data,Y=await Promise.resolve(w(D,N));if(O.task){let L=lw(yX,Y);if(!L.success){let F=L.error instanceof Error?L.error.message:String(L.error);throw new A0(L0.InvalidParams,`Invalid task creation result: ${F}`)}return L.data}let H=lw(Z4,Y);if(!H.success){let L=H.error instanceof Error?H.error.message:String(H.error);throw new A0(L0.InvalidParams,`Invalid tools/call result: ${L}`)}return H.data};return super.setRequestHandler($,A)}return super.setRequestHandler($,w)}assertCapabilityForMethod($){switch($){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${$})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${$})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${$})`);break;case"ping":break}}assertNotificationCapability($){switch($){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${$})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${$})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${$})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${$})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${$})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability($){if(!this._capabilities)return;switch($){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${$})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${$})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${$})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${$})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${$})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${$})`);break;case"ping":case"initialize":break}}assertTaskCapability($){LV(this._clientCapabilities?.tasks?.requests,$,"Client")}assertTaskHandlerCapability($){if(!this._capabilities)return;HV(this._capabilities.tasks?.requests,$,"Server")}async _oninitialize($){let w=$.params.protocolVersion;return this._clientCapabilities=$.params.capabilities,this._clientVersion=$.params.clientInfo,{protocolVersion:OT.includes(w)?w:q5,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},B4)}async createMessage($,w){if($.tools||$.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if($.messages.length>0){let E=$.messages[$.messages.length-1],X=Array.isArray(E.content)?E.content:[E.content],G=X.some((N)=>N.type==="tool_result"),J=$.messages.length>1?$.messages[$.messages.length-2]:void 0,A=J?Array.isArray(J.content)?J.content:[J.content]:[],D=A.some((N)=>N.type==="tool_use");if(G){if(X.some((N)=>N.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!D)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(D){let N=new Set(A.filter((O)=>O.type==="tool_use").map((O)=>O.id)),W=new Set(X.filter((O)=>O.type==="tool_result").map((O)=>O.toolUseId));if(N.size!==W.size||![...N].every((O)=>W.has(O)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if($.tools)return this.request({method:"sampling/createMessage",params:$},n5,w);return this.request({method:"sampling/createMessage",params:$},f6,w)}async elicitInput($,w){switch($.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let X=$;return this.request({method:"elicitation/create",params:X},uX,w)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let X=$.mode==="form"?$:{...$,mode:"form"},G=await this.request({method:"elicitation/create",params:X},uX,w);if(G.action==="accept"&&G.content&&X.requestedSchema)try{let A=this._jsonSchemaValidator.getValidator(X.requestedSchema)(G.content);if(!A.valid)throw new A0(L0.InvalidParams,`Elicitation response content does not match requested schema: ${A.errorMessage}`)}catch(J){if(J instanceof A0)throw J;throw new A0(L0.InternalError,`Error validating elicitation response: ${J instanceof Error?J.message:String(J)}`)}return G}}}createElicitationCompletionNotifier($,w){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:$}},w)}async listRoots($,w){return this.request({method:"roots/list",params:$},m5,w)}async sendLoggingMessage($,w){if(this._capabilities.logging){if(!this.isMessageIgnored($.level,w))return this.notification({method:"notifications/message",params:$})}}async sendResourceUpdated($){return this.notification({method:"notifications/resources/updated",params:$})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}});class QO{append($){this._buffer=this._buffer?Buffer.concat([this._buffer,$]):$}readMessage(){if(!this._buffer)return null;let $=this._buffer.indexOf(`
|
|
578
|
-
`);if($===-1)return null;let w=this._buffer.toString("utf8",0,$).replace(/\r$/,"");return this._buffer=this._buffer.subarray($+1),
|
|
579
|
-
`}var MV=R(()=>{hX()});import RV from"process";class IO{constructor($=RV.stdin,w=RV.stdout){this._stdin=$,this._stdout=w,this._readBuffer=new QO,this._started=!1,this._ondata=(E)=>{this._readBuffer.append(E),this.processReadBuffer()},this._onerror=(E)=>{this.onerror?.(E)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let $=this._readBuffer.readMessage();if($===null)break;this.onmessage?.($)}catch($){this.onerror?.($)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send($){return new Promise((w)=>{let E=jV($);if(this._stdout.write(E))w();else this._stdout.once("drain",w)})}}var zV=R(()=>{MV()});function eX($){let w=$._def,E=w.typeName;if(E==="ZodObject"){let X=w.shape(),G={},J=[];for(let[A,D]of Object.entries(X)){G[A]=eX(D);let N=D._def;if(N.typeName!=="ZodOptional"&&N.typeName!=="ZodDefault")J.push(A)}return{type:"object",properties:G,...J.length?{required:J}:{}}}if(E==="ZodString")return{type:"string"};if(E==="ZodNumber")return{type:"number"};if(E==="ZodBoolean")return{type:"boolean"};if(E==="ZodArray")return{type:"array",items:eX(w.type)};if(E==="ZodEnum")return{type:"string",enum:w.values};if(E==="ZodOptional"||E==="ZodDefault")return eX(w.innerType);if(E==="ZodUnion")return{oneOf:w.options.map(eX)};return{}}function TV(){let $=new BO({name:"orc",version:"0.0.1"},{capabilities:{tools:{}}});return $.setRequestHandler(h5,async()=>({tools:PX.map((w)=>({name:w.name,description:w.description,inputSchema:eX(w.inputSchema)}))})),$.setRequestHandler(_6,async(w)=>{let{name:E,arguments:X}=w.params;KO.debug(`Tool call: ${E}`,X);try{let G=PX.find((D)=>D.name===E);if(!G)return{content:[{type:"text",text:`Unknown tool: ${E}`}],isError:!0};let J=G.inputSchema.safeParse(X??{});if(!J.success)return{content:[{type:"text",text:`Invalid args: ${J.error.message}`}],isError:!0};return{content:[{type:"text",text:await A6(E,J.data)}]}}catch(G){return KO.error(`Tool error: ${E}`,G),{content:[{type:"text",text:G instanceof Error?G.message:"Unknown error"}],isError:!0}}}),$}async function mp(){let $=TV(),w=new IO;await $.connect(w),KO.info("MCP server running on stdio")}var KO;var BV=R(()=>{FV();zV();hX();p$();rA();KO=Z0("mcp")});var QV={};Ww(QV,{toolDefinitions:()=>PX,startStdioServer:()=>mp,executeTool:()=>A6,createMcpServer:()=>TV});var IV=R(async()=>{BV();rA()});C$();import{existsSync as rp,readFileSync as pp,statSync as op}from"fs";import{dirname as tp,join as ip}from"path";import{fileURLToPath as dp}from"url";var OU=AJ(WU(),1),{program:yo,createCommand:go,createArgument:uo,createOption:ho,CommanderError:co,InvalidArgumentError:no,InvalidOptionArgumentError:mo,Command:$$,Argument:ro,Option:po,Help:oo}=OU.default;C$();qN();import{mkdirSync as s_,readFileSync as a_,writeFileSync as e_}from"fs";import{homedir as $v}from"os";import{join as sA}from"path";nw();p$();y$();d$();function k$($,w,E,X,G,J,A,D){return k$.fromTZ(k$.tp($,w,E,X,G,J,A),D)}k$.fromTZISO=($,w,E)=>k$.fromTZ(ob($,w),E);k$.fromTZ=function($,w){let E=new Date(Date.UTC($.y,$.m-1,$.d,$.h,$.i,$.s)),X=SN($.tz,E),G=new Date(E.getTime()-X),J=SN($.tz,G);if(J-X===0)return G;{let A=new Date(E.getTime()-J),D=SN($.tz,A);if(D-J===0)return A;if(!w&&D-J>0)return A;if(w)throw Error("Invalid date passed to fromTZ()");return G}};k$.toTZ=function($,w){let E=$.toLocaleString("en-US",{timeZone:w}).replace(/[\u202f]/," "),X=new Date(E);return{y:X.getFullYear(),m:X.getMonth()+1,d:X.getDate(),h:X.getHours(),i:X.getMinutes(),s:X.getSeconds(),tz:w}};k$.tp=($,w,E,X,G,J,A)=>({y:$,m:w,d:E,h:X,i:G,s:J,tz:A});function SN($,w=new Date){let E=w.toLocaleString("en-US",{timeZone:$,timeZoneName:"shortOffset"}).split(" ").slice(-1)[0],X=w.toLocaleString("en-US").replace(/[\u202f]/," ");return Date.parse(`${X} GMT`)-Date.parse(`${X} ${E}`)}function ob($,w){let E=new Date(Date.parse($));if(isNaN(E))throw Error("minitz: Invalid ISO8601 passed to parser.");let X=$.substring(9);return $.includes("Z")||X.includes("-")||X.includes("+")?k$.tp(E.getUTCFullYear(),E.getUTCMonth()+1,E.getUTCDate(),E.getUTCHours(),E.getUTCMinutes(),E.getUTCSeconds(),"Etc/UTC"):k$.tp(E.getFullYear(),E.getMonth()+1,E.getDate(),E.getHours(),E.getMinutes(),E.getSeconds(),w)}k$.minitz=k$;var kN=32,cG=31|kN,uL=[1,2,4,8,16],xL=class{pattern;timezone;second;minute;hour;day;month;dayOfWeek;lastDayOfMonth;starDOM;starDOW;constructor($,w){this.pattern=$,this.timezone=w,this.second=Array(60).fill(0),this.minute=Array(60).fill(0),this.hour=Array(24).fill(0),this.day=Array(31).fill(0),this.month=Array(12).fill(0),this.dayOfWeek=Array(7).fill(0),this.lastDayOfMonth=!1,this.starDOM=!1,this.starDOW=!1,this.parse()}parse(){if(!(typeof this.pattern=="string"||this.pattern instanceof String))throw TypeError("CronPattern: Pattern has to be of type string.");this.pattern.indexOf("@")>=0&&(this.pattern=this.handleNicknames(this.pattern).trim());let $=this.pattern.replace(/\s+/g," ").split(" ");if($.length<5||$.length>6)throw TypeError("CronPattern: invalid configuration format ('"+this.pattern+"'), exactly five or six space separated parts are required.");if($.length===5&&$.unshift("0"),$[3].indexOf("L")>=0&&($[3]=$[3].replace("L",""),this.lastDayOfMonth=!0),$[3]=="*"&&(this.starDOM=!0),$[4].length>=3&&($[4]=this.replaceAlphaMonths($[4])),$[5].length>=3&&($[5]=this.replaceAlphaDays($[5])),$[5]=="*"&&(this.starDOW=!0),this.pattern.indexOf("?")>=0){let w=new F1(new Date,this.timezone).getDate(!0);$[0]=$[0].replace("?",w.getSeconds().toString()),$[1]=$[1].replace("?",w.getMinutes().toString()),$[2]=$[2].replace("?",w.getHours().toString()),this.starDOM||($[3]=$[3].replace("?",w.getDate().toString())),$[4]=$[4].replace("?",(w.getMonth()+1).toString()),this.starDOW||($[5]=$[5].replace("?",w.getDay().toString()))}this.throwAtIllegalCharacters($),this.partToArray("second",$[0],0,1),this.partToArray("minute",$[1],0,1),this.partToArray("hour",$[2],0,1),this.partToArray("day",$[3],-1,1),this.partToArray("month",$[4],-1,1),this.partToArray("dayOfWeek",$[5],0,cG),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray($,w,E,X){let G=this[$],J=$==="day"&&this.lastDayOfMonth;if(w===""&&!J)throw TypeError("CronPattern: configuration entry "+$+" ("+w+") is empty, check for trailing spaces.");if(w==="*")return G.fill(X);let A=w.split(",");if(A.length>1)for(let D=0;D<A.length;D++)this.partToArray($,A[D],E,X);else w.indexOf("-")!==-1&&w.indexOf("/")!==-1?this.handleRangeWithStepping(w,$,E,X):w.indexOf("-")!==-1?this.handleRange(w,$,E,X):w.indexOf("/")!==-1?this.handleStepping(w,$,E,X):w!==""&&this.handleNumber(w,$,E,X)}throwAtIllegalCharacters($){for(let w=0;w<$.length;w++)if((w===5?/[^/*0-9,\-#L]+/:/[^/*0-9,-]+/).test($[w]))throw TypeError("CronPattern: configuration entry "+w+" ("+$[w]+") contains illegal characters.")}handleNumber($,w,E,X){let G=this.extractNth($,w),J=parseInt(G[0],10)+E;if(isNaN(J))throw TypeError("CronPattern: "+w+" is not a number: '"+$+"'");this.setPart(w,J,G[1]||X)}setPart($,w,E){if(!Object.prototype.hasOwnProperty.call(this,$))throw TypeError("CronPattern: Invalid part specified: "+$);if($==="dayOfWeek"){if(w===7&&(w=0),w<0||w>6)throw RangeError("CronPattern: Invalid value for dayOfWeek: "+w);this.setNthWeekdayOfMonth(w,E);return}if($==="second"||$==="minute"){if(w<0||w>=60)throw RangeError("CronPattern: Invalid value for "+$+": "+w)}else if($==="hour"){if(w<0||w>=24)throw RangeError("CronPattern: Invalid value for "+$+": "+w)}else if($==="day"){if(w<0||w>=31)throw RangeError("CronPattern: Invalid value for "+$+": "+w)}else if($==="month"&&(w<0||w>=12))throw RangeError("CronPattern: Invalid value for "+$+": "+w);this[$][w]=E}handleRangeWithStepping($,w,E,X){let G=this.extractNth($,w),J=G[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(J===null)throw TypeError("CronPattern: Syntax error, illegal range with stepping: '"+$+"'");let[,A,D,N]=J,W=parseInt(A,10)+E,O=parseInt(D,10)+E,Y=parseInt(N,10);if(isNaN(W))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(O))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN(Y))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(Y===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(Y>this[w].length)throw TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[w].length+")");if(W>O)throw TypeError("CronPattern: From value is larger than to value: '"+$+"'");for(let H=W;H<=O;H+=Y)this.setPart(w,H,G[1]||X)}extractNth($,w){let E=$,X;if(E.includes("#")){if(w!=="dayOfWeek")throw Error("CronPattern: nth (#) only allowed in day-of-week field");X=E.split("#")[1],E=E.split("#")[0]}return[E,X]}handleRange($,w,E,X){let G=this.extractNth($,w),J=G[0].split("-");if(J.length!==2)throw TypeError("CronPattern: Syntax error, illegal range: '"+$+"'");let A=parseInt(J[0],10)+E,D=parseInt(J[1],10)+E;if(isNaN(A))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(D))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(A>D)throw TypeError("CronPattern: From value is larger than to value: '"+$+"'");for(let N=A;N<=D;N++)this.setPart(w,N,G[1]||X)}handleStepping($,w,E,X){let G=this.extractNth($,w),J=G[0].split("/");if(J.length!==2)throw TypeError("CronPattern: Syntax error, illegal stepping: '"+$+"'");J[0]===""&&(J[0]="*");let A=0;J[0]!=="*"&&(A=parseInt(J[0],10)+E);let D=parseInt(J[1],10);if(isNaN(D))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(D===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(D>this[w].length)throw TypeError("CronPattern: Syntax error, max steps for part is ("+this[w].length+")");for(let N=A;N<this[w].length;N+=D)this.setPart(w,N,G[1]||X)}replaceAlphaDays($){return $.replace(/-sun/gi,"-7").replace(/sun/gi,"0").replace(/mon/gi,"1").replace(/tue/gi,"2").replace(/wed/gi,"3").replace(/thu/gi,"4").replace(/fri/gi,"5").replace(/sat/gi,"6")}replaceAlphaMonths($){return $.replace(/jan/gi,"1").replace(/feb/gi,"2").replace(/mar/gi,"3").replace(/apr/gi,"4").replace(/may/gi,"5").replace(/jun/gi,"6").replace(/jul/gi,"7").replace(/aug/gi,"8").replace(/sep/gi,"9").replace(/oct/gi,"10").replace(/nov/gi,"11").replace(/dec/gi,"12")}handleNicknames($){let w=$.trim().toLowerCase();return w==="@yearly"||w==="@annually"?"0 0 1 1 *":w==="@monthly"?"0 0 1 * *":w==="@weekly"?"0 0 * * 0":w==="@daily"?"0 0 * * *":w==="@hourly"?"0 * * * *":$}setNthWeekdayOfMonth($,w){if(typeof w!="number"&&w==="L")this.dayOfWeek[$]=this.dayOfWeek[$]|kN;else if(w===cG)this.dayOfWeek[$]=cG;else if(w<6&&w>0)this.dayOfWeek[$]=this.dayOfWeek[$]|uL[w-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${w}, Type: ${typeof w}`)}},yL=[31,28,31,30,31,30,31,31,30,31,30,31],zw=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]],F1=class ${tz;ms;second;minute;hour;day;month;year;constructor(w,E){if(this.tz=E,w&&w instanceof Date)if(!isNaN(w))this.fromDate(w);else throw TypeError("CronDate: Invalid date passed to CronDate constructor");else if(w===void 0)this.fromDate(new Date);else if(w&&typeof w=="string")this.fromString(w);else if(w instanceof $)this.fromCronDate(w);else throw TypeError("CronDate: Invalid type ("+typeof w+") passed to CronDate constructor")}isNthWeekdayOfMonth(w,E,X,G){let J=new Date(Date.UTC(w,E,X)).getUTCDay(),A=0;for(let D=1;D<=X;D++)new Date(Date.UTC(w,E,D)).getUTCDay()===J&&A++;if(G&cG&&uL[A-1]&G)return!0;if(G&kN){let D=new Date(Date.UTC(w,E+1,0)).getUTCDate();for(let N=X+1;N<=D;N++)if(new Date(Date.UTC(w,E,N)).getUTCDay()===J)return!1;return!0}return!1}fromDate(w){if(this.tz!==void 0)if(typeof this.tz=="number")this.ms=w.getUTCMilliseconds(),this.second=w.getUTCSeconds(),this.minute=w.getUTCMinutes()+this.tz,this.hour=w.getUTCHours(),this.day=w.getUTCDate(),this.month=w.getUTCMonth(),this.year=w.getUTCFullYear(),this.apply();else{let E=k$.toTZ(w,this.tz);this.ms=w.getMilliseconds(),this.second=E.s,this.minute=E.i,this.hour=E.h,this.day=E.d,this.month=E.m-1,this.year=E.y}else this.ms=w.getMilliseconds(),this.second=w.getSeconds(),this.minute=w.getMinutes(),this.hour=w.getHours(),this.day=w.getDate(),this.month=w.getMonth(),this.year=w.getFullYear()}fromCronDate(w){this.tz=w.tz,this.year=w.year,this.month=w.month,this.day=w.day,this.hour=w.hour,this.minute=w.minute,this.second=w.second,this.ms=w.ms}apply(){if(this.month>11||this.day>yL[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let w=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=w.getUTCMilliseconds(),this.second=w.getUTCSeconds(),this.minute=w.getUTCMinutes(),this.hour=w.getUTCHours(),this.day=w.getUTCDate(),this.month=w.getUTCMonth(),this.year=w.getUTCFullYear(),!0}else return!1}fromString(w){if(typeof this.tz=="number"){let E=k$.fromTZISO(w);this.ms=E.getUTCMilliseconds(),this.second=E.getUTCSeconds(),this.minute=E.getUTCMinutes(),this.hour=E.getUTCHours(),this.day=E.getUTCDate(),this.month=E.getUTCMonth(),this.year=E.getUTCFullYear(),this.apply()}else return this.fromDate(k$.fromTZISO(w,this.tz))}findNext(w,E,X,G){let J=this[E],A;X.lastDayOfMonth&&(this.month!==1?A=yL[this.month]:A=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate());let D=!X.starDOW&&E=="day"?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let N=this[E]+G;N<X[E].length;N++){let W=X[E][N];if(E==="day"&&X.lastDayOfMonth&&N-G==A&&(W=1),E==="day"&&!X.starDOW){let O=X.dayOfWeek[(D+(N-G-1))%7];if(O&&O&cG)O=this.isNthWeekdayOfMonth(this.year,this.month,N-G,O)?1:0;else if(O)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${O}`);w.legacyMode&&!X.starDOM?W=W||O:W=W&&O}if(W)return this[E]=N-G,J!==this[E]?2:1}return 3}recurse(w,E,X){let G=this.findNext(E,zw[X][0],w,zw[X][2]);if(G>1){let J=X+1;for(;J<zw.length;)this[zw[J][0]]=-zw[J][2],J++;if(G===3)return this[zw[X][1]]++,this[zw[X][0]]=-zw[X][2],this.apply(),this.recurse(w,E,0);if(this.apply())return this.recurse(w,E,X-1)}return X+=1,X>=zw.length?this:this.year>=3000?null:this.recurse(w,E,X)}increment(w,E,X){return this.second+=E.interval!==void 0&&E.interval>1&&X?E.interval:1,this.ms=0,this.apply(),this.recurse(w,E,0)}getDate(w){return w||this.tz===void 0?new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms):typeof this.tz=="number"?new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms)):k$.fromTZ(k$.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function tb($){if($===void 0&&($={}),delete $.name,$.legacyMode=$.legacyMode===void 0?!0:$.legacyMode,$.paused=$.paused===void 0?!1:$.paused,$.maxRuns=$.maxRuns===void 0?1/0:$.maxRuns,$.catch=$.catch===void 0?!1:$.catch,$.interval=$.interval===void 0?0:parseInt($.interval.toString(),10),$.utcOffset=$.utcOffset===void 0?void 0:parseInt($.utcOffset.toString(),10),$.unref=$.unref===void 0?!1:$.unref,$.startAt&&($.startAt=new F1($.startAt,$.timezone)),$.stopAt&&($.stopAt=new F1($.stopAt,$.timezone)),$.interval!==null){if(isNaN($.interval))throw Error("CronOptions: Supplied value for interval is not a number");if($.interval<0)throw Error("CronOptions: Supplied value for interval can not be negative")}if($.utcOffset!==void 0){if(isNaN($.utcOffset))throw Error("CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.");if($.utcOffset<-870||$.utcOffset>870)throw Error("CronOptions: utcOffset out of bounds.");if($.utcOffset!==void 0&&$.timezone)throw Error("CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.")}if($.unref!==!0&&$.unref!==!1)throw Error("CronOptions: Unref should be either true, false or undefined(false).");return $}function hG($){return Object.prototype.toString.call($)==="[object Function]"||typeof $=="function"||$ instanceof Function}function ib($){return hG($)}function db($){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer($):$&&typeof $.unref<"u"&&$.unref()}var gL=30000,RA=[],hL=class{name;options;_states;fn;constructor($,w,E){let X,G;if(hG(w))G=w;else if(typeof w=="object")X=w;else if(w!==void 0)throw Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");if(hG(E))G=E;else if(typeof E=="object")X=E;else if(E!==void 0)throw Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");if(this.name=X?.name,this.options=tb(X),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:X?X.maxRuns:void 0,paused:X?X.paused:!1,pattern:new xL("* * * * *")},$&&($ instanceof Date||typeof $=="string"&&$.indexOf(":")>0)?this._states.once=new F1($,this.options.timezone||this.options.utcOffset):this._states.pattern=new xL($,this.options.timezone),this.name){if(RA.find((J)=>J.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");RA.push(this)}return G!==void 0&&ib(G)&&(this.fn=G,this.schedule()),this}nextRun($){let w=this._next($);return w?w.getDate(!1):null}nextRuns($,w){this._states.maxRuns!==void 0&&$>this._states.maxRuns&&($=this._states.maxRuns);let E=[],X=w||this._states.currentRun||void 0;for(;$--&&(X=this.nextRun(X));)E.push(X);return E}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let $=this.nextRun(this._states.currentRun),w=!this._states.paused,E=this.fn!==void 0,X=!this._states.kill;return w&&E&&X&&$!==null}isStopped(){return this._states.kill}isBusy(){return this._states.blocking}currentRun(){return this._states.currentRun?this._states.currentRun.getDate():null}previousRun(){return this._states.previousRun?this._states.previousRun.getDate():null}msToNext($){let w=this._next($);return w?$ instanceof F1||$ instanceof Date?w.getTime()-$.getTime():w.getTime()-new F1($).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let $=RA.indexOf(this);$>=0&&RA.splice($,1)}pause(){return this._states.paused=!0,!this._states.kill}resume(){return this._states.paused=!1,!this._states.kill}schedule($){if($&&this.fn)throw Error("Cron: It is not allowed to schedule two functions using the same Croner instance.");$&&(this.fn=$);let w=this.msToNext(),E=this.nextRun(this._states.currentRun);return w==null||isNaN(w)||E===null?this:(w>gL&&(w=gL),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(E),w),this._states.currentTimeout&&this.options.unref&&db(this._states.currentTimeout),this)}async _trigger($){if(this._states.blocking=!0,this._states.currentRun=new F1(void 0,this.options.timezone||this.options.utcOffset),this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(w){hG(this.options.catch)&&this.options.catch(w,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new F1($,this.options.timezone||this.options.utcOffset),this._states.blocking=!1}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger($){let w=new Date,E=!this._states.paused&&w.getTime()>=$.getTime(),X=this._states.blocking&&this.options.protect;E&&!X?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):E&&X&&hG(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next($){let w=!!($||this._states.currentRun),E=!1;!$&&this.options.startAt&&this.options.interval&&([$,w]=this._calculatePreviousRun($,w),E=!$),$=new F1($,this.options.timezone||this.options.utcOffset),this.options.startAt&&$&&$.getTime()<this.options.startAt.getTime()&&($=this.options.startAt);let X=this._states.once||new F1($,this.options.timezone||this.options.utcOffset);return!E&&X!==this._states.once&&(X=X.increment(this._states.pattern,this.options,w)),this._states.once&&this._states.once.getTime()<=$.getTime()||X===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&X.getTime()>=this.options.stopAt.getTime()?null:X}_calculatePreviousRun($,w){let E=new F1(void 0,this.options.timezone||this.options.utcOffset),X=$;if(this.options.startAt.getTime()<=E.getTime()){X=this.options.startAt;let G=X.getTime()+this.options.interval*1000;for(;G<=E.getTime();)X=new F1(X,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),G=X.getTime()+this.options.interval*1000;w=!0}return X===null&&(X=void 0),[X,w]}};i$();nw();var Tw=Z0("runner:scheduler"),MX=new Map,rw=new Map;async function cL(){let w=await x().query.jobs.findMany({where:V(I0.enabled,!0)}),E=new Set(["cron","one-shot","watch","webhook","manual","bridge-msg"]),X=w.filter((G)=>!E.has(G.trigger_type));if(X.length>0)Tw.warn(`${X.length} job(s) have an unsupported trigger type and will not fire: ${X.map((G)=>`${G.name} (${G.trigger_type})`).join(", ")}. Use 'cron' with a 6-field expression (e.g. '*/30 * * * * *') for sub-minute intervals.`);for(let G of w)if(G.trigger_type==="cron"&&G.cron_expr)lb(G.id,G.name,G.cron_expr);else if(G.trigger_type==="one-shot"&&G.run_at)sb(G.id,G.name,G.run_at,G.run_count);Tw.info(`Scheduler started. ${MX.size} cron + ${rw.size} one-shot jobs scheduled.`)}function lb($,w,E){if(MX.has($))MX.get($)?.stop();let X=new hL(E,async()=>{Tw.info(`Cron trigger: ${w}`);try{await A1({jobId:$,triggerBy:"cron"})}catch(G){Tw.error(`Cron job failed: ${w}`,G)}});MX.set($,X),Tw.info(`Scheduled cron job: ${w} (${E})`)}function sb($,w,E,X){if(X>0)return;if(rw.has($))clearTimeout(rw.get($)),rw.delete($);let G=Math.max(0,E.getTime()-Date.now()),J=setTimeout(async()=>{rw.delete($),Tw.info(`One-shot trigger: ${w}`);try{await A1({jobId:$,triggerBy:"one-shot"})}catch(D){Tw.error(`One-shot job failed: ${w}`,D)}},G);rw.set($,J);let A=G<1000?"now":`in ${Math.round(G/1000)}s`;Tw.info(`Scheduled one-shot job: ${w} (${A})`)}function nL(){for(let[,$]of MX)$.stop();MX.clear();for(let[,$]of rw)clearTimeout($);rw.clear(),Tw.info("Scheduler stopped.")}p$();y$();d$();import{stat as qZ}from"fs";import{stat as SZ,readdir as kZ}from"fs/promises";import{EventEmitter as bZ}from"events";import*as H0 from"path";import{stat as ab,lstat as mL,readdir as eb,realpath as $Z}from"fs/promises";import{Readable as wZ}from"stream";import{resolve as rL,relative as EZ,join as XZ,sep as GZ}from"path";var D1={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},bN={root:".",fileFilter:($)=>!0,directoryFilter:($)=>!0,type:D1.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(bN);var iL="READDIRP_RECURSIVE_ERROR",JZ=new Set(["ENOENT","EPERM","EACCES","ELOOP",iL]),pL=[D1.DIR_TYPE,D1.EVERYTHING_TYPE,D1.FILE_DIR_TYPE,D1.FILE_TYPE],AZ=new Set([D1.DIR_TYPE,D1.EVERYTHING_TYPE,D1.FILE_DIR_TYPE]),DZ=new Set([D1.EVERYTHING_TYPE,D1.FILE_DIR_TYPE,D1.FILE_TYPE]),NZ=($)=>JZ.has($.code),WZ=process.platform==="win32",oL=($)=>!0,tL=($)=>{if($===void 0)return oL;if(typeof $==="function")return $;if(typeof $==="string"){let w=$.trim();return(E)=>E.basename===w}if(Array.isArray($)){let w=$.map((E)=>E.trim());return(E)=>w.some((X)=>E.basename===X)}return oL};class dL extends wZ{constructor($={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:$.highWaterMark});let w={...bN,...$},{root:E,type:X}=w;this._fileFilter=tL(w.fileFilter),this._directoryFilter=tL(w.directoryFilter);let G=w.lstat?mL:ab;if(WZ)this._stat=(J)=>G(J,{bigint:!0});else this._stat=G;this._maxDepth=w.depth??bN.depth,this._wantsDir=X?AZ.has(X):!1,this._wantsFile=X?DZ.has(X):!1,this._wantsEverything=X===D1.EVERYTHING_TYPE,this._root=rL(E),this._isDirent=!w.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(E,1)],this.reading=!1,this.parent=void 0}async _read($){if(this.reading)return;this.reading=!0;try{while(!this.destroyed&&$>0){let w=this.parent,E=w&&w.files;if(E&&E.length>0){let{path:X,depth:G}=w,J=E.splice(0,$).map((D)=>this._formatEntry(D,X)),A=await Promise.all(J);for(let D of A){if(!D)continue;if(this.destroyed)return;let N=await this._getEntryType(D);if(N==="directory"&&this._directoryFilter(D)){if(G<=this._maxDepth)this.parents.push(this._exploreDir(D.fullPath,G+1));if(this._wantsDir)this.push(D),$--}else if((N==="file"||this._includeAsFile(D))&&this._fileFilter(D)){if(this._wantsFile)this.push(D),$--}}}else{let X=this.parents.pop();if(!X){this.push(null);break}if(this.parent=await X,this.destroyed)return}}}catch(w){this.destroy(w)}finally{this.reading=!1}}async _exploreDir($,w){let E;try{E=await eb($,this._rdOptions)}catch(X){this._onError(X)}return{files:E,depth:w,path:$}}async _formatEntry($,w){let E,X=this._isDirent?$.name:$;try{let G=rL(XZ(w,X));E={path:EZ(this._root,G),fullPath:G,basename:X},E[this._statsProp]=this._isDirent?$:await this._stat(G)}catch(G){this._onError(G);return}return E}_onError($){if(NZ($)&&!this.destroyed)this.emit("warn",$);else this.destroy($)}async _getEntryType($){if(!$&&this._statsProp in $)return"";let w=$[this._statsProp];if(w.isFile())return"file";if(w.isDirectory())return"directory";if(w&&w.isSymbolicLink()){let E=$.fullPath;try{let X=await $Z(E),G=await mL(X);if(G.isFile())return"file";if(G.isDirectory()){let J=X.length;if(E.startsWith(X)&&E.substr(J,1)===GZ){let A=Error(`Circular symlink detected: "${E}" points to "${X}"`);return A.code=iL,this._onError(A)}return"directory"}}catch(X){return this._onError(X),""}}}_includeAsFile($){let w=$&&$[this._statsProp];return w&&this._wantsEverything&&!w.isDirectory()}}function lL($,w={}){let E=w.entryType||w.type;if(E==="both")E=D1.FILE_DIR_TYPE;if(E)w.type=E;if(!$)throw Error("readdirp: root argument is required. Usage: readdirp(root, options)");else if(typeof $!=="string")throw TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");else if(E&&!pL.includes(E))throw Error(`readdirp: Invalid type passed. Use one of ${pL.join(", ")}`);return w.root=$,new dL(w)}import{watchFile as OZ,unwatchFile as sL,watch as UZ}from"fs";import{open as YZ,stat as eL,lstat as HZ,realpath as ZN}from"fs/promises";import*as r0 from"path";import{type as LZ}from"os";var FZ="data",vN="end",$3="close",QA=()=>{};var IA=process.platform,fN=IA==="win32",jZ=IA==="darwin",MZ=IA==="linux",RZ=IA==="freebsd",w3=LZ()==="OS400",y0={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},v1=y0,zZ="watch",TZ={lstat:HZ,stat:eL},TE="listeners",zA="errHandlers",RX="rawEmitters",BZ=[TE,zA,RX],QZ=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),IZ=($)=>QZ.has(r0.extname($).slice(1).toLowerCase()),_N=($,w)=>{if($ instanceof Set)$.forEach(w);else w($)},nG=($,w,E)=>{let X=$[w];if(!(X instanceof Set))$[w]=X=new Set([X]);X.add(E)},KZ=($)=>(w)=>{let E=$[w];if(E instanceof Set)E.clear();else delete $[w]},mG=($,w,E)=>{let X=$[w];if(X instanceof Set)X.delete(E);else if(X===E)delete $[w]},E3=($)=>$ instanceof Set?$.size===0:!$,TA=new Map;function aL($,w,E,X,G){let J=(A,D)=>{if(E($),G(A,D,{watchedPath:$}),D&&$!==D)BA(r0.resolve($,D),TE,r0.join($,D))};try{return UZ($,{persistent:w.persistent},J)}catch(A){X(A);return}}var BA=($,w,E,X,G)=>{let J=TA.get($);if(!J)return;_N(J[w],(A)=>{A(E,X,G)})},VZ=($,w,E,X)=>{let{listener:G,errHandler:J,rawEmitter:A}=X,D=TA.get(w),N;if(!E.persistent){if(N=aL($,E,G,J,A),!N)return;return N.close.bind(N)}if(D)nG(D,TE,G),nG(D,zA,J),nG(D,RX,A);else{if(N=aL($,E,BA.bind(null,w,TE),J,BA.bind(null,w,RX)),!N)return;N.on(v1.ERROR,async(W)=>{let O=BA.bind(null,w,zA);if(D)D.watcherUnusable=!0;if(fN&&W.code==="EPERM")try{await(await YZ($,"r")).close(),O(W)}catch(Y){}else O(W)}),D={listeners:G,errHandlers:J,rawEmitters:A,watcher:N},TA.set(w,D)}return()=>{if(mG(D,TE,G),mG(D,zA,J),mG(D,RX,A),E3(D.listeners))D.watcher.close(),TA.delete(w),BZ.forEach(KZ(D)),D.watcher=void 0,Object.freeze(D)}},CN=new Map,PZ=($,w,E,X)=>{let{listener:G,rawEmitter:J}=X,A=CN.get(w),D=A&&A.options;if(D&&(D.persistent<E.persistent||D.interval>E.interval))sL(w),A=void 0;if(A)nG(A,TE,G),nG(A,RX,J);else A={listeners:G,rawEmitters:J,options:E,watcher:OZ(w,E,(N,W)=>{_N(A.rawEmitters,(Y)=>{Y(v1.CHANGE,w,{curr:N,prev:W})});let O=N.mtimeMs;if(N.size!==W.size||O>W.mtimeMs||O===0)_N(A.listeners,(Y)=>Y($,N))})},CN.set(w,A);return()=>{if(mG(A,TE,G),mG(A,RX,J),E3(A.listeners))CN.delete(w),sL(w),A.options=A.watcher=void 0,Object.freeze(A)}};class xN{constructor($){this.fsw=$,this._boundHandleError=(w)=>$._handleError(w)}_watchWithNodeFs($,w){let E=this.fsw.options,X=r0.dirname($),G=r0.basename($);this.fsw._getWatchedDir(X).add(G);let A=r0.resolve($),D={persistent:E.persistent};if(!w)w=QA;let N;if(E.usePolling){let W=E.interval!==E.binaryInterval;D.interval=W&&IZ(G)?E.binaryInterval:E.interval,N=PZ($,A,D,{listener:w,rawEmitter:this.fsw._emitRaw})}else N=VZ($,A,D,{listener:w,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return N}_handleFile($,w,E){if(this.fsw.closed)return;let X=r0.dirname($),G=r0.basename($),J=this.fsw._getWatchedDir(X),A=w;if(J.has(G))return;let D=async(W,O)=>{if(!this.fsw._throttle(zZ,$,5))return;if(!O||O.mtimeMs===0)try{let Y=await eL($);if(this.fsw.closed)return;let{atimeMs:H,mtimeMs:L}=Y;if(!H||H<=L||L!==A.mtimeMs)this.fsw._emit(v1.CHANGE,$,Y);if((jZ||MZ||RZ)&&A.ino!==Y.ino){this.fsw._closeFile(W),A=Y;let F=this._watchWithNodeFs($,D);if(F)this.fsw._addPathCloser(W,F)}else A=Y}catch(Y){this.fsw._remove(X,G)}else if(J.has(G)){let{atimeMs:Y,mtimeMs:H}=O;if(!Y||Y<=H||H!==A.mtimeMs)this.fsw._emit(v1.CHANGE,$,O);A=O}},N=this._watchWithNodeFs($,D);if(!(E&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored($)){if(!this.fsw._throttle(v1.ADD,$,0))return;this.fsw._emit(v1.ADD,$,w)}return N}async _handleSymlink($,w,E,X){if(this.fsw.closed)return;let G=$.fullPath,J=this.fsw._getWatchedDir(w);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let A;try{A=await ZN(E)}catch(D){return this.fsw._emitReady(),!0}if(this.fsw.closed)return;if(J.has(X)){if(this.fsw._symlinkPaths.get(G)!==A)this.fsw._symlinkPaths.set(G,A),this.fsw._emit(v1.CHANGE,E,$.stats)}else J.add(X),this.fsw._symlinkPaths.set(G,A),this.fsw._emit(v1.ADD,E,$.stats);return this.fsw._emitReady(),!0}if(this.fsw._symlinkPaths.has(G))return!0;this.fsw._symlinkPaths.set(G,!0)}_handleRead($,w,E,X,G,J,A){if($=r0.join($,""),A=this.fsw._throttle("readdir",$,1000),!A)return;let D=this.fsw._getWatchedDir(E.path),N=new Set,W=this.fsw._readdirp($,{fileFilter:(O)=>E.filterPath(O),directoryFilter:(O)=>E.filterDir(O)});if(!W)return;return W.on(FZ,async(O)=>{if(this.fsw.closed){W=void 0;return}let Y=O.path,H=r0.join($,Y);if(N.add(Y),O.stats.isSymbolicLink()&&await this._handleSymlink(O,$,H,Y))return;if(this.fsw.closed){W=void 0;return}if(Y===X||!X&&!D.has(Y))this.fsw._incrReadyCount(),H=r0.join(G,r0.relative(G,H)),this._addToNodeFs(H,w,E,J+1)}).on(v1.ERROR,this._boundHandleError),new Promise((O,Y)=>{if(!W)return Y();W.once(vN,()=>{if(this.fsw.closed){W=void 0;return}let H=A?A.clear():!1;if(O(void 0),D.getChildren().filter((L)=>{return L!==$&&!N.has(L)}).forEach((L)=>{this.fsw._remove($,L)}),W=void 0,H)this._handleRead($,!1,E,X,G,J,A)})})}async _handleDir($,w,E,X,G,J,A){let D=this.fsw._getWatchedDir(r0.dirname($)),N=D.has(r0.basename($));if(!(E&&this.fsw.options.ignoreInitial)&&!G&&!N)this.fsw._emit(v1.ADD_DIR,$,w);D.add(r0.basename($)),this.fsw._getWatchedDir($);let W,O,Y=this.fsw.options.depth;if((Y==null||X<=Y)&&!this.fsw._symlinkPaths.has(A)){if(!G){if(await this._handleRead($,E,J,G,$,X,W),this.fsw.closed)return}O=this._watchWithNodeFs($,(H,L)=>{if(L&&L.mtimeMs===0)return;this._handleRead(H,!1,J,G,$,X,W)})}return O}async _addToNodeFs($,w,E,X,G){let J=this.fsw._emitReady;if(this.fsw._isIgnored($)||this.fsw.closed)return J(),!1;let A=this.fsw._getWatchHelpers($);if(E)A.filterPath=(D)=>E.filterPath(D),A.filterDir=(D)=>E.filterDir(D);try{let D=await TZ[A.statMethod](A.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(A.watchPath,D))return J(),!1;let N=this.fsw.options.followSymlinks,W;if(D.isDirectory()){let O=r0.resolve($),Y=N?await ZN($):$;if(this.fsw.closed)return;if(W=await this._handleDir(A.watchPath,D,w,X,G,A,Y),this.fsw.closed)return;if(O!==Y&&Y!==void 0)this.fsw._symlinkPaths.set(O,Y)}else if(D.isSymbolicLink()){let O=N?await ZN($):$;if(this.fsw.closed)return;let Y=r0.dirname(A.watchPath);if(this.fsw._getWatchedDir(Y).add(A.watchPath),this.fsw._emit(v1.ADD,A.watchPath,D),W=await this._handleDir(Y,D,w,X,$,A,O),this.fsw.closed)return;if(O!==void 0)this.fsw._symlinkPaths.set(r0.resolve($),O)}else W=this._handleFile(A.watchPath,D,w);if(J(),W)this.fsw._addPathCloser($,W);return!1}catch(D){if(this.fsw._handleError(D))return J(),$}}}/*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */var yN="/",ZZ="//",N3=".",CZ="..",_Z="string",vZ=/\\/g,X3=/\/\//,fZ=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,xZ=/^\.[/\\]/;function KA($){return Array.isArray($)?$:[$]}var gN=($)=>typeof $==="object"&&$!==null&&!($ instanceof RegExp);function yZ($){if(typeof $==="function")return $;if(typeof $==="string")return(w)=>$===w;if($ instanceof RegExp)return(w)=>$.test(w);if(typeof $==="object"&&$!==null)return(w)=>{if($.path===w)return!0;if($.recursive){let E=H0.relative($.path,w);if(!E)return!1;return!E.startsWith("..")&&!H0.isAbsolute(E)}return!1};return()=>!1}function gZ($){if(typeof $!=="string")throw Error("string expected");$=H0.normalize($),$=$.replace(/\\/g,"/");let w=!1;if($.startsWith("//"))w=!0;let E=/\/\//;while($.match(E))$=$.replace(E,"/");if(w)$="/"+$;return $}function G3($,w,E){let X=gZ(w);for(let G=0;G<$.length;G++){let J=$[G];if(J(X,E))return!0}return!1}function uZ($,w){if($==null)throw TypeError("anymatch: specify first argument");let X=KA($).map((G)=>yZ(G));if(w==null)return(G,J)=>{return G3(X,G,J)};return G3(X,w)}var J3=($)=>{let w=KA($).flat();if(!w.every((E)=>typeof E===_Z))throw TypeError(`Non-string provided as watch path: ${w}`);return w.map(W3)},A3=($)=>{let w=$.replace(vZ,yN),E=!1;if(w.startsWith(ZZ))E=!0;while(w.match(X3))w=w.replace(X3,yN);if(E)w=yN+w;return w},W3=($)=>A3(H0.normalize(A3($))),D3=($="")=>(w)=>{if(typeof w==="string")return W3(H0.isAbsolute(w)?w:H0.join($,w));else return w},hZ=($,w)=>{if(H0.isAbsolute($))return $;return H0.join(w,$)},cZ=Object.freeze(new Set);class O3{constructor($,w){this.path=$,this._removeWatcher=w,this.items=new Set}add($){let{items:w}=this;if(!w)return;if($!==N3&&$!==CZ)w.add($)}async remove($){let{items:w}=this;if(!w)return;if(w.delete($),w.size>0)return;let E=this.path;try{await kZ(E)}catch(X){if(this._removeWatcher)this._removeWatcher(H0.dirname(E),H0.basename(E))}}has($){let{items:w}=this;if(!w)return;return w.has($)}getChildren(){let{items:$}=this;if(!$)return[];return[...$.values()]}dispose(){this.items.clear(),this.path="",this._removeWatcher=QA,this.items=cZ,Object.freeze(this)}}var nZ="stat",mZ="lstat";class U3{constructor($,w,E){this.fsw=E;let X=$;this.path=$=$.replace(xZ,""),this.watchPath=X,this.fullWatchPath=H0.resolve(X),this.dirParts=[],this.dirParts.forEach((G)=>{if(G.length>1)G.pop()}),this.followSymlinks=w,this.statMethod=w?nZ:mZ}entryPath($){return H0.join(this.watchPath,H0.relative(this.watchPath,$.fullPath))}filterPath($){let{stats:w}=$;if(w&&w.isSymbolicLink())return this.filterDir($);let E=this.entryPath($);return this.fsw._isntIgnored(E,w)&&this.fsw._hasReadPermissions(w)}filterDir($){return this.fsw._isntIgnored(this.entryPath($),$.stats)}}class uN extends bZ{constructor($={}){super();this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let w=$.awaitWriteFinish,E={stabilityThreshold:2000,pollInterval:100},X={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...$,ignored:$.ignored?KA($.ignored):KA([]),awaitWriteFinish:w===!0?E:typeof w==="object"?{...E,...w}:!1};if(w3)X.usePolling=!0;if(X.atomic===void 0)X.atomic=!X.usePolling;let G=process.env.CHOKIDAR_USEPOLLING;if(G!==void 0){let D=G.toLowerCase();if(D==="false"||D==="0")X.usePolling=!1;else if(D==="true"||D==="1")X.usePolling=!0;else X.usePolling=!!D}let J=process.env.CHOKIDAR_INTERVAL;if(J)X.interval=Number.parseInt(J,10);let A=0;this._emitReady=()=>{if(A++,A>=this._readyCount)this._emitReady=QA,this._readyEmitted=!0,process.nextTick(()=>this.emit(y0.READY))},this._emitRaw=(...D)=>this.emit(y0.RAW,...D),this._boundRemove=this._remove.bind(this),this.options=X,this._nodeFsHandler=new xN(this),Object.freeze(X)}_addIgnoredPath($){if(gN($)){for(let w of this._ignoredPaths)if(gN(w)&&w.path===$.path&&w.recursive===$.recursive)return}this._ignoredPaths.add($)}_removeIgnoredPath($){if(this._ignoredPaths.delete($),typeof $==="string"){for(let w of this._ignoredPaths)if(gN(w)&&w.path===$)this._ignoredPaths.delete(w)}}add($,w,E){let{cwd:X}=this.options;this.closed=!1,this._closePromise=void 0;let G=J3($);if(X)G=G.map((J)=>{return hZ(J,X)});if(G.forEach((J)=>{this._removeIgnoredPath(J)}),this._userIgnored=void 0,!this._readyCount)this._readyCount=0;return this._readyCount+=G.length,Promise.all(G.map(async(J)=>{let A=await this._nodeFsHandler._addToNodeFs(J,!E,void 0,0,w);if(A)this._emitReady();return A})).then((J)=>{if(this.closed)return;J.forEach((A)=>{if(A)this.add(H0.dirname(A),H0.basename(w||A))})}),this}unwatch($){if(this.closed)return this;let w=J3($),{cwd:E}=this.options;return w.forEach((X)=>{if(!H0.isAbsolute(X)&&!this._closers.has(X)){if(E)X=H0.join(E,X);X=H0.resolve(X)}if(this._closePath(X),this._addIgnoredPath(X),this._watched.has(X))this._addIgnoredPath({path:X,recursive:!0});this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let $=[];return this._closers.forEach((w)=>w.forEach((E)=>{let X=E();if(X instanceof Promise)$.push(X)})),this._streams.forEach((w)=>w.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach((w)=>w.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=$.length?Promise.all($).then(()=>{return}):Promise.resolve(),this._closePromise}getWatched(){let $={};return this._watched.forEach((w,E)=>{let G=(this.options.cwd?H0.relative(this.options.cwd,E):E)||N3;$[G]=w.getChildren().sort()}),$}emitWithAll($,w){if(this.emit($,...w),$!==y0.ERROR)this.emit(y0.ALL,$,...w)}async _emit($,w,E){if(this.closed)return;let X=this.options;if(fN)w=H0.normalize(w);if(X.cwd)w=H0.relative(X.cwd,w);let G=[w];if(E!=null)G.push(E);let J=X.awaitWriteFinish,A;if(J&&(A=this._pendingWrites.get(w)))return A.lastChange=new Date,this;if(X.atomic){if($===y0.UNLINK)return this._pendingUnlinks.set(w,[$,...G]),setTimeout(()=>{this._pendingUnlinks.forEach((D,N)=>{this.emit(...D),this.emit(y0.ALL,...D),this._pendingUnlinks.delete(N)})},typeof X.atomic==="number"?X.atomic:100),this;if($===y0.ADD&&this._pendingUnlinks.has(w))$=y0.CHANGE,this._pendingUnlinks.delete(w)}if(J&&($===y0.ADD||$===y0.CHANGE)&&this._readyEmitted){let D=(N,W)=>{if(N)$=y0.ERROR,G[0]=N,this.emitWithAll($,G);else if(W){if(G.length>1)G[1]=W;else G.push(W);this.emitWithAll($,G)}};return this._awaitWriteFinish(w,J.stabilityThreshold,$,D),this}if($===y0.CHANGE){if(!this._throttle(y0.CHANGE,w,50))return this}if(X.alwaysStat&&E===void 0&&($===y0.ADD||$===y0.ADD_DIR||$===y0.CHANGE)){let D=X.cwd?H0.join(X.cwd,w):w,N;try{N=await SZ(D)}catch(W){}if(!N||this.closed)return;G.push(N)}return this.emitWithAll($,G),this}_handleError($){let w=$&&$.code;if($&&w!=="ENOENT"&&w!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||w!=="EPERM"&&w!=="EACCES"))this.emit(y0.ERROR,$);return $||this.closed}_throttle($,w,E){if(!this._throttled.has($))this._throttled.set($,new Map);let X=this._throttled.get($);if(!X)throw Error("invalid throttle");let G=X.get(w);if(G)return G.count++,!1;let J,A=()=>{let N=X.get(w),W=N?N.count:0;if(X.delete(w),clearTimeout(J),N)clearTimeout(N.timeoutObject);return W};J=setTimeout(A,E);let D={timeoutObject:J,clear:A,count:0};return X.set(w,D),D}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish($,w,E,X){let G=this.options.awaitWriteFinish;if(typeof G!=="object")return;let J=G.pollInterval,A,D=$;if(this.options.cwd&&!H0.isAbsolute($))D=H0.join(this.options.cwd,$);let N=new Date,W=this._pendingWrites;function O(Y){qZ(D,(H,L)=>{if(H||!W.has($)){if(H&&H.code!=="ENOENT")X(H);return}let F=Number(new Date);if(Y&&L.size!==Y.size)W.get($).lastChange=F;let j=W.get($);if(F-j.lastChange>=w)W.delete($),X(void 0,L);else A=setTimeout(O,J,L)})}if(!W.has($))W.set($,{lastChange:N,cancelWait:()=>{return W.delete($),clearTimeout(A),E}}),A=setTimeout(O,J)}_isIgnored($,w){if(this.options.atomic&&fZ.test($))return!0;if(!this._userIgnored){let{cwd:E}=this.options,G=(this.options.ignored||[]).map(D3(E)),A=[...[...this._ignoredPaths].map(D3(E)),...G];this._userIgnored=uZ(A,void 0)}return this._userIgnored($,w)}_isntIgnored($,w){return!this._isIgnored($,w)}_getWatchHelpers($){return new U3($,this.options.followSymlinks,this)}_getWatchedDir($){let w=H0.resolve($);if(!this._watched.has(w))this._watched.set(w,new O3(w,this._boundRemove));return this._watched.get(w)}_hasReadPermissions($){if(this.options.ignorePermissionErrors)return!0;return Boolean(Number($.mode)&256)}_remove($,w,E){let X=H0.join($,w),G=H0.resolve(X);if(E=E!=null?E:this._watched.has(X)||this._watched.has(G),!this._throttle("remove",X,100))return;if(!E&&this._watched.size===1)this.add($,w,!0);this._getWatchedDir(X).getChildren().forEach((Y)=>this._remove(X,Y));let D=this._getWatchedDir($),N=D.has(w);if(D.remove(w),this._symlinkPaths.has(G))this._symlinkPaths.delete(G);let W=X;if(this.options.cwd)W=H0.relative(this.options.cwd,X);if(this.options.awaitWriteFinish&&this._pendingWrites.has(W)){if(this._pendingWrites.get(W).cancelWait()===y0.ADD)return}this._watched.delete(X),this._watched.delete(G);let O=E?y0.UNLINK_DIR:y0.UNLINK;if(N&&!this._isIgnored(X))this._emit(O,X);this._closePath(X)}_closePath($){this._closeFile($);let w=H0.dirname($);this._getWatchedDir(w).remove(H0.basename($))}_closeFile($){let w=this._closers.get($);if(!w)return;w.forEach((E)=>E()),this._closers.delete($)}_addPathCloser($,w){if(!w)return;let E=this._closers.get($);if(!E)E=[],this._closers.set($,E);E.push(w)}_readdirp($,w){if(this.closed)return;let E={type:y0.ALL,alwaysStat:!0,lstat:!0,...w,depth:0},X=lL($,E);return this._streams.add(X),X.once($3,()=>{X=void 0}),X.once(vN,()=>{if(X)this._streams.delete(X),X=void 0}),X}}function rZ($,w={}){let E=new uN(w);return E.add($),E}var Y3={watch:rZ,FSWatcher:uN};i$();nw();var rG=Z0("runner:watcher"),zX=new Map;async function L3(){let w=await x().query.jobs.findMany({where:V(I0.enabled,!0)});for(let E of w)if(E.trigger_type==="watch"&&E.watch_path)pZ(E.id,E.name,E.watch_path);rG.info(`Watchers started. ${zX.size} paths watched.`)}function pZ($,w,E){if(zX.has($))zX.get($)?.close().catch(()=>{});let X=Y3.watch(E,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:500,pollInterval:100}});X.on("add",(G)=>H3($,w,G)),X.on("change",(G)=>H3($,w,G)),zX.set($,X),rG.info(`Watching: ${E} \u2192 ${w}`)}async function H3($,w,E){rG.info(`Watch trigger: ${w} (${E})`);try{await A1({jobId:$,triggerBy:"watch",envOverrides:{WATCH_PATH:E}})}catch(X){rG.error(`Watch job failed: ${w}`,X)}}async function F3(){for(let[,$]of zX)await $.close();zX.clear(),rG.info("Watchers stopped.")}C$();async function oZ($,w,E,X,G,J){let A=`${$}${X}`;if(J){let N=new URLSearchParams;for(let[O,Y]of Object.entries(J))if(Y!==void 0)N.set(O,String(Y));let W=N.toString();if(W)A+=`?${W}`}let D={"Content-Type":"application/json"};if(w)D.Authorization=`Bearer ${w}`;try{let N=await fetch(A,{method:E,headers:D,...G!==void 0?{body:JSON.stringify(G)}:{}});if(N.status===204)return{data:null,error:null};let W=await N.json();if(!N.ok){let O=W;return{data:null,error:{error:O.error??"Unknown error",code:O.code??"UNKNOWN"}}}return{data:W,error:null}}catch(N){return{data:null,error:{error:String(N),code:"NETWORK_ERROR"}}}}function e($){let w=O0(),E=$?.baseUrl??`http://${w.api.host}:${w.api.port}`,X=$?.secret??w.api.secret,G=(J,A,D,N)=>oZ(E,X,J,A,D,N);return{tasks:{list:(J)=>G("GET","/tasks",void 0,J),get:(J)=>G("GET",`/tasks/${J}`),create:(J)=>G("POST","/tasks",J),update:(J,A)=>G("PATCH",`/tasks/${J}`,A),delete:(J)=>G("DELETE",`/tasks/${J}`),addComment:(J,A,D="human")=>G("POST",`/tasks/${J}/comments`,{content:A,author:D}),listComments:(J)=>G("GET",`/tasks/${J}/comments`),listLinks:(J)=>G("GET",`/tasks/${J}/links`),addLink:(J,A)=>G("POST",`/tasks/${J}/links`,A),deleteLink:(J,A)=>G("DELETE",`/tasks/${J}/links/${A}`)},memories:{list:(J)=>G("GET","/memories",void 0,J),search:(J,A)=>G("GET","/memories/search",void 0,{q:J,scope:A?.scope,project_id:A?.project_id,limit:A?.limit}),create:(J)=>G("POST","/memories",J),delete:(J)=>G("DELETE",`/memories/${J}`)},jobs:{list:(J)=>G("GET","/jobs",void 0,J),get:(J)=>G("GET",`/jobs/${J}`),create:(J)=>G("POST","/jobs",J),update:(J,A)=>G("PATCH",`/jobs/${J}`,A),delete:(J)=>G("DELETE",`/jobs/${J}`),trigger:(J)=>G("POST",`/jobs/${J}/trigger`),runs:(J,A)=>G("GET",`/jobs/${J}/runs`,void 0,{limit:A}),runLogs:(J,A,D)=>G("GET",`/jobs/${J}/runs/${A}/logs`,void 0,D)},prompts:{list:(J)=>G("GET","/prompts",void 0,J),get:(J)=>G("GET",`/prompts/${J}`),create:(J)=>G("POST","/prompts",J),update:(J,A)=>G("PATCH",`/prompts/${J}`,A),delete:(J)=>G("DELETE",`/prompts/${J}`),render:(J,A)=>G("POST",`/prompts/${J}/render`,{vars:A??{}}),history:(J,A)=>G("GET",`/prompts/${J}/history`,void 0,{limit:A})},projects:{list:(J)=>G("GET","/projects",void 0,J),get:(J)=>G("GET",`/projects/${J}`),getByName:(J)=>G("GET",`/projects/by-name/${encodeURIComponent(J)}`),summary:(J)=>G("GET",`/projects/${J}/summary`),create:(J)=>G("POST","/projects",J),update:(J,A)=>G("PATCH",`/projects/${J}`,A),delete:(J)=>G("DELETE",`/projects/${J}`),addComment:(J,A,D="human")=>G("POST",`/projects/${J}/comments`,{content:A,author:D}),listComments:(J)=>G("GET",`/projects/${J}/comments`)},sessions:{list:(J)=>G("GET","/sessions",void 0,J),get:(J)=>G("GET",`/sessions/${J}`)},health:{check:()=>G("GET","/health")},gateway:{status:()=>G("GET","/gateway/status"),send:(J)=>G("POST","/gateway/send",J)}}}var tw=process.env.ORC_HOME??sA($v(),".orc"),kX0=sA(tw,"daemon.log"),kX=sA(tw,"daemon.pid");function wv(){s_(sA(tw,"logs"),{recursive:!0})}function lA(){try{return Number(a_(kX,"utf-8").trim())}catch{return null}}function Ev(){e_(kX,String(process.pid))}function Qj(){try{V$("fs").unlinkSync(kX)}catch{}}function Ij(){let $=new $$("daemon").description("Run the API + scheduler + file watchers + gateway as one persistent process");return $.command("start",{isDefault:!0}).description("Start the daemon (use global --port / --host / --db / --secret to configure)").action(async()=>{wv();let w=lA();if(w)try{process.kill(w,0),console.error(`[orc] daemon already running (pid ${w}). Use: orc daemon stop`),process.exit(1)}catch{}let E=O0();Ev(),await Promise.resolve().then(() => (I9(),Q9)),console.log(`[orc] home ${tw}`),console.log(`[orc] db ${E.db.path}`),console.log(`[orc] API http://${E.api.host}:${E.api.port}`),console.log(`[orc] pid ${process.pid} -> ${kX}`),await cL(),await L3(),await IN(),console.log(`[orc] Scheduler + watchers + gateway active. Ctrl+C to stop.
|
|
577
|
+
deps: ${E}}`};var $r={keyword:"dependencies",type:"object",schemaType:"object",error:aI.error,code($){let[w,E]=wr($);lI($,w),sI($,E)}};function wr({schema:$}){let w={},E={};for(let X in $){if(X==="__proto__")continue;let G=Array.isArray($[X])?w:E;G[X]=$[X]}return[w,E]}function lI($,w=$.schema){let{gen:E,data:X,it:G}=$;if(Object.keys(w).length===0)return;let J=E.let("missing");for(let A in w){let D=w[A];if(D.length===0)continue;let N=(0,GJ.propertyInData)(E,X,A,G.opts.ownProperties);if($.setParams({property:A,depsCount:D.length,deps:D.join(", ")}),G.allErrors)E.if(N,()=>{for(let W of D)(0,GJ.checkReportMissingProp)($,W)});else E.if(DO._`${N} && (${(0,GJ.checkMissingProp)($,D,J)})`),(0,GJ.reportMissingProp)($,J),E.else()}}aI.validatePropertyDeps=lI;function sI($,w=$.schema){let{gen:E,data:X,keyword:G,it:J}=$,A=E.name("valid");for(let D in w){if((0,em.alwaysValidSchema)(J,w[D]))continue;E.if((0,GJ.propertyInData)(E,X,D,J.opts.ownProperties),()=>{let N=$.subschema({keyword:G,schemaProp:D},A);$.mergeValidEvaluated(N,A)},()=>E.var(A,!0)),$.ok(A)}}aI.validateSchemaDeps=sI;aI.default=$r});var GK=Z((XK)=>{Object.defineProperty(XK,"__esModule",{value:!0});var EK=W0(),Gr=R0(),Jr={message:"property name must be valid",params:({params:$})=>EK._`{propertyName: ${$.propertyName}}`},Ar={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Jr,code($){let{gen:w,schema:E,data:X,it:G}=$;if((0,Gr.alwaysValidSchema)(G,E))return;let J=w.name("valid");w.forIn("key",X,(A)=>{$.setParams({propertyName:A}),$.subschema({keyword:"propertyNames",data:A,dataTypes:["string"],propertyName:A,compositeRule:!0},J),w.if((0,EK.not)(J),()=>{if($.error(!0),!G.allErrors)w.break()})}),$.ok(J)}};XK.default=Ar});var NO=Z((JK)=>{Object.defineProperty(JK,"__esModule",{value:!0});var FD=I1(),r1=W0(),Nr=qw(),jD=R0(),Wr={message:"must NOT have additional properties",params:({params:$})=>r1._`{additionalProperty: ${$.additionalProperty}}`},Or={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Wr,code($){let{gen:w,schema:E,parentSchema:X,data:G,errsCount:J,it:A}=$;if(!J)throw Error("ajv implementation error");let{allErrors:D,opts:N}=A;if(A.props=!0,N.removeAdditional!=="all"&&(0,jD.alwaysValidSchema)(A,E))return;let W=(0,FD.allSchemaProperties)(X.properties),O=(0,FD.allSchemaProperties)(X.patternProperties);Y(),$.ok(r1._`${J} === ${Nr.default.errors}`);function Y(){w.forIn("key",G,(M)=>{if(!W.length&&!O.length)F(M);else w.if(H(M),()=>F(M))})}function H(M){let z;if(W.length>8){let B=(0,jD.schemaRefOrVal)(A,X.properties,"properties");z=(0,FD.isOwnProperty)(w,B,M)}else if(W.length)z=(0,r1.or)(...W.map((B)=>r1._`${M} === ${B}`));else z=r1.nil;if(O.length)z=(0,r1.or)(z,...O.map((B)=>r1._`${(0,FD.usePattern)($,B)}.test(${M})`));return(0,r1.not)(z)}function L(M){w.code(r1._`delete ${G}[${M}]`)}function F(M){if(N.removeAdditional==="all"||N.removeAdditional&&E===!1){L(M);return}if(E===!1){if($.setParams({additionalProperty:M}),$.error(),!D)w.break();return}if(typeof E=="object"&&!(0,jD.alwaysValidSchema)(A,E)){let z=w.name("valid");if(N.removeAdditional==="failing")j(M,z,!1),w.if((0,r1.not)(z),()=>{$.reset(),L(M)});else if(j(M,z),!D)w.if((0,r1.not)(z),()=>w.break())}}function j(M,z,B){let Q={keyword:"additionalProperties",dataProp:M,dataPropType:jD.Type.Str};if(B===!1)Object.assign(Q,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(Q,z)}}};JK.default=Or});var WK=Z((NK)=>{Object.defineProperty(NK,"__esModule",{value:!0});var Yr=o6(),AK=I1(),WO=R0(),DK=NO(),Hr={keyword:"properties",type:"object",schemaType:"object",code($){let{gen:w,schema:E,parentSchema:X,data:G,it:J}=$;if(J.opts.removeAdditional==="all"&&X.additionalProperties===void 0)DK.default.code(new Yr.KeywordCxt(J,DK.default,"additionalProperties"));let A=(0,AK.allSchemaProperties)(E);for(let Y of A)J.definedProperties.add(Y);if(J.opts.unevaluated&&A.length&&J.props!==!0)J.props=WO.mergeEvaluated.props(w,(0,WO.toHash)(A),J.props);let D=A.filter((Y)=>!(0,WO.alwaysValidSchema)(J,E[Y]));if(D.length===0)return;let N=w.name("valid");for(let Y of D){if(W(Y))O(Y);else{if(w.if((0,AK.propertyInData)(w,G,Y,J.opts.ownProperties)),O(Y),!J.allErrors)w.else().var(N,!0);w.endIf()}$.it.definedProperties.add(Y),$.ok(N)}function W(Y){return J.opts.useDefaults&&!J.compositeRule&&E[Y].default!==void 0}function O(Y){$.subschema({keyword:"properties",schemaProp:Y,dataProp:Y},N)}}};NK.default=Hr});var LK=Z((HK)=>{Object.defineProperty(HK,"__esModule",{value:!0});var OK=I1(),MD=W0(),UK=R0(),YK=R0(),Fr={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:w,schema:E,data:X,parentSchema:G,it:J}=$,{opts:A}=J,D=(0,OK.allSchemaProperties)(E),N=D.filter((j)=>(0,UK.alwaysValidSchema)(J,E[j]));if(D.length===0||N.length===D.length&&(!J.opts.unevaluated||J.props===!0))return;let W=A.strictSchema&&!A.allowMatchingProperties&&G.properties,O=w.name("valid");if(J.props!==!0&&!(J.props instanceof MD.Name))J.props=(0,YK.evaluatedPropsToName)(w,J.props);let{props:Y}=J;H();function H(){for(let j of D){if(W)L(j);if(J.allErrors)F(j);else w.var(O,!0),F(j),w.if(O)}}function L(j){for(let M in W)if(new RegExp(j).test(M))(0,UK.checkStrictMode)(J,`property ${M} matches pattern ${j} (use allowMatchingProperties)`)}function F(j){w.forIn("key",X,(M)=>{w.if(MD._`${(0,OK.usePattern)($,j)}.test(${M})`,()=>{let z=N.includes(j);if(!z)$.subschema({keyword:"patternProperties",schemaProp:j,dataProp:M,dataPropType:YK.Type.Str},O);if(J.opts.unevaluated&&Y!==!0)w.assign(MD._`${Y}[${M}]`,!0);else if(!z&&!J.allErrors)w.if((0,MD.not)(O),()=>w.break())})})}}};HK.default=Fr});var jK=Z((FK)=>{Object.defineProperty(FK,"__esModule",{value:!0});var Mr=R0(),Rr={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code($){let{gen:w,schema:E,it:X}=$;if((0,Mr.alwaysValidSchema)(X,E)){$.fail();return}let G=w.name("valid");$.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},G),$.failResult(G,()=>$.reset(),()=>$.error())},error:{message:"must NOT be valid"}};FK.default=Rr});var RK=Z((MK)=>{Object.defineProperty(MK,"__esModule",{value:!0});var Tr=I1(),Br={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Tr.validateUnion,error:{message:"must match a schema in anyOf"}};MK.default=Br});var TK=Z((zK)=>{Object.defineProperty(zK,"__esModule",{value:!0});var RD=W0(),Ir=R0(),Kr={message:"must match exactly one schema in oneOf",params:({params:$})=>RD._`{passingSchemas: ${$.passing}}`},Vr={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Kr,code($){let{gen:w,schema:E,parentSchema:X,it:G}=$;if(!Array.isArray(E))throw Error("ajv implementation error");if(G.opts.discriminator&&X.discriminator)return;let J=E,A=w.let("valid",!1),D=w.let("passing",null),N=w.name("_valid");$.setParams({passing:D}),w.block(W),$.result(A,()=>$.reset(),()=>$.error(!0));function W(){J.forEach((O,Y)=>{let H;if((0,Ir.alwaysValidSchema)(G,O))w.var(N,!0);else H=$.subschema({keyword:"oneOf",schemaProp:Y,compositeRule:!0},N);if(Y>0)w.if(RD._`${N} && ${A}`).assign(A,!1).assign(D,RD._`[${D}, ${Y}]`).else();w.if(N,()=>{if(w.assign(A,!0),w.assign(D,Y),H)$.mergeEvaluated(H,RD.Name)})})}}};zK.default=Vr});var QK=Z((BK)=>{Object.defineProperty(BK,"__esModule",{value:!0});var qr=R0(),Sr={keyword:"allOf",schemaType:"array",code($){let{gen:w,schema:E,it:X}=$;if(!Array.isArray(E))throw Error("ajv implementation error");let G=w.name("valid");E.forEach((J,A)=>{if((0,qr.alwaysValidSchema)(X,J))return;let D=$.subschema({keyword:"allOf",schemaProp:A},G);$.ok(G),$.mergeEvaluated(D)})}};BK.default=Sr});var PK=Z((VK)=>{Object.defineProperty(VK,"__esModule",{value:!0});var zD=W0(),KK=R0(),br={message:({params:$})=>zD.str`must match "${$.ifClause}" schema`,params:({params:$})=>zD._`{failingKeyword: ${$.ifClause}}`},Zr={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:br,code($){let{gen:w,parentSchema:E,it:X}=$;if(E.then===void 0&&E.else===void 0)(0,KK.checkStrictMode)(X,'"if" without "then" and "else" is ignored');let G=IK(X,"then"),J=IK(X,"else");if(!G&&!J)return;let A=w.let("valid",!0),D=w.name("_valid");if(N(),$.reset(),G&&J){let O=w.let("ifClause");$.setParams({ifClause:O}),w.if(D,W("then",O),W("else",O))}else if(G)w.if(D,W("then"));else w.if((0,zD.not)(D),W("else"));$.pass(A,()=>$.error(!0));function N(){let O=$.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},D);$.mergeEvaluated(O)}function W(O,Y){return()=>{let H=$.subschema({keyword:O},D);if(w.assign(A,D),$.mergeValidEvaluated(H,A),Y)w.assign(Y,zD._`${O}`);else $.setParams({ifClause:O})}}}};function IK($,w){let E=$.schema[w];return E!==void 0&&!(0,KK.alwaysValidSchema)($,E)}VK.default=Zr});var SK=Z((qK)=>{Object.defineProperty(qK,"__esModule",{value:!0});var _r=R0(),vr={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:$,parentSchema:w,it:E}){if(w.if===void 0)(0,_r.checkStrictMode)(E,`"${$}" without "if" is ignored`)}};qK.default=vr});var bK=Z((kK)=>{Object.defineProperty(kK,"__esModule",{value:!0});var xr=JO(),yr=rI(),gr=AO(),ur=tI(),hr=dI(),cr=wK(),nr=GK(),mr=NO(),rr=WK(),pr=LK(),or=jK(),tr=RK(),ir=TK(),dr=QK(),lr=PK(),sr=SK();function ar($=!1){let w=[or.default,tr.default,ir.default,dr.default,lr.default,sr.default,nr.default,mr.default,cr.default,rr.default,pr.default];if($)w.push(yr.default,ur.default);else w.push(xr.default,gr.default);return w.push(hr.default),w}kK.default=ar});var CK=Z((ZK)=>{Object.defineProperty(ZK,"__esModule",{value:!0});var J$=W0(),$p={message:({schemaCode:$})=>J$.str`must match format "${$}"`,params:({schemaCode:$})=>J$._`{format: ${$}}`},wp={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:$p,code($,w){let{gen:E,data:X,$data:G,schema:J,schemaCode:A,it:D}=$,{opts:N,errSchemaPath:W,schemaEnv:O,self:Y}=D;if(!N.validateFormats)return;if(G)H();else L();function H(){let F=E.scopeValue("formats",{ref:Y.formats,code:N.code.formats}),j=E.const("fDef",J$._`${F}[${A}]`),M=E.let("fType"),z=E.let("format");E.if(J$._`typeof ${j} == "object" && !(${j} instanceof RegExp)`,()=>E.assign(M,J$._`${j}.type || "string"`).assign(z,J$._`${j}.validate`),()=>E.assign(M,J$._`"string"`).assign(z,j)),$.fail$data((0,J$.or)(B(),Q()));function B(){if(N.strictSchema===!1)return J$.nil;return J$._`${A} && !${z}`}function Q(){let k=O.$async?J$._`(${j}.async ? await ${z}(${X}) : ${z}(${X}))`:J$._`${z}(${X})`,v=J$._`(typeof ${z} == "function" ? ${k} : ${z}.test(${X}))`;return J$._`${z} && ${z} !== true && ${M} === ${w} && !${v}`}}function L(){let F=Y.formats[J];if(!F){B();return}if(F===!0)return;let[j,M,z]=Q(F);if(j===w)$.pass(k());function B(){if(N.strictSchema===!1){Y.logger.warn(v());return}throw Error(v());function v(){return`unknown format "${J}" ignored in schema at path "${W}"`}}function Q(v){let C=v instanceof RegExp?(0,J$.regexpCode)(v):N.code.formats?J$._`${N.code.formats}${(0,J$.getProperty)(J)}`:void 0,n=E.scopeValue("formats",{key:J,ref:v,code:C});if(typeof v=="object"&&!(v instanceof RegExp))return[v.type||"string",v.validate,J$._`${n}.validate`];return["string",v,n]}function k(){if(typeof F=="object"&&!(F instanceof RegExp)&&F.async){if(!O.$async)throw Error("async format in sync schema");return J$._`await ${z}(${X})`}return typeof M=="function"?J$._`${z}(${X})`:J$._`${z}.test(${X})`}}}};ZK.default=wp});var vK=Z((_K)=>{Object.defineProperty(_K,"__esModule",{value:!0});var Xp=CK(),Gp=[Xp.default];_K.default=Gp});var yK=Z((fK)=>{Object.defineProperty(fK,"__esModule",{value:!0});fK.contentVocabulary=fK.metadataVocabulary=void 0;fK.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];fK.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var hK=Z((uK)=>{Object.defineProperty(uK,"__esModule",{value:!0});var Dp=NI(),Np=fI(),Wp=bK(),Op=vK(),gK=yK(),Up=[Dp.default,Np.default,(0,Wp.default)(),Op.default,gK.metadataVocabulary,gK.contentVocabulary];uK.default=Up});var rK=Z((nK)=>{Object.defineProperty(nK,"__esModule",{value:!0});nK.DiscrError=void 0;var cK;(function($){$.Tag="tag",$.Mapping="mapping"})(cK||(nK.DiscrError=cK={}))});var tK=Z((oK)=>{Object.defineProperty(oK,"__esModule",{value:!0});var sX=W0(),OO=rK(),pK=wD(),Hp=t6(),Lp=R0(),Fp={message:({params:{discrError:$,tagName:w}})=>$===OO.DiscrError.Tag?`tag "${w}" must be string`:`value of tag "${w}" must be in oneOf`,params:({params:{discrError:$,tag:w,tagName:E}})=>sX._`{error: ${$}, tag: ${E}, tagValue: ${w}}`},jp={keyword:"discriminator",type:"object",schemaType:"object",error:Fp,code($){let{gen:w,data:E,schema:X,parentSchema:G,it:J}=$,{oneOf:A}=G;if(!J.opts.discriminator)throw Error("discriminator: requires discriminator option");let D=X.propertyName;if(typeof D!="string")throw Error("discriminator: requires propertyName");if(X.mapping)throw Error("discriminator: mapping is not supported");if(!A)throw Error("discriminator: requires oneOf keyword");let N=w.let("valid",!1),W=w.const("tag",sX._`${E}${(0,sX.getProperty)(D)}`);w.if(sX._`typeof ${W} == "string"`,()=>O(),()=>$.error(!1,{discrError:OO.DiscrError.Tag,tag:W,tagName:D})),$.ok(N);function O(){let L=H();w.if(!1);for(let F in L)w.elseIf(sX._`${W} === ${F}`),w.assign(N,Y(L[F]));w.else(),$.error(!1,{discrError:OO.DiscrError.Mapping,tag:W,tagName:D}),w.endIf()}function Y(L){let F=w.name("valid"),j=$.subschema({keyword:"oneOf",schemaProp:L},F);return $.mergeEvaluated(j,sX.Name),F}function H(){var L;let F={},j=z(G),M=!0;for(let k=0;k<A.length;k++){let v=A[k];if((v===null||v===void 0?void 0:v.$ref)&&!(0,Lp.schemaHasRulesButRef)(v,J.self.RULES)){let n=v.$ref;if(v=pK.resolveRef.call(J.self,J.schemaEnv.root,J.baseId,n),v instanceof pK.SchemaEnv)v=v.schema;if(v===void 0)throw new Hp.default(J.opts.uriResolver,J.baseId,n)}let C=(L=v===null||v===void 0?void 0:v.properties)===null||L===void 0?void 0:L[D];if(typeof C!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${D}"`);M=M&&(j||z(v)),B(C,k)}if(!M)throw Error(`discriminator: "${D}" must be required`);return F;function z({required:k}){return Array.isArray(k)&&k.includes(D)}function B(k,v){if(k.const)Q(k.const,v);else if(k.enum)for(let C of k.enum)Q(C,v);else throw Error(`discriminator: "properties/${D}" must have "const" or "enum"`)}function Q(k,v){if(typeof k!="string"||k in F)throw Error(`discriminator: "${D}" values must be unique strings`);F[k]=v}}}};oK.default=jp});var iK=Z((rN0,Rp)=>{Rp.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var YO=Z((E1,UO)=>{Object.defineProperty(E1,"__esModule",{value:!0});E1.MissingRefError=E1.ValidationError=E1.CodeGen=E1.Name=E1.nil=E1.stringify=E1.str=E1._=E1.KeywordCxt=E1.Ajv=void 0;var zp=aQ(),Tp=hK(),Bp=tK(),dK=iK(),Qp=["/properties"],TD="http://json-schema.org/draft-07/schema";class JJ extends zp.default{_addVocabularies(){if(super._addVocabularies(),Tp.default.forEach(($)=>this.addVocabulary($)),this.opts.discriminator)this.addKeyword(Bp.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let $=this.opts.$data?this.$dataMetaSchema(dK,Qp):dK;this.addMetaSchema($,TD,!1),this.refs["http://json-schema.org/schema"]=TD}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(TD)?TD:void 0)}}E1.Ajv=JJ;UO.exports=E1=JJ;UO.exports.Ajv=JJ;Object.defineProperty(E1,"__esModule",{value:!0});E1.default=JJ;var Ip=o6();Object.defineProperty(E1,"KeywordCxt",{enumerable:!0,get:function(){return Ip.KeywordCxt}});var aX=W0();Object.defineProperty(E1,"_",{enumerable:!0,get:function(){return aX._}});Object.defineProperty(E1,"str",{enumerable:!0,get:function(){return aX.str}});Object.defineProperty(E1,"stringify",{enumerable:!0,get:function(){return aX.stringify}});Object.defineProperty(E1,"nil",{enumerable:!0,get:function(){return aX.nil}});Object.defineProperty(E1,"Name",{enumerable:!0,get:function(){return aX.Name}});Object.defineProperty(E1,"CodeGen",{enumerable:!0,get:function(){return aX.CodeGen}});var Kp=e4();Object.defineProperty(E1,"ValidationError",{enumerable:!0,get:function(){return Kp.default}});var Vp=t6();Object.defineProperty(E1,"MissingRefError",{enumerable:!0,get:function(){return Vp.default}})});var JV=Z((XV)=>{Object.defineProperty(XV,"__esModule",{value:!0});XV.formatNames=XV.fastFormats=XV.fullFormats=void 0;function Nw($,w){return{validate:$,compare:w}}XV.fullFormats={date:Nw(eK,jO),time:Nw(LO(!0),MO),"date-time":Nw(lK(!0),wV),"iso-time":Nw(LO(),$V),"iso-date-time":Nw(lK(),EV),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_p,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:hp,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:vp,int32:{type:"number",validate:yp},int64:{type:"number",validate:gp},float:{type:"number",validate:aK},double:{type:"number",validate:aK},password:!0,binary:!0};XV.fastFormats={...XV.fullFormats,date:Nw(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,jO),time:Nw(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,MO),"date-time":Nw(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,wV),"iso-time":Nw(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,$V),"iso-date-time":Nw(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,EV),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};XV.formatNames=Object.keys(XV.fullFormats);function Sp($){return $%4===0&&($%100!==0||$%400===0)}var kp=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,bp=[0,31,28,31,30,31,30,31,31,30,31,30,31];function eK($){let w=kp.exec($);if(!w)return!1;let E=+w[1],X=+w[2],G=+w[3];return X>=1&&X<=12&&G>=1&&G<=(X===2&&Sp(E)?29:bp[X])}function jO($,w){if(!($&&w))return;if($>w)return 1;if($<w)return-1;return 0}var HO=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function LO($){return function(E){let X=HO.exec(E);if(!X)return!1;let G=+X[1],J=+X[2],A=+X[3],D=X[4],N=X[5]==="-"?-1:1,W=+(X[6]||0),O=+(X[7]||0);if(W>23||O>59||$&&!D)return!1;if(G<=23&&J<=59&&A<60)return!0;let Y=J-O*N,H=G-W*N-(Y<0?1:0);return(H===23||H===-1)&&(Y===59||Y===-1)&&A<61}}function MO($,w){if(!($&&w))return;let E=new Date("2020-01-01T"+$).valueOf(),X=new Date("2020-01-01T"+w).valueOf();if(!(E&&X))return;return E-X}function $V($,w){if(!($&&w))return;let E=HO.exec($),X=HO.exec(w);if(!(E&&X))return;if($=E[1]+E[2]+E[3],w=X[1]+X[2]+X[3],$>w)return 1;if($<w)return-1;return 0}var FO=/t|\s/i;function lK($){let w=LO($);return function(X){let G=X.split(FO);return G.length===2&&eK(G[0])&&w(G[1])}}function wV($,w){if(!($&&w))return;let E=new Date($).valueOf(),X=new Date(w).valueOf();if(!(E&&X))return;return E-X}function EV($,w){if(!($&&w))return;let[E,X]=$.split(FO),[G,J]=w.split(FO),A=jO(E,G);if(A===void 0)return;return A||MO(X,J)}var Zp=/\/|:/,Cp=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function _p($){return Zp.test($)&&Cp.test($)}var sK=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function vp($){return sK.lastIndex=0,sK.test($)}var fp=-2147483648,xp=2147483647;function yp($){return Number.isInteger($)&&$<=xp&&$>=fp}function gp($){return Number.isInteger($)}function aK(){return!0}var up=/[^\\]\\Z/;function hp($){if(up.test($))return!1;try{return new RegExp($),!0}catch(w){return!1}}});var DV=Z((AV)=>{Object.defineProperty(AV,"__esModule",{value:!0});AV.formatLimitDefinition=void 0;var np=YO(),p1=W0(),JE=p1.operators,BD={formatMaximum:{okStr:"<=",ok:JE.LTE,fail:JE.GT},formatMinimum:{okStr:">=",ok:JE.GTE,fail:JE.LT},formatExclusiveMaximum:{okStr:"<",ok:JE.LT,fail:JE.GTE},formatExclusiveMinimum:{okStr:">",ok:JE.GT,fail:JE.LTE}},mp={message:({keyword:$,schemaCode:w})=>p1.str`should be ${BD[$].okStr} ${w}`,params:({keyword:$,schemaCode:w})=>p1._`{comparison: ${BD[$].okStr}, limit: ${w}}`};AV.formatLimitDefinition={keyword:Object.keys(BD),type:"string",schemaType:"string",$data:!0,error:mp,code($){let{gen:w,data:E,schemaCode:X,keyword:G,it:J}=$,{opts:A,self:D}=J;if(!A.validateFormats)return;let N=new np.KeywordCxt(J,D.RULES.all.format.definition,"format");if(N.$data)W();else O();function W(){let H=w.scopeValue("formats",{ref:D.formats,code:A.code.formats}),L=w.const("fmt",p1._`${H}[${N.schemaCode}]`);$.fail$data((0,p1.or)(p1._`typeof ${L} != "object"`,p1._`${L} instanceof RegExp`,p1._`typeof ${L}.compare != "function"`,Y(L)))}function O(){let H=N.schema,L=D.formats[H];if(!L||L===!0)return;if(typeof L!="object"||L instanceof RegExp||typeof L.compare!="function")throw Error(`"${G}": format "${H}" does not define "compare" function`);let F=w.scopeValue("formats",{key:H,ref:L,code:A.code.formats?p1._`${A.code.formats}${(0,p1.getProperty)(H)}`:void 0});$.fail$data(Y(F))}function Y(H){return p1._`${H}.compare(${E}, ${X}) ${BD[G].fail} 0`}},dependencies:["format"]};var rp=($)=>{return $.addKeyword(AV.formatLimitDefinition),$};AV.default=rp});var UV=Z((AJ,OV)=>{Object.defineProperty(AJ,"__esModule",{value:!0});var eX=JV(),op=DV(),TO=W0(),NV=new TO.Name("fullFormats"),tp=new TO.Name("fastFormats"),BO=($,w={keywords:!0})=>{if(Array.isArray(w))return WV($,w,eX.fullFormats,NV),$;let[E,X]=w.mode==="fast"?[eX.fastFormats,tp]:[eX.fullFormats,NV],G=w.formats||eX.formatNames;if(WV($,G,E,X),w.keywords)(0,op.default)($);return $};BO.get=($,w="full")=>{let X=(w==="fast"?eX.fastFormats:eX.fullFormats)[$];if(!X)throw Error(`Unknown format "${$}"`);return X};function WV($,w,E,X){var G,J;(G=(J=$.opts.code).formats)!==null&&G!==void 0||(J.formats=TO._`require("ajv-formats/dist/formats").${X}`);for(let A of w)$.addFormat(A,E[A])}OV.exports=AJ=BO;Object.defineProperty(AJ,"__esModule",{value:!0});AJ.default=BO});function ip(){let $=new YV.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return HV.default($),$}class QO{constructor($){this._ajv=$??ip()}getValidator($){let w="$id"in $&&typeof $.$id==="string"?this._ajv.getSchema($.$id)??this._ajv.compile($):this._ajv.compile($);return(E)=>{if(w(E))return{valid:!0,data:E,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(w.errors)}}}}var YV,HV;var LV=R(()=>{YV=DJ(YO(),1),HV=DJ(UV(),1)});class IO{constructor($){this._server=$}requestStream($,w,E){return this._server.requestStream($,w,E)}createMessageStream($,w){let E=this._server.getClientCapabilities();if(($.tools||$.toolChoice)&&!E?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if($.messages.length>0){let X=$.messages[$.messages.length-1],G=Array.isArray(X.content)?X.content:[X.content],J=G.some((W)=>W.type==="tool_result"),A=$.messages.length>1?$.messages[$.messages.length-2]:void 0,D=A?Array.isArray(A.content)?A.content:[A.content]:[],N=D.some((W)=>W.type==="tool_use");if(J){if(G.some((W)=>W.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!N)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(N){let W=new Set(D.filter((Y)=>Y.type==="tool_use").map((Y)=>Y.id)),O=new Set(G.filter((Y)=>Y.type==="tool_result").map((Y)=>Y.toolUseId));if(W.size!==O.size||![...W].every((Y)=>O.has(Y)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:$},x6,w)}elicitInputStream($,w){let E=this._server.getClientCapabilities(),X=$.mode??"form";switch(X){case"url":{if(!E?.elicitation?.url)throw Error("Client does not support url elicitation.");break}case"form":{if(!E?.elicitation?.form)throw Error("Client does not support form elicitation.");break}}let G=X==="form"&&$.mode===void 0?{...$,mode:"form"}:$;return this.requestStream({method:"elicitation/create",params:G},hX,w)}async getTask($,w){return this._server.getTask({taskId:$},w)}async getTaskResult($,w,E){return this._server.getTaskResult({taskId:$},w,E)}async listTasks($,w){return this._server.listTasks($?{cursor:$}:void 0,w)}async cancelTask($,w){return this._server.cancelTask({taskId:$},w)}}var FV=R(()=>{cX()});function jV($,w,E){if(!$)throw Error(`${E} does not support task creation (required for ${w})`);switch(w){case"tools/call":if(!$.tools?.call)throw Error(`${E} does not support task creation for tools/call (required for ${w})`);break;default:break}}function MV($,w,E){if(!$)throw Error(`${E} does not support task creation (required for ${w})`);switch(w){case"sampling/createMessage":if(!$.sampling?.createMessage)throw Error(`${E} does not support task creation for sampling/createMessage (required for ${w})`);break;case"elicitation/create":if(!$.elicitation?.create)throw Error(`${E} does not support task creation for elicitation/create (required for ${w})`);break;default:break}}var KO;var RV=R(()=>{fT();cX();LV();M4();FV();KO=class KO extends RW{constructor($,w){super(w);if(this._serverInfo=$,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(f6.options.map((E,X)=>[E,X])),this.isMessageIgnored=(E,X)=>{let G=this._loggingLevels.get(X);return G?this.LOG_LEVEL_SEVERITY.get(E)<this.LOG_LEVEL_SEVERITY.get(G):!1},this._capabilities=w?.capabilities??{},this._instructions=w?.instructions,this._jsonSchemaValidator=w?.jsonSchemaValidator??new QO,this.setRequestHandler(f5,(E)=>this._oninitialize(E)),this.setNotificationHandler(x5,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(r5,async(E,X)=>{let G=X.sessionId||X.requestInfo?.headers["mcp-session-id"]||void 0,{level:J}=E.params,A=f6.safeParse(J);if(A.success)this._loggingLevels.set(G,A.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new IO(this)};return this._experimental}registerCapabilities($){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=vT(this._capabilities,$)}setRequestHandler($,w){let X=j4($)?.method;if(!X)throw Error("Schema is missing a method literal");let G;if(xX(X)){let A=X;G=A._zod?.def?.value??A.value}else{let A=X;G=A._def?.value??A.value}if(typeof G!=="string")throw Error("Schema method literal must be a string");if(G==="tools/call"){let A=async(D,N)=>{let W=lw(v6,D);if(!W.success){let L=W.error instanceof Error?W.error.message:String(W.error);throw new A0(L0.InvalidParams,`Invalid tools/call request: ${L}`)}let{params:O}=W.data,Y=await Promise.resolve(w(D,N));if(O.task){let L=lw(gX,Y);if(!L.success){let F=L.error instanceof Error?L.error.message:String(L.error);throw new A0(L0.InvalidParams,`Invalid task creation result: ${F}`)}return L.data}let H=lw(_4,Y);if(!H.success){let L=H.error instanceof Error?H.error.message:String(H.error);throw new A0(L0.InvalidParams,`Invalid tools/call result: ${L}`)}return H.data};return super.setRequestHandler($,A)}return super.setRequestHandler($,w)}assertCapabilityForMethod($){switch($){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${$})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${$})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${$})`);break;case"ping":break}}assertNotificationCapability($){switch($){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${$})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${$})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${$})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${$})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${$})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability($){if(!this._capabilities)return;switch($){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${$})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${$})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${$})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${$})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${$})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${$})`);break;case"ping":case"initialize":break}}assertTaskCapability($){MV(this._clientCapabilities?.tasks?.requests,$,"Client")}assertTaskHandlerCapability($){if(!this._capabilities)return;jV(this._capabilities.tasks?.requests,$,"Server")}async _oninitialize($){let w=$.params.protocolVersion;return this._clientCapabilities=$.params.capabilities,this._clientVersion=$.params.clientInfo,{protocolVersion:HT.includes(w)?w:b5,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},I4)}async createMessage($,w){if($.tools||$.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if($.messages.length>0){let E=$.messages[$.messages.length-1],X=Array.isArray(E.content)?E.content:[E.content],G=X.some((N)=>N.type==="tool_result"),J=$.messages.length>1?$.messages[$.messages.length-2]:void 0,A=J?Array.isArray(J.content)?J.content:[J.content]:[],D=A.some((N)=>N.type==="tool_use");if(G){if(X.some((N)=>N.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!D)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(D){let N=new Set(A.filter((O)=>O.type==="tool_use").map((O)=>O.id)),W=new Set(X.filter((O)=>O.type==="tool_result").map((O)=>O.toolUseId));if(N.size!==W.size||![...N].every((O)=>W.has(O)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if($.tools)return this.request({method:"sampling/createMessage",params:$},p5,w);return this.request({method:"sampling/createMessage",params:$},x6,w)}async elicitInput($,w){switch($.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let X=$;return this.request({method:"elicitation/create",params:X},hX,w)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let X=$.mode==="form"?$:{...$,mode:"form"},G=await this.request({method:"elicitation/create",params:X},hX,w);if(G.action==="accept"&&G.content&&X.requestedSchema)try{let A=this._jsonSchemaValidator.getValidator(X.requestedSchema)(G.content);if(!A.valid)throw new A0(L0.InvalidParams,`Elicitation response content does not match requested schema: ${A.errorMessage}`)}catch(J){if(J instanceof A0)throw J;throw new A0(L0.InternalError,`Error validating elicitation response: ${J instanceof Error?J.message:String(J)}`)}return G}}}createElicitationCompletionNotifier($,w){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:$}},w)}async listRoots($,w){return this.request({method:"roots/list",params:$},o5,w)}async sendLoggingMessage($,w){if(this._capabilities.logging){if(!this.isMessageIgnored($.level,w))return this.notification({method:"notifications/message",params:$})}}async sendResourceUpdated($){return this.notification({method:"notifications/resources/updated",params:$})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}});class VO{append($){this._buffer=this._buffer?Buffer.concat([this._buffer,$]):$}readMessage(){if(!this._buffer)return null;let $=this._buffer.indexOf(`
|
|
578
|
+
`);if($===-1)return null;let w=this._buffer.toString("utf8",0,$).replace(/\r$/,"");return this._buffer=this._buffer.subarray($+1),dp(w)}clear(){this._buffer=void 0}}function dp($){return BT.parse(JSON.parse($))}function zV($){return JSON.stringify($)+`
|
|
579
|
+
`}var TV=R(()=>{cX()});import BV from"process";class PO{constructor($=BV.stdin,w=BV.stdout){this._stdin=$,this._stdout=w,this._readBuffer=new VO,this._started=!1,this._ondata=(E)=>{this._readBuffer.append(E),this.processReadBuffer()},this._onerror=(E)=>{this.onerror?.(E)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let $=this._readBuffer.readMessage();if($===null)break;this.onmessage?.($)}catch($){this.onerror?.($)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send($){return new Promise((w)=>{let E=zV($);if(this._stdout.write(E))w();else this._stdout.once("drain",w)})}}var QV=R(()=>{TV()});function $G($){let w=$._def,E=w.typeName;if(E==="ZodObject"){let X=w.shape(),G={},J=[];for(let[A,D]of Object.entries(X)){G[A]=$G(D);let N=D._def;if(N.typeName!=="ZodOptional"&&N.typeName!=="ZodDefault")J.push(A)}return{type:"object",properties:G,...J.length?{required:J}:{}}}if(E==="ZodString")return{type:"string"};if(E==="ZodNumber")return{type:"number"};if(E==="ZodBoolean")return{type:"boolean"};if(E==="ZodArray")return{type:"array",items:$G(w.type)};if(E==="ZodEnum")return{type:"string",enum:w.values};if(E==="ZodOptional"||E==="ZodDefault")return $G(w.innerType);if(E==="ZodUnion")return{oneOf:w.options.map($G)};return{}}function IV(){let $=new KO({name:"orc",version:"0.0.1"},{capabilities:{tools:{}}});return $.setRequestHandler(m5,async()=>({tools:qX.map((w)=>({name:w.name,description:w.description,inputSchema:$G(w.inputSchema)}))})),$.setRequestHandler(v6,async(w)=>{let{name:E,arguments:X}=w.params;qO.debug(`Tool call: ${E}`,X);try{let G=qX.find((D)=>D.name===E);if(!G)return{content:[{type:"text",text:`Unknown tool: ${E}`}],isError:!0};let J=G.inputSchema.safeParse(X??{});if(!J.success)return{content:[{type:"text",text:`Invalid args: ${J.error.message}`}],isError:!0};return{content:[{type:"text",text:await D6(E,J.data)}]}}catch(G){return qO.error(`Tool error: ${E}`,G),{content:[{type:"text",text:G instanceof Error?G.message:"Unknown error"}],isError:!0}}}),$}async function lp(){let $=IV(),w=new PO;await $.connect(w),qO.info("MCP server running on stdio")}var qO;var KV=R(()=>{RV();QV();cX();p$();oA();qO=Z0("mcp")});var VV={};Ww(VV,{toolDefinitions:()=>qX,startStdioServer:()=>lp,executeTool:()=>D6,createMcpServer:()=>IV});var PV=R(async()=>{KV();oA()});C$();FJ();import{existsSync as sp,statSync as ap}from"fs";var HU=DJ(YU(),1),{program:no,createCommand:mo,createArgument:ro,createOption:po,CommanderError:oo,InvalidArgumentError:to,InvalidOptionArgumentError:io,Command:$$,Argument:lo,Option:so,Help:ao}=HU.default;C$();bN();import{mkdirSync as Gv,readFileSync as Jv,writeFileSync as Av}from"fs";import{homedir as Dv}from"os";import{join as eA}from"path";nw();p$();y$();d$();function k$($,w,E,X,G,J,A,D){return k$.fromTZ(k$.tp($,w,E,X,G,J,A),D)}k$.fromTZISO=($,w,E)=>k$.fromTZ(eb($,w),E);k$.fromTZ=function($,w){let E=new Date(Date.UTC($.y,$.m-1,$.d,$.h,$.i,$.s)),X=ZN($.tz,E),G=new Date(E.getTime()-X),J=ZN($.tz,G);if(J-X===0)return G;{let A=new Date(E.getTime()-J),D=ZN($.tz,A);if(D-J===0)return A;if(!w&&D-J>0)return A;if(w)throw Error("Invalid date passed to fromTZ()");return G}};k$.toTZ=function($,w){let E=$.toLocaleString("en-US",{timeZone:w}).replace(/[\u202f]/," "),X=new Date(E);return{y:X.getFullYear(),m:X.getMonth()+1,d:X.getDate(),h:X.getHours(),i:X.getMinutes(),s:X.getSeconds(),tz:w}};k$.tp=($,w,E,X,G,J,A)=>({y:$,m:w,d:E,h:X,i:G,s:J,tz:A});function ZN($,w=new Date){let E=w.toLocaleString("en-US",{timeZone:$,timeZoneName:"shortOffset"}).split(" ").slice(-1)[0],X=w.toLocaleString("en-US").replace(/[\u202f]/," ");return Date.parse(`${X} GMT`)-Date.parse(`${X} ${E}`)}function eb($,w){let E=new Date(Date.parse($));if(isNaN(E))throw Error("minitz: Invalid ISO8601 passed to parser.");let X=$.substring(9);return $.includes("Z")||X.includes("-")||X.includes("+")?k$.tp(E.getUTCFullYear(),E.getUTCMonth()+1,E.getUTCDate(),E.getUTCHours(),E.getUTCMinutes(),E.getUTCSeconds(),"Etc/UTC"):k$.tp(E.getFullYear(),E.getMonth()+1,E.getDate(),E.getHours(),E.getMinutes(),E.getSeconds(),w)}k$.minitz=k$;var CN=32,nG=31|CN,nL=[1,2,4,8,16],uL=class{pattern;timezone;second;minute;hour;day;month;dayOfWeek;lastDayOfMonth;starDOM;starDOW;constructor($,w){this.pattern=$,this.timezone=w,this.second=Array(60).fill(0),this.minute=Array(60).fill(0),this.hour=Array(24).fill(0),this.day=Array(31).fill(0),this.month=Array(12).fill(0),this.dayOfWeek=Array(7).fill(0),this.lastDayOfMonth=!1,this.starDOM=!1,this.starDOW=!1,this.parse()}parse(){if(!(typeof this.pattern=="string"||this.pattern instanceof String))throw TypeError("CronPattern: Pattern has to be of type string.");this.pattern.indexOf("@")>=0&&(this.pattern=this.handleNicknames(this.pattern).trim());let $=this.pattern.replace(/\s+/g," ").split(" ");if($.length<5||$.length>6)throw TypeError("CronPattern: invalid configuration format ('"+this.pattern+"'), exactly five or six space separated parts are required.");if($.length===5&&$.unshift("0"),$[3].indexOf("L")>=0&&($[3]=$[3].replace("L",""),this.lastDayOfMonth=!0),$[3]=="*"&&(this.starDOM=!0),$[4].length>=3&&($[4]=this.replaceAlphaMonths($[4])),$[5].length>=3&&($[5]=this.replaceAlphaDays($[5])),$[5]=="*"&&(this.starDOW=!0),this.pattern.indexOf("?")>=0){let w=new F1(new Date,this.timezone).getDate(!0);$[0]=$[0].replace("?",w.getSeconds().toString()),$[1]=$[1].replace("?",w.getMinutes().toString()),$[2]=$[2].replace("?",w.getHours().toString()),this.starDOM||($[3]=$[3].replace("?",w.getDate().toString())),$[4]=$[4].replace("?",(w.getMonth()+1).toString()),this.starDOW||($[5]=$[5].replace("?",w.getDay().toString()))}this.throwAtIllegalCharacters($),this.partToArray("second",$[0],0,1),this.partToArray("minute",$[1],0,1),this.partToArray("hour",$[2],0,1),this.partToArray("day",$[3],-1,1),this.partToArray("month",$[4],-1,1),this.partToArray("dayOfWeek",$[5],0,nG),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray($,w,E,X){let G=this[$],J=$==="day"&&this.lastDayOfMonth;if(w===""&&!J)throw TypeError("CronPattern: configuration entry "+$+" ("+w+") is empty, check for trailing spaces.");if(w==="*")return G.fill(X);let A=w.split(",");if(A.length>1)for(let D=0;D<A.length;D++)this.partToArray($,A[D],E,X);else w.indexOf("-")!==-1&&w.indexOf("/")!==-1?this.handleRangeWithStepping(w,$,E,X):w.indexOf("-")!==-1?this.handleRange(w,$,E,X):w.indexOf("/")!==-1?this.handleStepping(w,$,E,X):w!==""&&this.handleNumber(w,$,E,X)}throwAtIllegalCharacters($){for(let w=0;w<$.length;w++)if((w===5?/[^/*0-9,\-#L]+/:/[^/*0-9,-]+/).test($[w]))throw TypeError("CronPattern: configuration entry "+w+" ("+$[w]+") contains illegal characters.")}handleNumber($,w,E,X){let G=this.extractNth($,w),J=parseInt(G[0],10)+E;if(isNaN(J))throw TypeError("CronPattern: "+w+" is not a number: '"+$+"'");this.setPart(w,J,G[1]||X)}setPart($,w,E){if(!Object.prototype.hasOwnProperty.call(this,$))throw TypeError("CronPattern: Invalid part specified: "+$);if($==="dayOfWeek"){if(w===7&&(w=0),w<0||w>6)throw RangeError("CronPattern: Invalid value for dayOfWeek: "+w);this.setNthWeekdayOfMonth(w,E);return}if($==="second"||$==="minute"){if(w<0||w>=60)throw RangeError("CronPattern: Invalid value for "+$+": "+w)}else if($==="hour"){if(w<0||w>=24)throw RangeError("CronPattern: Invalid value for "+$+": "+w)}else if($==="day"){if(w<0||w>=31)throw RangeError("CronPattern: Invalid value for "+$+": "+w)}else if($==="month"&&(w<0||w>=12))throw RangeError("CronPattern: Invalid value for "+$+": "+w);this[$][w]=E}handleRangeWithStepping($,w,E,X){let G=this.extractNth($,w),J=G[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(J===null)throw TypeError("CronPattern: Syntax error, illegal range with stepping: '"+$+"'");let[,A,D,N]=J,W=parseInt(A,10)+E,O=parseInt(D,10)+E,Y=parseInt(N,10);if(isNaN(W))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(O))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN(Y))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(Y===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(Y>this[w].length)throw TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[w].length+")");if(W>O)throw TypeError("CronPattern: From value is larger than to value: '"+$+"'");for(let H=W;H<=O;H+=Y)this.setPart(w,H,G[1]||X)}extractNth($,w){let E=$,X;if(E.includes("#")){if(w!=="dayOfWeek")throw Error("CronPattern: nth (#) only allowed in day-of-week field");X=E.split("#")[1],E=E.split("#")[0]}return[E,X]}handleRange($,w,E,X){let G=this.extractNth($,w),J=G[0].split("-");if(J.length!==2)throw TypeError("CronPattern: Syntax error, illegal range: '"+$+"'");let A=parseInt(J[0],10)+E,D=parseInt(J[1],10)+E;if(isNaN(A))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(D))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(A>D)throw TypeError("CronPattern: From value is larger than to value: '"+$+"'");for(let N=A;N<=D;N++)this.setPart(w,N,G[1]||X)}handleStepping($,w,E,X){let G=this.extractNth($,w),J=G[0].split("/");if(J.length!==2)throw TypeError("CronPattern: Syntax error, illegal stepping: '"+$+"'");J[0]===""&&(J[0]="*");let A=0;J[0]!=="*"&&(A=parseInt(J[0],10)+E);let D=parseInt(J[1],10);if(isNaN(D))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(D===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(D>this[w].length)throw TypeError("CronPattern: Syntax error, max steps for part is ("+this[w].length+")");for(let N=A;N<this[w].length;N+=D)this.setPart(w,N,G[1]||X)}replaceAlphaDays($){return $.replace(/-sun/gi,"-7").replace(/sun/gi,"0").replace(/mon/gi,"1").replace(/tue/gi,"2").replace(/wed/gi,"3").replace(/thu/gi,"4").replace(/fri/gi,"5").replace(/sat/gi,"6")}replaceAlphaMonths($){return $.replace(/jan/gi,"1").replace(/feb/gi,"2").replace(/mar/gi,"3").replace(/apr/gi,"4").replace(/may/gi,"5").replace(/jun/gi,"6").replace(/jul/gi,"7").replace(/aug/gi,"8").replace(/sep/gi,"9").replace(/oct/gi,"10").replace(/nov/gi,"11").replace(/dec/gi,"12")}handleNicknames($){let w=$.trim().toLowerCase();return w==="@yearly"||w==="@annually"?"0 0 1 1 *":w==="@monthly"?"0 0 1 * *":w==="@weekly"?"0 0 * * 0":w==="@daily"?"0 0 * * *":w==="@hourly"?"0 * * * *":$}setNthWeekdayOfMonth($,w){if(typeof w!="number"&&w==="L")this.dayOfWeek[$]=this.dayOfWeek[$]|CN;else if(w===nG)this.dayOfWeek[$]=nG;else if(w<6&&w>0)this.dayOfWeek[$]=this.dayOfWeek[$]|nL[w-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${w}, Type: ${typeof w}`)}},hL=[31,28,31,30,31,30,31,31,30,31,30,31],zw=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]],F1=class ${tz;ms;second;minute;hour;day;month;year;constructor(w,E){if(this.tz=E,w&&w instanceof Date)if(!isNaN(w))this.fromDate(w);else throw TypeError("CronDate: Invalid date passed to CronDate constructor");else if(w===void 0)this.fromDate(new Date);else if(w&&typeof w=="string")this.fromString(w);else if(w instanceof $)this.fromCronDate(w);else throw TypeError("CronDate: Invalid type ("+typeof w+") passed to CronDate constructor")}isNthWeekdayOfMonth(w,E,X,G){let J=new Date(Date.UTC(w,E,X)).getUTCDay(),A=0;for(let D=1;D<=X;D++)new Date(Date.UTC(w,E,D)).getUTCDay()===J&&A++;if(G&nG&&nL[A-1]&G)return!0;if(G&CN){let D=new Date(Date.UTC(w,E+1,0)).getUTCDate();for(let N=X+1;N<=D;N++)if(new Date(Date.UTC(w,E,N)).getUTCDay()===J)return!1;return!0}return!1}fromDate(w){if(this.tz!==void 0)if(typeof this.tz=="number")this.ms=w.getUTCMilliseconds(),this.second=w.getUTCSeconds(),this.minute=w.getUTCMinutes()+this.tz,this.hour=w.getUTCHours(),this.day=w.getUTCDate(),this.month=w.getUTCMonth(),this.year=w.getUTCFullYear(),this.apply();else{let E=k$.toTZ(w,this.tz);this.ms=w.getMilliseconds(),this.second=E.s,this.minute=E.i,this.hour=E.h,this.day=E.d,this.month=E.m-1,this.year=E.y}else this.ms=w.getMilliseconds(),this.second=w.getSeconds(),this.minute=w.getMinutes(),this.hour=w.getHours(),this.day=w.getDate(),this.month=w.getMonth(),this.year=w.getFullYear()}fromCronDate(w){this.tz=w.tz,this.year=w.year,this.month=w.month,this.day=w.day,this.hour=w.hour,this.minute=w.minute,this.second=w.second,this.ms=w.ms}apply(){if(this.month>11||this.day>hL[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let w=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=w.getUTCMilliseconds(),this.second=w.getUTCSeconds(),this.minute=w.getUTCMinutes(),this.hour=w.getUTCHours(),this.day=w.getUTCDate(),this.month=w.getUTCMonth(),this.year=w.getUTCFullYear(),!0}else return!1}fromString(w){if(typeof this.tz=="number"){let E=k$.fromTZISO(w);this.ms=E.getUTCMilliseconds(),this.second=E.getUTCSeconds(),this.minute=E.getUTCMinutes(),this.hour=E.getUTCHours(),this.day=E.getUTCDate(),this.month=E.getUTCMonth(),this.year=E.getUTCFullYear(),this.apply()}else return this.fromDate(k$.fromTZISO(w,this.tz))}findNext(w,E,X,G){let J=this[E],A;X.lastDayOfMonth&&(this.month!==1?A=hL[this.month]:A=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate());let D=!X.starDOW&&E=="day"?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let N=this[E]+G;N<X[E].length;N++){let W=X[E][N];if(E==="day"&&X.lastDayOfMonth&&N-G==A&&(W=1),E==="day"&&!X.starDOW){let O=X.dayOfWeek[(D+(N-G-1))%7];if(O&&O&nG)O=this.isNthWeekdayOfMonth(this.year,this.month,N-G,O)?1:0;else if(O)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${O}`);w.legacyMode&&!X.starDOM?W=W||O:W=W&&O}if(W)return this[E]=N-G,J!==this[E]?2:1}return 3}recurse(w,E,X){let G=this.findNext(E,zw[X][0],w,zw[X][2]);if(G>1){let J=X+1;for(;J<zw.length;)this[zw[J][0]]=-zw[J][2],J++;if(G===3)return this[zw[X][1]]++,this[zw[X][0]]=-zw[X][2],this.apply(),this.recurse(w,E,0);if(this.apply())return this.recurse(w,E,X-1)}return X+=1,X>=zw.length?this:this.year>=3000?null:this.recurse(w,E,X)}increment(w,E,X){return this.second+=E.interval!==void 0&&E.interval>1&&X?E.interval:1,this.ms=0,this.apply(),this.recurse(w,E,0)}getDate(w){return w||this.tz===void 0?new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms):typeof this.tz=="number"?new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms)):k$.fromTZ(k$.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function $Z($){if($===void 0&&($={}),delete $.name,$.legacyMode=$.legacyMode===void 0?!0:$.legacyMode,$.paused=$.paused===void 0?!1:$.paused,$.maxRuns=$.maxRuns===void 0?1/0:$.maxRuns,$.catch=$.catch===void 0?!1:$.catch,$.interval=$.interval===void 0?0:parseInt($.interval.toString(),10),$.utcOffset=$.utcOffset===void 0?void 0:parseInt($.utcOffset.toString(),10),$.unref=$.unref===void 0?!1:$.unref,$.startAt&&($.startAt=new F1($.startAt,$.timezone)),$.stopAt&&($.stopAt=new F1($.stopAt,$.timezone)),$.interval!==null){if(isNaN($.interval))throw Error("CronOptions: Supplied value for interval is not a number");if($.interval<0)throw Error("CronOptions: Supplied value for interval can not be negative")}if($.utcOffset!==void 0){if(isNaN($.utcOffset))throw Error("CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.");if($.utcOffset<-870||$.utcOffset>870)throw Error("CronOptions: utcOffset out of bounds.");if($.utcOffset!==void 0&&$.timezone)throw Error("CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.")}if($.unref!==!0&&$.unref!==!1)throw Error("CronOptions: Unref should be either true, false or undefined(false).");return $}function cG($){return Object.prototype.toString.call($)==="[object Function]"||typeof $=="function"||$ instanceof Function}function wZ($){return cG($)}function EZ($){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer($):$&&typeof $.unref<"u"&&$.unref()}var cL=30000,TA=[],mL=class{name;options;_states;fn;constructor($,w,E){let X,G;if(cG(w))G=w;else if(typeof w=="object")X=w;else if(w!==void 0)throw Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");if(cG(E))G=E;else if(typeof E=="object")X=E;else if(E!==void 0)throw Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");if(this.name=X?.name,this.options=$Z(X),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:X?X.maxRuns:void 0,paused:X?X.paused:!1,pattern:new uL("* * * * *")},$&&($ instanceof Date||typeof $=="string"&&$.indexOf(":")>0)?this._states.once=new F1($,this.options.timezone||this.options.utcOffset):this._states.pattern=new uL($,this.options.timezone),this.name){if(TA.find((J)=>J.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");TA.push(this)}return G!==void 0&&wZ(G)&&(this.fn=G,this.schedule()),this}nextRun($){let w=this._next($);return w?w.getDate(!1):null}nextRuns($,w){this._states.maxRuns!==void 0&&$>this._states.maxRuns&&($=this._states.maxRuns);let E=[],X=w||this._states.currentRun||void 0;for(;$--&&(X=this.nextRun(X));)E.push(X);return E}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let $=this.nextRun(this._states.currentRun),w=!this._states.paused,E=this.fn!==void 0,X=!this._states.kill;return w&&E&&X&&$!==null}isStopped(){return this._states.kill}isBusy(){return this._states.blocking}currentRun(){return this._states.currentRun?this._states.currentRun.getDate():null}previousRun(){return this._states.previousRun?this._states.previousRun.getDate():null}msToNext($){let w=this._next($);return w?$ instanceof F1||$ instanceof Date?w.getTime()-$.getTime():w.getTime()-new F1($).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let $=TA.indexOf(this);$>=0&&TA.splice($,1)}pause(){return this._states.paused=!0,!this._states.kill}resume(){return this._states.paused=!1,!this._states.kill}schedule($){if($&&this.fn)throw Error("Cron: It is not allowed to schedule two functions using the same Croner instance.");$&&(this.fn=$);let w=this.msToNext(),E=this.nextRun(this._states.currentRun);return w==null||isNaN(w)||E===null?this:(w>cL&&(w=cL),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(E),w),this._states.currentTimeout&&this.options.unref&&EZ(this._states.currentTimeout),this)}async _trigger($){if(this._states.blocking=!0,this._states.currentRun=new F1(void 0,this.options.timezone||this.options.utcOffset),this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(w){cG(this.options.catch)&&this.options.catch(w,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new F1($,this.options.timezone||this.options.utcOffset),this._states.blocking=!1}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger($){let w=new Date,E=!this._states.paused&&w.getTime()>=$.getTime(),X=this._states.blocking&&this.options.protect;E&&!X?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):E&&X&&cG(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next($){let w=!!($||this._states.currentRun),E=!1;!$&&this.options.startAt&&this.options.interval&&([$,w]=this._calculatePreviousRun($,w),E=!$),$=new F1($,this.options.timezone||this.options.utcOffset),this.options.startAt&&$&&$.getTime()<this.options.startAt.getTime()&&($=this.options.startAt);let X=this._states.once||new F1($,this.options.timezone||this.options.utcOffset);return!E&&X!==this._states.once&&(X=X.increment(this._states.pattern,this.options,w)),this._states.once&&this._states.once.getTime()<=$.getTime()||X===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&X.getTime()>=this.options.stopAt.getTime()?null:X}_calculatePreviousRun($,w){let E=new F1(void 0,this.options.timezone||this.options.utcOffset),X=$;if(this.options.startAt.getTime()<=E.getTime()){X=this.options.startAt;let G=X.getTime()+this.options.interval*1000;for(;G<=E.getTime();)X=new F1(X,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),G=X.getTime()+this.options.interval*1000;w=!0}return X===null&&(X=void 0),[X,w]}};i$();nw();var Tw=Z0("runner:scheduler"),RX=new Map,rw=new Map;async function rL(){let w=await x().query.jobs.findMany({where:V(I0.enabled,!0)}),E=new Set(["cron","one-shot","watch","webhook","manual","bridge-msg"]),X=w.filter((G)=>!E.has(G.trigger_type));if(X.length>0)Tw.warn(`${X.length} job(s) have an unsupported trigger type and will not fire: ${X.map((G)=>`${G.name} (${G.trigger_type})`).join(", ")}. Use 'cron' with a 6-field expression (e.g. '*/30 * * * * *') for sub-minute intervals.`);for(let G of w)if(G.trigger_type==="cron"&&G.cron_expr)XZ(G.id,G.name,G.cron_expr);else if(G.trigger_type==="one-shot"&&G.run_at)GZ(G.id,G.name,G.run_at,G.run_count);Tw.info(`Scheduler started. ${RX.size} cron + ${rw.size} one-shot jobs scheduled.`)}function XZ($,w,E){if(RX.has($))RX.get($)?.stop();let X=new mL(E,async()=>{Tw.info(`Cron trigger: ${w}`);try{await A1({jobId:$,triggerBy:"cron"})}catch(G){Tw.error(`Cron job failed: ${w}`,G)}});RX.set($,X),Tw.info(`Scheduled cron job: ${w} (${E})`)}function GZ($,w,E,X){if(X>0)return;if(rw.has($))clearTimeout(rw.get($)),rw.delete($);let G=Math.max(0,E.getTime()-Date.now()),J=setTimeout(async()=>{rw.delete($),Tw.info(`One-shot trigger: ${w}`);try{await A1({jobId:$,triggerBy:"one-shot"})}catch(D){Tw.error(`One-shot job failed: ${w}`,D)}},G);rw.set($,J);let A=G<1000?"now":`in ${Math.round(G/1000)}s`;Tw.info(`Scheduled one-shot job: ${w} (${A})`)}function pL(){for(let[,$]of RX)$.stop();RX.clear();for(let[,$]of rw)clearTimeout($);rw.clear(),Tw.info("Scheduler stopped.")}p$();y$();d$();import{stat as vZ}from"fs";import{stat as fZ,readdir as xZ}from"fs/promises";import{EventEmitter as yZ}from"events";import*as H0 from"path";import{stat as JZ,lstat as oL,readdir as AZ,realpath as DZ}from"fs/promises";import{Readable as NZ}from"stream";import{resolve as tL,relative as WZ,join as OZ,sep as UZ}from"path";var D1={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},_N={root:".",fileFilter:($)=>!0,directoryFilter:($)=>!0,type:D1.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(_N);var sL="READDIRP_RECURSIVE_ERROR",YZ=new Set(["ENOENT","EPERM","EACCES","ELOOP",sL]),iL=[D1.DIR_TYPE,D1.EVERYTHING_TYPE,D1.FILE_DIR_TYPE,D1.FILE_TYPE],HZ=new Set([D1.DIR_TYPE,D1.EVERYTHING_TYPE,D1.FILE_DIR_TYPE]),LZ=new Set([D1.EVERYTHING_TYPE,D1.FILE_DIR_TYPE,D1.FILE_TYPE]),FZ=($)=>YZ.has($.code),jZ=process.platform==="win32",dL=($)=>!0,lL=($)=>{if($===void 0)return dL;if(typeof $==="function")return $;if(typeof $==="string"){let w=$.trim();return(E)=>E.basename===w}if(Array.isArray($)){let w=$.map((E)=>E.trim());return(E)=>w.some((X)=>E.basename===X)}return dL};class aL extends NZ{constructor($={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:$.highWaterMark});let w={..._N,...$},{root:E,type:X}=w;this._fileFilter=lL(w.fileFilter),this._directoryFilter=lL(w.directoryFilter);let G=w.lstat?oL:JZ;if(jZ)this._stat=(J)=>G(J,{bigint:!0});else this._stat=G;this._maxDepth=w.depth??_N.depth,this._wantsDir=X?HZ.has(X):!1,this._wantsFile=X?LZ.has(X):!1,this._wantsEverything=X===D1.EVERYTHING_TYPE,this._root=tL(E),this._isDirent=!w.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(E,1)],this.reading=!1,this.parent=void 0}async _read($){if(this.reading)return;this.reading=!0;try{while(!this.destroyed&&$>0){let w=this.parent,E=w&&w.files;if(E&&E.length>0){let{path:X,depth:G}=w,J=E.splice(0,$).map((D)=>this._formatEntry(D,X)),A=await Promise.all(J);for(let D of A){if(!D)continue;if(this.destroyed)return;let N=await this._getEntryType(D);if(N==="directory"&&this._directoryFilter(D)){if(G<=this._maxDepth)this.parents.push(this._exploreDir(D.fullPath,G+1));if(this._wantsDir)this.push(D),$--}else if((N==="file"||this._includeAsFile(D))&&this._fileFilter(D)){if(this._wantsFile)this.push(D),$--}}}else{let X=this.parents.pop();if(!X){this.push(null);break}if(this.parent=await X,this.destroyed)return}}}catch(w){this.destroy(w)}finally{this.reading=!1}}async _exploreDir($,w){let E;try{E=await AZ($,this._rdOptions)}catch(X){this._onError(X)}return{files:E,depth:w,path:$}}async _formatEntry($,w){let E,X=this._isDirent?$.name:$;try{let G=tL(OZ(w,X));E={path:WZ(this._root,G),fullPath:G,basename:X},E[this._statsProp]=this._isDirent?$:await this._stat(G)}catch(G){this._onError(G);return}return E}_onError($){if(FZ($)&&!this.destroyed)this.emit("warn",$);else this.destroy($)}async _getEntryType($){if(!$&&this._statsProp in $)return"";let w=$[this._statsProp];if(w.isFile())return"file";if(w.isDirectory())return"directory";if(w&&w.isSymbolicLink()){let E=$.fullPath;try{let X=await DZ(E),G=await oL(X);if(G.isFile())return"file";if(G.isDirectory()){let J=X.length;if(E.startsWith(X)&&E.substr(J,1)===UZ){let A=Error(`Circular symlink detected: "${E}" points to "${X}"`);return A.code=sL,this._onError(A)}return"directory"}}catch(X){return this._onError(X),""}}}_includeAsFile($){let w=$&&$[this._statsProp];return w&&this._wantsEverything&&!w.isDirectory()}}function eL($,w={}){let E=w.entryType||w.type;if(E==="both")E=D1.FILE_DIR_TYPE;if(E)w.type=E;if(!$)throw Error("readdirp: root argument is required. Usage: readdirp(root, options)");else if(typeof $!=="string")throw TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");else if(E&&!iL.includes(E))throw Error(`readdirp: Invalid type passed. Use one of ${iL.join(", ")}`);return w.root=$,new aL(w)}import{watchFile as MZ,unwatchFile as $3,watch as RZ}from"fs";import{open as zZ,stat as E3,lstat as TZ,realpath as vN}from"fs/promises";import*as r0 from"path";import{type as BZ}from"os";var QZ="data",yN="end",X3="close",KA=()=>{};var VA=process.platform,gN=VA==="win32",IZ=VA==="darwin",KZ=VA==="linux",VZ=VA==="freebsd",G3=BZ()==="OS400",y0={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},v1=y0,PZ="watch",qZ={lstat:TZ,stat:E3},TE="listeners",BA="errHandlers",zX="rawEmitters",SZ=[TE,BA,zX],kZ=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),bZ=($)=>kZ.has(r0.extname($).slice(1).toLowerCase()),xN=($,w)=>{if($ instanceof Set)$.forEach(w);else w($)},mG=($,w,E)=>{let X=$[w];if(!(X instanceof Set))$[w]=X=new Set([X]);X.add(E)},ZZ=($)=>(w)=>{let E=$[w];if(E instanceof Set)E.clear();else delete $[w]},rG=($,w,E)=>{let X=$[w];if(X instanceof Set)X.delete(E);else if(X===E)delete $[w]},J3=($)=>$ instanceof Set?$.size===0:!$,QA=new Map;function w3($,w,E,X,G){let J=(A,D)=>{if(E($),G(A,D,{watchedPath:$}),D&&$!==D)IA(r0.resolve($,D),TE,r0.join($,D))};try{return RZ($,{persistent:w.persistent},J)}catch(A){X(A);return}}var IA=($,w,E,X,G)=>{let J=QA.get($);if(!J)return;xN(J[w],(A)=>{A(E,X,G)})},CZ=($,w,E,X)=>{let{listener:G,errHandler:J,rawEmitter:A}=X,D=QA.get(w),N;if(!E.persistent){if(N=w3($,E,G,J,A),!N)return;return N.close.bind(N)}if(D)mG(D,TE,G),mG(D,BA,J),mG(D,zX,A);else{if(N=w3($,E,IA.bind(null,w,TE),J,IA.bind(null,w,zX)),!N)return;N.on(v1.ERROR,async(W)=>{let O=IA.bind(null,w,BA);if(D)D.watcherUnusable=!0;if(gN&&W.code==="EPERM")try{await(await zZ($,"r")).close(),O(W)}catch(Y){}else O(W)}),D={listeners:G,errHandlers:J,rawEmitters:A,watcher:N},QA.set(w,D)}return()=>{if(rG(D,TE,G),rG(D,BA,J),rG(D,zX,A),J3(D.listeners))D.watcher.close(),QA.delete(w),SZ.forEach(ZZ(D)),D.watcher=void 0,Object.freeze(D)}},fN=new Map,_Z=($,w,E,X)=>{let{listener:G,rawEmitter:J}=X,A=fN.get(w),D=A&&A.options;if(D&&(D.persistent<E.persistent||D.interval>E.interval))$3(w),A=void 0;if(A)mG(A,TE,G),mG(A,zX,J);else A={listeners:G,rawEmitters:J,options:E,watcher:MZ(w,E,(N,W)=>{xN(A.rawEmitters,(Y)=>{Y(v1.CHANGE,w,{curr:N,prev:W})});let O=N.mtimeMs;if(N.size!==W.size||O>W.mtimeMs||O===0)xN(A.listeners,(Y)=>Y($,N))})},fN.set(w,A);return()=>{if(rG(A,TE,G),rG(A,zX,J),J3(A.listeners))fN.delete(w),$3(w),A.options=A.watcher=void 0,Object.freeze(A)}};class uN{constructor($){this.fsw=$,this._boundHandleError=(w)=>$._handleError(w)}_watchWithNodeFs($,w){let E=this.fsw.options,X=r0.dirname($),G=r0.basename($);this.fsw._getWatchedDir(X).add(G);let A=r0.resolve($),D={persistent:E.persistent};if(!w)w=KA;let N;if(E.usePolling){let W=E.interval!==E.binaryInterval;D.interval=W&&bZ(G)?E.binaryInterval:E.interval,N=_Z($,A,D,{listener:w,rawEmitter:this.fsw._emitRaw})}else N=CZ($,A,D,{listener:w,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return N}_handleFile($,w,E){if(this.fsw.closed)return;let X=r0.dirname($),G=r0.basename($),J=this.fsw._getWatchedDir(X),A=w;if(J.has(G))return;let D=async(W,O)=>{if(!this.fsw._throttle(PZ,$,5))return;if(!O||O.mtimeMs===0)try{let Y=await E3($);if(this.fsw.closed)return;let{atimeMs:H,mtimeMs:L}=Y;if(!H||H<=L||L!==A.mtimeMs)this.fsw._emit(v1.CHANGE,$,Y);if((IZ||KZ||VZ)&&A.ino!==Y.ino){this.fsw._closeFile(W),A=Y;let F=this._watchWithNodeFs($,D);if(F)this.fsw._addPathCloser(W,F)}else A=Y}catch(Y){this.fsw._remove(X,G)}else if(J.has(G)){let{atimeMs:Y,mtimeMs:H}=O;if(!Y||Y<=H||H!==A.mtimeMs)this.fsw._emit(v1.CHANGE,$,O);A=O}},N=this._watchWithNodeFs($,D);if(!(E&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored($)){if(!this.fsw._throttle(v1.ADD,$,0))return;this.fsw._emit(v1.ADD,$,w)}return N}async _handleSymlink($,w,E,X){if(this.fsw.closed)return;let G=$.fullPath,J=this.fsw._getWatchedDir(w);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let A;try{A=await vN(E)}catch(D){return this.fsw._emitReady(),!0}if(this.fsw.closed)return;if(J.has(X)){if(this.fsw._symlinkPaths.get(G)!==A)this.fsw._symlinkPaths.set(G,A),this.fsw._emit(v1.CHANGE,E,$.stats)}else J.add(X),this.fsw._symlinkPaths.set(G,A),this.fsw._emit(v1.ADD,E,$.stats);return this.fsw._emitReady(),!0}if(this.fsw._symlinkPaths.has(G))return!0;this.fsw._symlinkPaths.set(G,!0)}_handleRead($,w,E,X,G,J,A){if($=r0.join($,""),A=this.fsw._throttle("readdir",$,1000),!A)return;let D=this.fsw._getWatchedDir(E.path),N=new Set,W=this.fsw._readdirp($,{fileFilter:(O)=>E.filterPath(O),directoryFilter:(O)=>E.filterDir(O)});if(!W)return;return W.on(QZ,async(O)=>{if(this.fsw.closed){W=void 0;return}let Y=O.path,H=r0.join($,Y);if(N.add(Y),O.stats.isSymbolicLink()&&await this._handleSymlink(O,$,H,Y))return;if(this.fsw.closed){W=void 0;return}if(Y===X||!X&&!D.has(Y))this.fsw._incrReadyCount(),H=r0.join(G,r0.relative(G,H)),this._addToNodeFs(H,w,E,J+1)}).on(v1.ERROR,this._boundHandleError),new Promise((O,Y)=>{if(!W)return Y();W.once(yN,()=>{if(this.fsw.closed){W=void 0;return}let H=A?A.clear():!1;if(O(void 0),D.getChildren().filter((L)=>{return L!==$&&!N.has(L)}).forEach((L)=>{this.fsw._remove($,L)}),W=void 0,H)this._handleRead($,!1,E,X,G,J,A)})})}async _handleDir($,w,E,X,G,J,A){let D=this.fsw._getWatchedDir(r0.dirname($)),N=D.has(r0.basename($));if(!(E&&this.fsw.options.ignoreInitial)&&!G&&!N)this.fsw._emit(v1.ADD_DIR,$,w);D.add(r0.basename($)),this.fsw._getWatchedDir($);let W,O,Y=this.fsw.options.depth;if((Y==null||X<=Y)&&!this.fsw._symlinkPaths.has(A)){if(!G){if(await this._handleRead($,E,J,G,$,X,W),this.fsw.closed)return}O=this._watchWithNodeFs($,(H,L)=>{if(L&&L.mtimeMs===0)return;this._handleRead(H,!1,J,G,$,X,W)})}return O}async _addToNodeFs($,w,E,X,G){let J=this.fsw._emitReady;if(this.fsw._isIgnored($)||this.fsw.closed)return J(),!1;let A=this.fsw._getWatchHelpers($);if(E)A.filterPath=(D)=>E.filterPath(D),A.filterDir=(D)=>E.filterDir(D);try{let D=await qZ[A.statMethod](A.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(A.watchPath,D))return J(),!1;let N=this.fsw.options.followSymlinks,W;if(D.isDirectory()){let O=r0.resolve($),Y=N?await vN($):$;if(this.fsw.closed)return;if(W=await this._handleDir(A.watchPath,D,w,X,G,A,Y),this.fsw.closed)return;if(O!==Y&&Y!==void 0)this.fsw._symlinkPaths.set(O,Y)}else if(D.isSymbolicLink()){let O=N?await vN($):$;if(this.fsw.closed)return;let Y=r0.dirname(A.watchPath);if(this.fsw._getWatchedDir(Y).add(A.watchPath),this.fsw._emit(v1.ADD,A.watchPath,D),W=await this._handleDir(Y,D,w,X,$,A,O),this.fsw.closed)return;if(O!==void 0)this.fsw._symlinkPaths.set(r0.resolve($),O)}else W=this._handleFile(A.watchPath,D,w);if(J(),W)this.fsw._addPathCloser($,W);return!1}catch(D){if(this.fsw._handleError(D))return J(),$}}}/*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */var hN="/",gZ="//",U3=".",uZ="..",hZ="string",cZ=/\\/g,A3=/\/\//,nZ=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,mZ=/^\.[/\\]/;function PA($){return Array.isArray($)?$:[$]}var cN=($)=>typeof $==="object"&&$!==null&&!($ instanceof RegExp);function rZ($){if(typeof $==="function")return $;if(typeof $==="string")return(w)=>$===w;if($ instanceof RegExp)return(w)=>$.test(w);if(typeof $==="object"&&$!==null)return(w)=>{if($.path===w)return!0;if($.recursive){let E=H0.relative($.path,w);if(!E)return!1;return!E.startsWith("..")&&!H0.isAbsolute(E)}return!1};return()=>!1}function pZ($){if(typeof $!=="string")throw Error("string expected");$=H0.normalize($),$=$.replace(/\\/g,"/");let w=!1;if($.startsWith("//"))w=!0;let E=/\/\//;while($.match(E))$=$.replace(E,"/");if(w)$="/"+$;return $}function D3($,w,E){let X=pZ(w);for(let G=0;G<$.length;G++){let J=$[G];if(J(X,E))return!0}return!1}function oZ($,w){if($==null)throw TypeError("anymatch: specify first argument");let X=PA($).map((G)=>rZ(G));if(w==null)return(G,J)=>{return D3(X,G,J)};return D3(X,w)}var N3=($)=>{let w=PA($).flat();if(!w.every((E)=>typeof E===hZ))throw TypeError(`Non-string provided as watch path: ${w}`);return w.map(Y3)},W3=($)=>{let w=$.replace(cZ,hN),E=!1;if(w.startsWith(gZ))E=!0;while(w.match(A3))w=w.replace(A3,hN);if(E)w=hN+w;return w},Y3=($)=>W3(H0.normalize(W3($))),O3=($="")=>(w)=>{if(typeof w==="string")return Y3(H0.isAbsolute(w)?w:H0.join($,w));else return w},tZ=($,w)=>{if(H0.isAbsolute($))return $;return H0.join(w,$)},iZ=Object.freeze(new Set);class H3{constructor($,w){this.path=$,this._removeWatcher=w,this.items=new Set}add($){let{items:w}=this;if(!w)return;if($!==U3&&$!==uZ)w.add($)}async remove($){let{items:w}=this;if(!w)return;if(w.delete($),w.size>0)return;let E=this.path;try{await xZ(E)}catch(X){if(this._removeWatcher)this._removeWatcher(H0.dirname(E),H0.basename(E))}}has($){let{items:w}=this;if(!w)return;return w.has($)}getChildren(){let{items:$}=this;if(!$)return[];return[...$.values()]}dispose(){this.items.clear(),this.path="",this._removeWatcher=KA,this.items=iZ,Object.freeze(this)}}var dZ="stat",lZ="lstat";class L3{constructor($,w,E){this.fsw=E;let X=$;this.path=$=$.replace(mZ,""),this.watchPath=X,this.fullWatchPath=H0.resolve(X),this.dirParts=[],this.dirParts.forEach((G)=>{if(G.length>1)G.pop()}),this.followSymlinks=w,this.statMethod=w?dZ:lZ}entryPath($){return H0.join(this.watchPath,H0.relative(this.watchPath,$.fullPath))}filterPath($){let{stats:w}=$;if(w&&w.isSymbolicLink())return this.filterDir($);let E=this.entryPath($);return this.fsw._isntIgnored(E,w)&&this.fsw._hasReadPermissions(w)}filterDir($){return this.fsw._isntIgnored(this.entryPath($),$.stats)}}class nN extends yZ{constructor($={}){super();this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let w=$.awaitWriteFinish,E={stabilityThreshold:2000,pollInterval:100},X={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...$,ignored:$.ignored?PA($.ignored):PA([]),awaitWriteFinish:w===!0?E:typeof w==="object"?{...E,...w}:!1};if(G3)X.usePolling=!0;if(X.atomic===void 0)X.atomic=!X.usePolling;let G=process.env.CHOKIDAR_USEPOLLING;if(G!==void 0){let D=G.toLowerCase();if(D==="false"||D==="0")X.usePolling=!1;else if(D==="true"||D==="1")X.usePolling=!0;else X.usePolling=!!D}let J=process.env.CHOKIDAR_INTERVAL;if(J)X.interval=Number.parseInt(J,10);let A=0;this._emitReady=()=>{if(A++,A>=this._readyCount)this._emitReady=KA,this._readyEmitted=!0,process.nextTick(()=>this.emit(y0.READY))},this._emitRaw=(...D)=>this.emit(y0.RAW,...D),this._boundRemove=this._remove.bind(this),this.options=X,this._nodeFsHandler=new uN(this),Object.freeze(X)}_addIgnoredPath($){if(cN($)){for(let w of this._ignoredPaths)if(cN(w)&&w.path===$.path&&w.recursive===$.recursive)return}this._ignoredPaths.add($)}_removeIgnoredPath($){if(this._ignoredPaths.delete($),typeof $==="string"){for(let w of this._ignoredPaths)if(cN(w)&&w.path===$)this._ignoredPaths.delete(w)}}add($,w,E){let{cwd:X}=this.options;this.closed=!1,this._closePromise=void 0;let G=N3($);if(X)G=G.map((J)=>{return tZ(J,X)});if(G.forEach((J)=>{this._removeIgnoredPath(J)}),this._userIgnored=void 0,!this._readyCount)this._readyCount=0;return this._readyCount+=G.length,Promise.all(G.map(async(J)=>{let A=await this._nodeFsHandler._addToNodeFs(J,!E,void 0,0,w);if(A)this._emitReady();return A})).then((J)=>{if(this.closed)return;J.forEach((A)=>{if(A)this.add(H0.dirname(A),H0.basename(w||A))})}),this}unwatch($){if(this.closed)return this;let w=N3($),{cwd:E}=this.options;return w.forEach((X)=>{if(!H0.isAbsolute(X)&&!this._closers.has(X)){if(E)X=H0.join(E,X);X=H0.resolve(X)}if(this._closePath(X),this._addIgnoredPath(X),this._watched.has(X))this._addIgnoredPath({path:X,recursive:!0});this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let $=[];return this._closers.forEach((w)=>w.forEach((E)=>{let X=E();if(X instanceof Promise)$.push(X)})),this._streams.forEach((w)=>w.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach((w)=>w.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=$.length?Promise.all($).then(()=>{return}):Promise.resolve(),this._closePromise}getWatched(){let $={};return this._watched.forEach((w,E)=>{let G=(this.options.cwd?H0.relative(this.options.cwd,E):E)||U3;$[G]=w.getChildren().sort()}),$}emitWithAll($,w){if(this.emit($,...w),$!==y0.ERROR)this.emit(y0.ALL,$,...w)}async _emit($,w,E){if(this.closed)return;let X=this.options;if(gN)w=H0.normalize(w);if(X.cwd)w=H0.relative(X.cwd,w);let G=[w];if(E!=null)G.push(E);let J=X.awaitWriteFinish,A;if(J&&(A=this._pendingWrites.get(w)))return A.lastChange=new Date,this;if(X.atomic){if($===y0.UNLINK)return this._pendingUnlinks.set(w,[$,...G]),setTimeout(()=>{this._pendingUnlinks.forEach((D,N)=>{this.emit(...D),this.emit(y0.ALL,...D),this._pendingUnlinks.delete(N)})},typeof X.atomic==="number"?X.atomic:100),this;if($===y0.ADD&&this._pendingUnlinks.has(w))$=y0.CHANGE,this._pendingUnlinks.delete(w)}if(J&&($===y0.ADD||$===y0.CHANGE)&&this._readyEmitted){let D=(N,W)=>{if(N)$=y0.ERROR,G[0]=N,this.emitWithAll($,G);else if(W){if(G.length>1)G[1]=W;else G.push(W);this.emitWithAll($,G)}};return this._awaitWriteFinish(w,J.stabilityThreshold,$,D),this}if($===y0.CHANGE){if(!this._throttle(y0.CHANGE,w,50))return this}if(X.alwaysStat&&E===void 0&&($===y0.ADD||$===y0.ADD_DIR||$===y0.CHANGE)){let D=X.cwd?H0.join(X.cwd,w):w,N;try{N=await fZ(D)}catch(W){}if(!N||this.closed)return;G.push(N)}return this.emitWithAll($,G),this}_handleError($){let w=$&&$.code;if($&&w!=="ENOENT"&&w!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||w!=="EPERM"&&w!=="EACCES"))this.emit(y0.ERROR,$);return $||this.closed}_throttle($,w,E){if(!this._throttled.has($))this._throttled.set($,new Map);let X=this._throttled.get($);if(!X)throw Error("invalid throttle");let G=X.get(w);if(G)return G.count++,!1;let J,A=()=>{let N=X.get(w),W=N?N.count:0;if(X.delete(w),clearTimeout(J),N)clearTimeout(N.timeoutObject);return W};J=setTimeout(A,E);let D={timeoutObject:J,clear:A,count:0};return X.set(w,D),D}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish($,w,E,X){let G=this.options.awaitWriteFinish;if(typeof G!=="object")return;let J=G.pollInterval,A,D=$;if(this.options.cwd&&!H0.isAbsolute($))D=H0.join(this.options.cwd,$);let N=new Date,W=this._pendingWrites;function O(Y){vZ(D,(H,L)=>{if(H||!W.has($)){if(H&&H.code!=="ENOENT")X(H);return}let F=Number(new Date);if(Y&&L.size!==Y.size)W.get($).lastChange=F;let j=W.get($);if(F-j.lastChange>=w)W.delete($),X(void 0,L);else A=setTimeout(O,J,L)})}if(!W.has($))W.set($,{lastChange:N,cancelWait:()=>{return W.delete($),clearTimeout(A),E}}),A=setTimeout(O,J)}_isIgnored($,w){if(this.options.atomic&&nZ.test($))return!0;if(!this._userIgnored){let{cwd:E}=this.options,G=(this.options.ignored||[]).map(O3(E)),A=[...[...this._ignoredPaths].map(O3(E)),...G];this._userIgnored=oZ(A,void 0)}return this._userIgnored($,w)}_isntIgnored($,w){return!this._isIgnored($,w)}_getWatchHelpers($){return new L3($,this.options.followSymlinks,this)}_getWatchedDir($){let w=H0.resolve($);if(!this._watched.has(w))this._watched.set(w,new H3(w,this._boundRemove));return this._watched.get(w)}_hasReadPermissions($){if(this.options.ignorePermissionErrors)return!0;return Boolean(Number($.mode)&256)}_remove($,w,E){let X=H0.join($,w),G=H0.resolve(X);if(E=E!=null?E:this._watched.has(X)||this._watched.has(G),!this._throttle("remove",X,100))return;if(!E&&this._watched.size===1)this.add($,w,!0);this._getWatchedDir(X).getChildren().forEach((Y)=>this._remove(X,Y));let D=this._getWatchedDir($),N=D.has(w);if(D.remove(w),this._symlinkPaths.has(G))this._symlinkPaths.delete(G);let W=X;if(this.options.cwd)W=H0.relative(this.options.cwd,X);if(this.options.awaitWriteFinish&&this._pendingWrites.has(W)){if(this._pendingWrites.get(W).cancelWait()===y0.ADD)return}this._watched.delete(X),this._watched.delete(G);let O=E?y0.UNLINK_DIR:y0.UNLINK;if(N&&!this._isIgnored(X))this._emit(O,X);this._closePath(X)}_closePath($){this._closeFile($);let w=H0.dirname($);this._getWatchedDir(w).remove(H0.basename($))}_closeFile($){let w=this._closers.get($);if(!w)return;w.forEach((E)=>E()),this._closers.delete($)}_addPathCloser($,w){if(!w)return;let E=this._closers.get($);if(!E)E=[],this._closers.set($,E);E.push(w)}_readdirp($,w){if(this.closed)return;let E={type:y0.ALL,alwaysStat:!0,lstat:!0,...w,depth:0},X=eL($,E);return this._streams.add(X),X.once(X3,()=>{X=void 0}),X.once(yN,()=>{if(X)this._streams.delete(X),X=void 0}),X}}function sZ($,w={}){let E=new nN(w);return E.add($),E}var F3={watch:sZ,FSWatcher:nN};i$();nw();var pG=Z0("runner:watcher"),TX=new Map;async function M3(){let w=await x().query.jobs.findMany({where:V(I0.enabled,!0)});for(let E of w)if(E.trigger_type==="watch"&&E.watch_path)aZ(E.id,E.name,E.watch_path);pG.info(`Watchers started. ${TX.size} paths watched.`)}function aZ($,w,E){if(TX.has($))TX.get($)?.close().catch(()=>{});let X=F3.watch(E,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:500,pollInterval:100}});X.on("add",(G)=>j3($,w,G)),X.on("change",(G)=>j3($,w,G)),TX.set($,X),pG.info(`Watching: ${E} \u2192 ${w}`)}async function j3($,w,E){pG.info(`Watch trigger: ${w} (${E})`);try{await A1({jobId:$,triggerBy:"watch",envOverrides:{WATCH_PATH:E}})}catch(X){pG.error(`Watch job failed: ${w}`,X)}}async function R3(){for(let[,$]of TX)await $.close();TX.clear(),pG.info("Watchers stopped.")}C$();async function eZ($,w,E,X,G,J){let A=`${$}${X}`;if(J){let N=new URLSearchParams;for(let[O,Y]of Object.entries(J))if(Y!==void 0)N.set(O,String(Y));let W=N.toString();if(W)A+=`?${W}`}let D={"Content-Type":"application/json"};if(w)D.Authorization=`Bearer ${w}`;try{let N=await fetch(A,{method:E,headers:D,...G!==void 0?{body:JSON.stringify(G)}:{}});if(N.status===204)return{data:null,error:null};let W=await N.json();if(!N.ok){let O=W;return{data:null,error:{error:O.error??"Unknown error",code:O.code??"UNKNOWN"}}}return{data:W,error:null}}catch(N){return{data:null,error:{error:String(N),code:"NETWORK_ERROR"}}}}function e($){let w=O0(),E=$?.baseUrl??`http://${w.api.host}:${w.api.port}`,X=$?.secret??w.api.secret,G=(J,A,D,N)=>eZ(E,X,J,A,D,N);return{tasks:{list:(J)=>G("GET","/tasks",void 0,J),get:(J)=>G("GET",`/tasks/${J}`),create:(J)=>G("POST","/tasks",J),update:(J,A)=>G("PATCH",`/tasks/${J}`,A),delete:(J)=>G("DELETE",`/tasks/${J}`),addComment:(J,A,D="human")=>G("POST",`/tasks/${J}/comments`,{content:A,author:D}),listComments:(J)=>G("GET",`/tasks/${J}/comments`),listLinks:(J)=>G("GET",`/tasks/${J}/links`),addLink:(J,A)=>G("POST",`/tasks/${J}/links`,A),deleteLink:(J,A)=>G("DELETE",`/tasks/${J}/links/${A}`)},memories:{list:(J)=>G("GET","/memories",void 0,J),search:(J,A)=>G("GET","/memories/search",void 0,{q:J,scope:A?.scope,project_id:A?.project_id,limit:A?.limit}),create:(J)=>G("POST","/memories",J),delete:(J)=>G("DELETE",`/memories/${J}`)},jobs:{list:(J)=>G("GET","/jobs",void 0,J),get:(J)=>G("GET",`/jobs/${J}`),create:(J)=>G("POST","/jobs",J),update:(J,A)=>G("PATCH",`/jobs/${J}`,A),delete:(J)=>G("DELETE",`/jobs/${J}`),trigger:(J)=>G("POST",`/jobs/${J}/trigger`),runs:(J,A)=>G("GET",`/jobs/${J}/runs`,void 0,{limit:A}),runLogs:(J,A,D)=>G("GET",`/jobs/${J}/runs/${A}/logs`,void 0,D)},prompts:{list:(J)=>G("GET","/prompts",void 0,J),get:(J)=>G("GET",`/prompts/${J}`),create:(J)=>G("POST","/prompts",J),update:(J,A)=>G("PATCH",`/prompts/${J}`,A),delete:(J)=>G("DELETE",`/prompts/${J}`),render:(J,A)=>G("POST",`/prompts/${J}/render`,{vars:A??{}}),history:(J,A)=>G("GET",`/prompts/${J}/history`,void 0,{limit:A})},projects:{list:(J)=>G("GET","/projects",void 0,J),get:(J)=>G("GET",`/projects/${J}`),getByName:(J)=>G("GET",`/projects/by-name/${encodeURIComponent(J)}`),summary:(J)=>G("GET",`/projects/${J}/summary`),create:(J)=>G("POST","/projects",J),update:(J,A)=>G("PATCH",`/projects/${J}`,A),delete:(J)=>G("DELETE",`/projects/${J}`),addComment:(J,A,D="human")=>G("POST",`/projects/${J}/comments`,{content:A,author:D}),listComments:(J)=>G("GET",`/projects/${J}/comments`)},sessions:{list:(J)=>G("GET","/sessions",void 0,J),get:(J)=>G("GET",`/sessions/${J}`)},health:{check:()=>G("GET","/health")},gateway:{status:()=>G("GET","/gateway/status"),send:(J)=>G("POST","/gateway/send",J)}}}var tw=process.env.ORC_HOME??eA(Dv(),".orc"),xX0=eA(tw,"daemon.log"),bX=eA(tw,"daemon.pid");function Nv(){Gv(eA(tw,"logs"),{recursive:!0})}function aA(){try{return Number(Jv(bX,"utf-8").trim())}catch{return null}}function Wv(){Av(bX,String(process.pid))}function Vj(){try{V$("fs").unlinkSync(bX)}catch{}}function Pj(){let $=new $$("daemon").description("Run the API + scheduler + file watchers + gateway as one persistent process");return $.command("start",{isDefault:!0}).description("Start the daemon (use global --port / --host / --db / --secret to configure)").action(async()=>{Nv();let w=aA();if(w)try{process.kill(w,0),console.error(`[orc] daemon already running (pid ${w}). Use: orc daemon stop`),process.exit(1)}catch{}let E=O0();Wv(),await Promise.resolve().then(() => (P9(),V9)),console.log(`[orc] home ${tw}`),console.log(`[orc] db ${E.db.path}`),console.log(`[orc] API http://${E.api.host}:${E.api.port}`),console.log(`[orc] pid ${process.pid} -> ${bX}`),await rL(),await M3(),await PN(),console.log(`[orc] Scheduler + watchers + gateway active. Ctrl+C to stop.
|
|
580
580
|
`);let X=async(G)=>{process.stdout.write(`
|
|
581
581
|
[orc] ${G} - shutting down...
|
|
582
|
-
`),
|
|
583
|
-
`),process.exit(0)};process.on("SIGINT",()=>void X("SIGINT")),process.on("SIGTERM",()=>void X("SIGTERM")),await new Promise(()=>{})}),$.command("stop").description("Stop the running daemon").action(()=>{let w=
|
|
584
|
-
`);for(let J of G){let A=J.trigger_type==="cron"?`cron(${J.cron_expr??"?"})`:J.trigger_type,D=J.last_run_at?new Date(J.last_run_at).toISOString().slice(0,19):"never",N=`runs:${J.run_count}`,W=J.enabled?"\u25CF":"\u25CB";console.log(` ${W} ${J.name.padEnd(24)} ${A.padEnd(24)} last:${D.padEnd(20)} ${N}`)}}),$}function
|
|
585
|
-
`)}function qj(){let $=new $$("project").description("Manage projects");return $.command("list").description("List projects").option("--status <s>","Filter by status").option("-t, --tag <tag>","Filter by tag").option("-l, --limit <n>","Max results","20").action(async(w)=>{let E=e(),{data:X,error:G}=await E.projects.list({status:w.status,tag:w.tag,limit:Number(w.limit)});if(G)return console.error("Error:",G);let J=X?.projects??[];if(t())return $0({projects:J});if(J.length===0)return console.log("No projects found.");for(let A of J){let{data:D}=await E.projects.summary(A.id),W=`${Nv(A.status)} ${A.name.padEnd(18)} (${A.status})`;if(D){let O=D.tasks.total,Y=D.tasks.by_status.review??0,H=Y>0?`${O} tasks (${Y} review)`:`${O} tasks`;W+=` ${H} ${D.memories} mems ${D.jobs} jobs`}console.log(W)}}),$.command("add <name>").description("Create a new project").option("-d, --description <text>","Project description").option("--scope <s>","Project scope").option("--tags <csv>","Comma-separated tags").action(async(w,E)=>{if(!/^[a-zA-Z0-9_-]+$/.test(w))return console.error("Invalid project name: only [a-zA-Z0-9_-] characters allowed.");let X=e(),G=E.tags?E.tags.split(",").map((N)=>N.trim()):void 0,{data:J,error:A}=await X.projects.create({name:w,description:E.description,scope:E.scope,tags:G});if(A)return console.error("Error:",A);if(t())return $0(J);if(!O0().activeProject){let N=Vj();N.activeProject=w,K9(N)}console.log(`Created: ${J?.name} [${J?.id.slice(-6)}]`)}),$.command("show [name]").description("Show project details").action(async(w)=>{let E=e(),X=w??O0().activeProject;if(!X)return console.error("No project set. Use -p <name> or 'orc project use <name>'");let{data:G,error:J}=await E.projects.getByName(X);if(J||!G)return console.error(`Project not found: ${X}`);let[A,D,N,W]=await Promise.all([E.projects.summary(G.id),E.tasks.list({project_id:G.id}),E.jobs.list({project_id:G.id}),E.memories.list({project_id:G.id})]),O=A.data,Y=D.data?.tasks??[],H=N.data?.jobs??[],L=W.data?.memories??[];if(t())return $0({project:G,summary:O??null,tasks:Y,jobs:H,memories:L});if(console.log(`${G.name} (${G.status})`),G.description)console.log(` ${G.description}`);if(console.log(),O){let M=O.tasks.by_status,z=Object.entries(M).filter(([,B])=>B>0).map(([B,Q])=>`${B}: ${Q}`);if(console.log(`Tasks (${O.tasks.total})`),z.length>0)console.log(` ${z.join(" ")}`);console.log()}for(let M of Y.slice(0,10)){let z=Ov(M.status),B=Uv(M.priority);console.log(` ${z} ${B} [${M.id.slice(-6)}] ${M.title.padEnd(36)} ${M.status}`)}if(Y.length>10)console.log(` ... and ${Y.length-10} more`);console.log(),console.log(`Jobs (${H.length})`);for(let M of H){let z=M.trigger_type==="cron"&&M.cron_expr?`cron(${M.cron_expr})`:M.trigger_type;console.log(` \u25CF ${M.name.padEnd(20)} ${z} runs:${M.run_count}`)}console.log();let F=O?.memories??L.length,j=L.slice(0,5);console.log(`Memories (${j.length} of ${F})`);for(let M of j){let z=M.scope?`[${M.scope}]`:"",B=Wv(M.created_at);console.log(` \u2022 ${z} ${M.content.slice(0,50).padEnd(50)} ${B}`)}}),$.command("use <name>").description("Set active project").option("--clear","Unset active project").action(async(w,E)=>{let X=Vj();if(E.clear)return delete X.activeProject,K9(X),console.log("Active project cleared");let G=e(),{data:J,error:A}=await G.projects.getByName(w);if(A||!J)return console.error(`Project not found: ${w}`);if(X.activeProject=w,K9(X),t())return $0({activeProject:w});console.log(`Active project: ${w}`)}),$.command("update <name>").description("Update a project").option("--name <n>","New name").option("-d, --description <text>","Description").option("--status <s>","Status (active/paused/archived)").option("--scope <s>","Scope").option("--tags <csv>","Comma-separated tags").action(async(w,E)=>{let X=e(),{data:G,error:J}=await X.projects.getByName(w);if(J||!G)return console.error(`Project not found: ${w}`);if(g$())return u$("update",`project ${w}`);let A=E.tags?E.tags.split(",").map((W)=>W.trim()):void 0,{data:D,error:N}=await X.projects.update(G.id,{name:E.name,description:E.description,status:E.status,scope:E.scope,tags:A});if(N)return console.error("Error:",N);if(t())return $0(D);console.log(`Updated: ${D?.name} [${D?.id.slice(-6)}]`)}),$.command("archive <name>").description("Archive a project").action(async(w)=>{let E=e(),{data:X,error:G}=await E.projects.getByName(w);if(G||!X)return console.error(`Project not found: ${w}`);if(g$())return u$("archive",`project ${w}`);let{data:J,error:A}=await E.projects.update(X.id,{status:"archived"});if(A)return console.error("Error:",A);if(t())return $0(J);console.log(`Archived: ${J?.name} [${J?.id.slice(-6)}]`)}),$.command("delete <name>").description("Delete a project").action(async(w)=>{let E=e(),{data:X,error:G}=await E.projects.getByName(w);if(G||!X)return console.error(`Project not found: ${w}`);if(g$())return u$("delete",`project ${w}`);let{error:J}=await E.projects.delete(X.id);if(J)return console.error("Error:",J);if(t())return $0({deleted:X.id,name:w});console.log(`Deleted project: ${w} [${X.id.slice(-6)}]`)}),$}function Sj(){let $=new $$("job").description("Manage jobs");return $.command("list").description("List jobs").option("-p, --project <name>","Filter by project name").option("--no-project","Show all jobs").action(async(w)=>{let E=e(),X=w.project===!1,G=X?null:await g1(E,{project:w.project,noProject:X}),{data:J,error:A}=await E.jobs.list(G?{project_id:G.id}:{});if(A)return console.error("Error:",A);let D=J?.jobs??[];if(t())return $0({jobs:D});if(D.length===0)return console.log("No jobs found.");for(let N of D){let W=N.enabled?"\u25CF":"\u25CB",O=N.cron_expr?`cron(${N.cron_expr})`:N.trigger_type;console.log(`${W} ${N.name.padEnd(24)} ${O.padEnd(20)} runs:${N.run_count}`)}}),$.command("add <name>").description("Create a job").requiredOption("-c, --command <cmd>","Shell command to run").option("--trigger <type>","Trigger type (manual/cron/watch/one-shot/webhook)","manual").option("--cron <expr>","Cron expression (e.g. '0 22 * * *' or '*/30 * * * * *' every 30s)").option("--watch <path>","Watch path for file changes").option("--timeout <secs>","Timeout in seconds","300").option("--retries <n>","Max retries","0").option("--notify <when>","Notify on: never/failure/always","failure").option("-d, --description <text>","Description").option("-p, --project <name>","Project name").option("--no-project","Create without project").action(async(w,E)=>{let X=e(),G=E.project===!1,J=G?null:await g1(X,{project:E.project,noProject:G}),{data:A,error:D}=await X.jobs.create({name:w,...J?{project_id:J.id}:{},description:E.description,command:E.command,trigger_type:E.trigger,cron_expr:E.cron,watch_path:E.watch,timeout_secs:Number(E.timeout),max_retries:Number(E.retries),notify_on:E.notify});if(D||!A)return console.error("Error:",D);if(t())return $0(A);console.log(`Created job: ${A.name} [${A.id.slice(-6)}]`)}),$.command("run <name-or-id>").description("Manually trigger a job").action(async(w)=>{let E=e(),{data:X,error:G}=await E.jobs.list();if(G)return console.error("Error:",G);let J=X?.jobs.find((N)=>N.name===w||N.id===w);if(!J)return console.error(`Job not found: ${w}`);let{data:A,error:D}=await E.jobs.trigger(J.id);if(D||!A)return console.error("Error:",D);if(t())return $0(A);console.log(`Triggered job ${J.name} \u2192 run: ${A.run_id}`)}),$.command("show <name-or-id>").description("Show job details").action(async(w)=>{let E=e(),{data:X,error:G}=await E.jobs.list();if(G)return console.error("Error:",G);let J=X?.jobs.find((W)=>W.name===w||W.id===w);if(!J)return console.error(`Job not found: ${w}`);let{data:A,error:D}=await E.jobs.get(J.id);if(D||!A)return console.error("Error:",D);if(t())return $0(A);let N=[["Name",A.name],["ID",A.id],["Description",A.description],["Command",A.command],["Trigger",A.trigger_type],["Cron",A.cron_expr],["Enabled",A.enabled],["Timeout (s)",A.timeout_secs],["Max retries",A.max_retries],["Overlap",A.overlap],["Notify on",A.notify_on],["Project ID",A.project_id],["Run count",A.run_count],["Last run",A.last_run_at],["Created",A.created_at],["Updated",A.updated_at]];for(let[W,O]of N)if(O!==void 0&&O!==null&&O!=="")console.log(`${W.padEnd(14)} ${O}`)}),$.command("delete <name-or-id>").description("Delete a job").action(async(w)=>{let E=e(),{data:X,error:G}=await E.jobs.list();if(G)return console.error("Error:",G);let J=X?.jobs.find((D)=>D.name===w||D.id===w);if(!J)return console.error(`Job not found: ${w}`);if(g$())return u$("delete",`job ${J.name}`);let{error:A}=await E.jobs.delete(J.id);if(A)return console.error("Error:",A);if(t())return $0({deleted:J.id,name:J.name});console.log(`Deleted job: ${J.name} [${J.id.slice(-6)}]`)}),$.command("update <name-or-id>").description("Update a job").option("--name <n>","New name").option("-d, --description <text>","Description").option("-c, --command <cmd>","Shell command").option("--trigger <type>","Trigger type").option("--cron <expr>","Cron expression").option("--timeout <secs>","Timeout in seconds").option("--retries <n>","Max retries").option("--notify <when>","Notify on: never/failure/always").option("--enabled","Enable the job").option("--disabled","Disable the job").action(async(w,E)=>{let X=e(),{data:G,error:J}=await X.jobs.list();if(J)return console.error("Error:",J);let A=G?.jobs.find((O)=>O.name===w||O.id===w);if(!A)return console.error(`Job not found: ${w}`);let D={};if(E.name)D.name=E.name;if(E.description)D.description=E.description;if(E.command)D.command=E.command;if(E.trigger)D.trigger_type=E.trigger;if(E.cron)D.cron_expr=E.cron;if(E.timeout)D.timeout_secs=Number(E.timeout);if(E.retries)D.max_retries=Number(E.retries);if(E.notify)D.notify_on=E.notify;if(E.enabled)D.enabled=!0;if(E.disabled)D.enabled=!1;if(g$())return u$("update",`job ${A.name}`,D);let{data:N,error:W}=await X.jobs.update(A.id,D);if(W||!N)return console.error("Error:",W);if(t())return $0(N);console.log(`Updated job: ${N.name} [${N.id.slice(-6)}]`)}),$.command("runs <name-or-id>").description("Show recent runs for a job").option("-l, --limit <n>","Max results","10").option("-s, --sessions","Show linked agent sessions per run").option("--logs","Show stdout/stderr logs for each run").action(async(w,E)=>{let X=e(),{data:G,error:J}=await X.jobs.list();if(J)return console.error("Error:",J);let A=G?.jobs.find((O)=>O.name===w||O.id===w);if(!A)return console.error(`Job not found: ${w}`);let{data:D,error:N}=await X.jobs.runs(A.id,Number(E.limit));if(N)return console.error("Error:",N);let W=D?.runs??[];if(t())return $0({runs:W});if(W.length===0)return console.log("No runs yet.");for(let O of W){let Y=Yv(O.status),H=O.started_at&&O.ended_at?`${Math.round((new Date(O.ended_at).getTime()-new Date(O.started_at).getTime())/1000)}s`:"-";if(console.log(`${Y} ${O.status.padEnd(10)} ${O.created_at.slice(0,19)} ${H} [${O.id.slice(-6)}]`),E.logs){let{data:L}=await X.jobs.runLogs(A.id,O.id);for(let F of L?.logs??[]){let j=F.stream==="stderr"?" ERR":" OUT";console.log(`${j} ${F.line}`)}}if(E.sessions){let{data:L}=await X.sessions.list({job_run_id:O.id,limit:5});for(let F of L?.sessions??[]){let j=F.summary?` ${F.summary.split(`
|
|
586
|
-
`)[0]?.slice(0,60)}`:"";console.log(` \u21B3 session ${F.agent}${F.agent_version?`/${F.agent_version}`:""}${j}`)}}}}),$}function Yv($){return{pending:"\u25CB",running:"\u25D0",success:"\u25CF",failed:"\u2715",cancelled:"\u2298",skipped:"\u21B7"}[$]??"?"}function bj(){let $=new $$("mem").description("Manage memory");return $.command("search <query>").description("Search memories").option("-s, --scope <scope>","Scope filter").option("-l, --limit <n>","Max results","10").option("-p, --project <name>","Filter by project name").option("--no-project","Search all memories").action(async(w,E)=>{let X=e(),G=E.project===!1,J=G?null:await g1(X,{project:E.project,noProject:G}),{data:A,error:D}=await X.memories.search(w,{scope:E.scope,...J?{project_id:J.id}:{},limit:Number(E.limit)});if(D)return console.error("Error:",D);let N=A?.results??[];if(t())return $0({results:N});if(N.length===0)return console.log("No memories found.");for(let W of N){let O=kj(W.created_at),Y=W.scope?`[${W.scope}]`:"";console.log(`\u2022 ${W.content.slice(0,80)} ${Y} ${O}`)}}),$.command("add <content>").description("Store a memory").option("-s, --scope <scope>","Scope").option("--type <type>","Type (fact/decision/event/rule/discovery)","fact").option("--source <source>","Source reference").option("--importance <level>","Importance (low/normal/high/critical)","normal").option("-t, --tags <tags>","Comma-separated tags").option("-p, --project <name>","Project name").option("--no-project","Create without project").action(async(w,E)=>{let X=e(),G=E.project===!1,J=G?null:await g1(X,{project:E.project,noProject:G}),{data:A,error:D}=await X.memories.create({content:w,...J?{project_id:J.id}:{},type:E.type,scope:E.scope,source:E.source,importance:E.importance,...E.tags?{tags:E.tags.split(",").map((N)=>N.trim())}:{}});if(D)return console.error("Error:",D);if(t())return $0(A);console.log(`Stored: [${A?.id.slice(-6)}] [${E.type}] ${A?.content.slice(0,60)}`)}),$.command("list").description("List recent memories").option("-s, --scope <scope>","Scope filter").option("-l, --limit <n>","Max results","20").option("-p, --project <name>","Filter by project name").option("--no-project","Show all memories").action(async(w)=>{let E=e(),X=w.project===!1,G=X?null:await g1(E,{project:w.project,noProject:X}),{data:J,error:A}=await E.memories.list({scope:w.scope,...G?{project_id:G.id}:{},limit:Number(w.limit)});if(A)return console.error("Error:",A);let D=J?.memories??[];if(t())return $0({memories:D});if(D.length===0)return console.log("No memories found.");for(let N of D){let W=kj(N.created_at),O=N.scope?`[${N.scope}]`:"";console.log(`\u2022 [${N.id.slice(-6)}] ${N.content.slice(0,70)} ${O} ${W}`)}}),$.command("show <id>").description("Show memory details").action(async(w)=>{let E=e(),{data:X,error:G}=await E.memories.list({limit:200});if(G)return console.error("Error:",G);let J=(X?.memories??[]).find((D)=>D.id===w||D.id.endsWith(w));if(!J)return console.error(`Memory not found: ${w}`);if(t())return $0(J);let A=[["ID",J.id],["Content",J.content],["Scope",J.scope],["Source",J.source],["Importance",J.importance],["Project ID",J.project_id],["Tags",J.tags?.join(", ")],["Expires",J.expires_at],["Created",J.created_at],["Updated",J.updated_at]];for(let[D,N]of A)if(N!==void 0&&N!==null&&N!=="")console.log(`${D.padEnd(14)} ${N}`)}),$.command("delete <id>").description("Delete a memory").action(async(w)=>{let E=e(),{data:X,error:G}=await E.memories.list({limit:200});if(G)return console.error("Error:",G);let J=(X?.memories??[]).find((D)=>D.id===w||D.id.endsWith(w));if(!J)return console.error(`Memory not found: ${w}`);if(g$())return u$("delete",`memory [${J.id.slice(-6)}]`,{content:J.content.slice(0,80)});let{error:A}=await E.memories.delete(J.id);if(A)return console.error("Error:",A);if(t())return $0({deleted:J.id});console.log(`Deleted memory: [${J.id.slice(-6)}] ${J.content.slice(0,60)}`)}),$}function kj($){let w=Date.now()-new Date($).getTime(),E=Math.floor(w/60000);if(E<60)return`${E}m ago`;let X=Math.floor(E/60);if(X<24)return`${X}h ago`;return`${Math.floor(X/24)}d ago`}function Zj(){let $=new $$("prompt").description("Manage prompts and skills");return $.command("list").description("List prompts").option("--skill","Show skills only").option("-l, --limit <n>","Max results","20").action(async(w)=>{let E=e(),{data:X,error:G}=await E.prompts.list({limit:Number(w.limit)});if(G)return console.error("Error:",G);let J=X?.prompts??[];if(w.skill)J=J.filter((A)=>A.is_skill);if(t())return $0({prompts:J});if(J.length===0)return console.log("No prompts found.");for(let A of J){let D=A.id.slice(-6),N=A.is_skill?Y6(" [skill]","36"):"",W=Y6(`v${A.version}`,"2"),O=A.name.length>40?`${A.name.slice(0,39)}\u2026`:A.name;console.log(` [${D}] ${O.padEnd(42)} ${W}${N}`)}}),$.command("show <id>").description("Show prompt details").action(async(w)=>{let E=e(),X=await U6(E,w);if(!X)return;let{data:G,error:J}=await E.prompts.get(X);if(J)return console.error("Error:",J);if(!G)return console.error("Prompt not found.");if(t())return $0(G);if(console.log(Y6(G.name,"1")),console.log(),G.description)console.log(` ${G.description}`);if(console.log(` id: ${G.id}`),console.log(` version: ${G.version}`),console.log(` is_skill: ${G.is_skill}`),G.skill_dir)console.log(` skill_dir: ${G.skill_dir}`);if(G.skill_version)console.log(` skill_ver: ${G.skill_version}`);if(console.log(` pinned: ${G.pinned}`),G.tags?.length)console.log(` tags: ${G.tags.join(", ")}`);if(G.last_used_at)console.log(` last_used: ${G.last_used_at}`);console.log(` created: ${G.created_at}`),console.log(` updated: ${G.updated_at}`),console.log(),console.log(Y6("\u2500\u2500 template \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","2")),console.log(G.template)}),$.command("add <name>").description("Create a new prompt").option("-c, --content <text>","Prompt template content").option("-m, --model <model>","Model name").option("-t, --temperature <t>","Temperature").option("--skill","Mark as skill").option("--variables <csv>","Comma-separated variable names").option("-d, --description <text>","Description").option("--tags <csv>","Comma-separated tags").option("--pinned","Pin this prompt").action(async(w,E)=>{let X=e(),G=E.content??"",{data:J,error:A}=await X.prompts.create({name:w,template:G,description:E.description,is_skill:E.skill??!1,tags:E.tags?E.tags.split(",").map((D)=>D.trim()):void 0,pinned:E.pinned??!1});if(A)return console.error("Error:",A);if(t())return $0(J);console.log(`Created: [${J?.id.slice(-6)}] ${J?.name}`)}),$.command("update <id>").description("Update a prompt").option("-c, --content <text>","Prompt template content").option("-n, --name <name>","Prompt name").option("-m, --model <model>","Model name").option("-t, --temperature <t>","Temperature").option("--skill","Mark as skill").option("--no-skill","Unmark as skill").option("--variables <csv>","Comma-separated variable names").option("-d, --description <text>","Description").option("--tags <csv>","Comma-separated tags").option("--pinned","Pin this prompt").option("--no-pinned","Unpin this prompt").action(async(w,E)=>{let X=e(),G=await U6(X,w);if(!G)return;let J={};if(E.content!==void 0)J.template=E.content;if(E.name!==void 0)J.name=E.name;if(E.description!==void 0)J.description=E.description;if(E.skill!==void 0)J.is_skill=E.skill;if(E.tags)J.tags=E.tags.split(",").map((N)=>N.trim());if(E.pinned!==void 0)J.pinned=E.pinned;if(g$())return u$("update",`prompt [${G.slice(-6)}]`,J);let{data:A,error:D}=await X.prompts.update(G,J);if(D)return console.error("Error:",D);if(t())return $0(A);console.log(`Updated: [${A?.id.slice(-6)}] ${A?.name}`)}),$.command("delete <id>").description("Delete a prompt").action(async(w)=>{let E=e(),X=await U6(E,w);if(!X)return;if(g$())return u$("delete",`prompt ${X}`);let{error:G}=await E.prompts.delete(X);if(G)return console.error("Error:",G);if(t())return $0({deleted:X});console.log(`Deleted: ${X}`)}),$.command("render <id>").description("Render a prompt with variables").option("--var <key=value>","Variable (repeatable)",Hv,[]).action(async(w,E)=>{let X=e(),G=await U6(X,w);if(!G)return;let J={};for(let N of E.var){let W=N.indexOf("=");if(W===-1)return console.error(`Invalid variable format: ${N} (expected key=value)`);J[N.slice(0,W)]=N.slice(W+1)}let{data:A,error:D}=await X.prompts.render(G,J);if(D)return console.error("Error:",D);if(t())return $0(A);console.log(A?.rendered)}),$.command("history <id>").description("Show version history").option("-l, --limit <n>","Max results","20").action(async(w,E)=>{let X=e(),G=await U6(X,w);if(!G)return;let{data:J,error:A}=await X.prompts.history(G,Number(E.limit));if(A)return console.error("Error:",A);let D=J?.history??[];if(t())return $0({history:D});if(D.length===0)return console.log("No history found.");for(let N of D){let W=N.changed_at.slice(0,19).replace("T"," ");console.log(` v${String(N.version).padEnd(4)} ${Y6(W,"2")} by ${N.changed_by} ${N.name}`)}}),$}function Hv($,w){return w.concat([$])}async function U6($,w){if(w.length===26)return w;let{data:E}=await $.prompts.list({limit:200}),X=(E?.prompts??[]).find((G)=>G.id.endsWith(w)||G.id===w);if(!X)return console.error(`Prompt not found: ${w}`),null;return X.id}function Y6($,w){return process.stdout.isTTY?`\x1B[${w}m${$}\x1B[0m`:$}C$();var Cj=["task","memory","job","project","prompt","session"];function Lv(){try{let $=O0();return`http://${$.api.host}:${$.api.port}`}catch{return process.env.ORC_API_BASE??"http://127.0.0.1:7700"}}function Fv(){let $={},w=process.env.ORC_API_SECRET??(()=>{try{return O0().api.secret}catch{return}})();if(w)$.Authorization=`Bearer ${w}`;return $}var jv={task:["Task","CreateTask","UpdateTask","Comment","TaskLink"],memory:["Memory","CreateMemory"],job:["Job","CreateJob","UpdateJob","JobRun"],project:["Project","CreateProject","UpdateProject"],prompt:["Prompt","CreatePrompt","UpdatePrompt"],session:["Session"]};function _j(){return new $$("schema").description("Show resource schemas from the OpenAPI spec (requires running API)").argument("[resource]",`Resource name: ${Cj.join(", ")}`).option("--list","List available schema names").action(async(w,E)=>{let X;try{X=await fetch(`${Lv()}/openapi.json`,{headers:Fv()})}catch{return console.error("Cannot connect to orc API. Is it running? (orc api or orc daemon)")}if(!X.ok)return console.error(`API error: ${X.status}`);let J=(await X.json()).components?.schemas;if(!J)return console.error("No schemas found in OpenAPI spec.");if(E?.list||!w){console.log("Available schemas:");for(let W of Object.keys(J).sort())console.log(` ${W}`);return}let A=w.toLowerCase(),D=jv[A];if(!D)return console.error(`Unknown resource: ${w}. Available: ${Cj.join(", ")}`);let N={};for(let W of D)if(J[W])N[W]=J[W];if(Object.keys(N).length===0)return console.error(`No schemas found for: ${w}`);console.log(JSON.stringify(N,null,2))})}C$();function vj($){let w=Date.now()-new Date($).getTime(),E=Math.floor(w/60000);if(E<60)return`${E}m ago`;let X=Math.floor(E/60);if(X<24)return`${X}h ago`;return`${Math.floor(X/24)}d ago`}function V9(){try{let $=O0();return`http://${$.api.host}:${$.api.port}`}catch{return process.env.ORC_API_BASE??"http://127.0.0.1:7700"}}function P9(){let $={"Content-Type":"application/json"},w=process.env.ORC_API_SECRET??(()=>{try{return O0().api.secret}catch{return}})();if(w)$.Authorization=`Bearer ${w}`;return $}function fj(){let $=new $$("session").description("View session history");return $.command("list").description("List recent sessions").option("-a, --agent <agent>","Filter by agent (claude-code, cursor, codex)").option("-n, --limit <n>","Max results","20").action(async(w)=>{let E=new URLSearchParams({limit:w.limit});if(w.agent)E.set("agent",w.agent);let X;try{X=await fetch(`${V9()}/sessions?${E}`,{headers:P9()})}catch{return console.error("Cannot connect to orc API. Is it running? (orc api or orc daemon)")}if(!X.ok)return console.error(`API error: ${X.status}`);let J=(await X.json()).sessions;if(t())return $0({sessions:J});if(J.length===0)return console.log("No sessions recorded yet.");console.log(`${"ID".padEnd(8)} ${"AGENT".padEnd(16)} ${"WHEN".padEnd(10)} SUMMARY`),console.log("\u2500".repeat(72));for(let A of J){let D=A.id.slice(-6),N=A.agent.padEnd(16),W=vj(A.created_at).padEnd(10),O=(A.summary??"\u2014").slice(0,40);console.log(`${D} ${N} ${W} ${O}`)}}),$.command("show <id>").description("Show session detail with events").option("-e, --events","Show recorded events").option("-s, --snapshot","Show snapshot XML").option("-n, --limit <n>","Max events to show","50").action(async(w,E)=>{let X=w;if(w.length<26){let A=await fetch(`${V9()}/sessions?limit=100`,{headers:P9()}).catch(()=>null);if(A?.ok){let N=(await A.json()).sessions.find((W)=>W.id.endsWith(w)||W.id===w);if(N)X=N.id}}let G;try{G=await fetch(`${V9()}/sessions/${X}`,{headers:P9()})}catch{return console.error("Cannot connect to orc API.")}if(G.status===404)return console.error(`Session not found: ${w}`);if(!G.ok)return console.error(`API error: ${G.status}`);let J=await G.json();if(t())return $0(J);if(console.log(`Session: ${J.id}`),console.log(`Agent: ${J.agent}`),console.log(`When: ${new Date(J.created_at).toLocaleString()} (${vj(J.created_at)})`),J.project_id)console.log(`Project: ${J.project_id}`);if(J.tokens_used)console.log(`Tokens: ${J.tokens_used}`);if(J.summary)console.log(`
|
|
582
|
+
`),pL(),await R3(),await qN(),Vj(),process.stdout.write(`[orc] Stopped.
|
|
583
|
+
`),process.exit(0)};process.on("SIGINT",()=>void X("SIGINT")),process.on("SIGTERM",()=>void X("SIGTERM")),await new Promise(()=>{})}),$.command("stop").description("Stop the running daemon").action(()=>{let w=aA();if(!w){console.log("No daemon running (no pid file at ~/.orc/daemon.pid).");return}try{process.kill(w,"SIGTERM"),console.log(`Sent SIGTERM to daemon (pid ${w}).`)}catch{console.error(`Could not signal pid ${w} - process may already be stopped.`),Vj()}}),$.command("status").description("Show scheduler state and next run times for all active jobs").action(async()=>{let w=e(),{data:E,error:X}=await w.jobs.list();if(X)return console.error("Error:",X);let G=(E?.jobs??[]).filter((J)=>J.enabled&&(J.trigger_type==="cron"||J.trigger_type==="watch"));if(G.length===0){console.log("No scheduled jobs defined."),console.log("Create one with: orc job add <name> --trigger cron --cron '0 22 * * *' ...");return}console.log(`Scheduled jobs:
|
|
584
|
+
`);for(let J of G){let A=J.trigger_type==="cron"?`cron(${J.cron_expr??"?"})`:J.trigger_type,D=J.last_run_at?new Date(J.last_run_at).toISOString().slice(0,19):"never",N=`runs:${J.run_count}`,W=J.enabled?"\u25CF":"\u25CB";console.log(` ${W} ${J.name.padEnd(24)} ${A.padEnd(24)} last:${D.padEnd(20)} ${N}`)}}),$}function qj(){let $=new $$("gateway").description("Inspect and send channel gateway messages");return $.command("status").description("Show enabled adapters and active sessions").action(async()=>{let w=e(),{data:E,error:X}=await w.gateway.status();if(X)console.error(`Error: ${X.error}`),process.exit(1);console.log(E.status)}),$.command("send").description("Send a message to a configured Telegram or Slack chat").requiredOption("--platform <platform>","telegram or slack").requiredOption("--chat <id>","Platform chat/channel ID").requiredOption("--text <text>","Message text").option("--thread <id>","Optional Telegram thread or Slack thread timestamp").action(async(w)=>{let E=e(),{error:X}=await E.gateway.send({platform:w.platform,chat_id:w.chat,text:w.text,thread_id:w.thread});if(X)console.error(`Error: ${X.error}`),process.exit(1);console.log(`Sent message to ${w.platform}:${w.chat}`)}),$}function t(){return process.argv.includes("--json")}function $0($){console.log(JSON.stringify($,null,2))}function M1($){console.error(JSON.stringify({error:$})),process.exit(1)}function g$(){return process.argv.includes("--dry-run")}function u$($,w,E){if(console.log(`[dry-run] Would ${$} ${w}`),E)console.log(JSON.stringify(E,null,2))}C$();import{existsSync as Ov,readFileSync as Uv,writeFileSync as Yv}from"fs";import{homedir as Hv}from"os";import{join as Lv}from"path";async function g1($,w){if(w.noProject)return null;let E=w.project??O0().activeProject;if(!E)console.error("No project set. Use -p <name> or 'orc project use <name>'"),process.exit(1);let{data:X,error:G}=await $.projects.getByName(E);if(G||!X)console.error(`Project not found: ${E}`),process.exit(1);return{id:X.id,name:X.name}}function Fv($){return{active:"\u25CF",paused:"\u25D0",archived:"\u25CB"}[$]??"?"}function jv($){let w=Date.now()-new Date($).getTime(),E=Math.floor(w/60000);if(E<60)return`${E}m ago`;let X=Math.floor(E/60);if(X<24)return`${X}h ago`;return`${Math.floor(X/24)}d ago`}function Mv($){return{todo:"\u25CB",doing:"\u25D0",review:"\u25C9",changes_requested:"\u21A9",blocked:"\u2298",done:"\u25CF",cancelled:"\u2715"}[$]??"?"}function Rv($){return{low:"\u2193",normal:"\u2192",high:"\u2191",critical:"\u203C"}[$]??" "}function kj(){return Lv(Hv(),".orc","config.json")}function Sj(){let $=kj();if(!Ov($))return{};return JSON.parse(Uv($,"utf-8"))}function q9($){Yv(kj(),`${JSON.stringify($,null,2)}
|
|
585
|
+
`)}function bj(){let $=new $$("project").description("Manage projects");return $.command("list").description("List projects").option("--status <s>","Filter by status").option("-t, --tag <tag>","Filter by tag").option("-l, --limit <n>","Max results","20").action(async(w)=>{let E=e(),{data:X,error:G}=await E.projects.list({status:w.status,tag:w.tag,limit:Number(w.limit)});if(G)return console.error("Error:",G);let J=X?.projects??[];if(t())return $0({projects:J});if(J.length===0)return console.log("No projects found.");for(let A of J){let{data:D}=await E.projects.summary(A.id),W=`${Fv(A.status)} ${A.name.padEnd(18)} (${A.status})`;if(D){let O=D.tasks.total,Y=D.tasks.by_status.review??0,H=Y>0?`${O} tasks (${Y} review)`:`${O} tasks`;W+=` ${H} ${D.memories} mems ${D.jobs} jobs`}console.log(W)}}),$.command("add <name>").description("Create a new project").option("-d, --description <text>","Project description").option("--scope <s>","Project scope").option("--tags <csv>","Comma-separated tags").action(async(w,E)=>{if(!/^[a-zA-Z0-9_-]+$/.test(w))return console.error("Invalid project name: only [a-zA-Z0-9_-] characters allowed.");let X=e(),G=E.tags?E.tags.split(",").map((N)=>N.trim()):void 0,{data:J,error:A}=await X.projects.create({name:w,description:E.description,scope:E.scope,tags:G});if(A)return console.error("Error:",A);if(t())return $0(J);if(!O0().activeProject){let N=Sj();N.activeProject=w,q9(N)}console.log(`Created: ${J?.name} [${J?.id.slice(-6)}]`)}),$.command("show [name]").description("Show project details").action(async(w)=>{let E=e(),X=w??O0().activeProject;if(!X)return console.error("No project set. Use -p <name> or 'orc project use <name>'");let{data:G,error:J}=await E.projects.getByName(X);if(J||!G)return console.error(`Project not found: ${X}`);let[A,D,N,W]=await Promise.all([E.projects.summary(G.id),E.tasks.list({project_id:G.id}),E.jobs.list({project_id:G.id}),E.memories.list({project_id:G.id})]),O=A.data,Y=D.data?.tasks??[],H=N.data?.jobs??[],L=W.data?.memories??[];if(t())return $0({project:G,summary:O??null,tasks:Y,jobs:H,memories:L});if(console.log(`${G.name} (${G.status})`),G.description)console.log(` ${G.description}`);if(console.log(),O){let M=O.tasks.by_status,z=Object.entries(M).filter(([,B])=>B>0).map(([B,Q])=>`${B}: ${Q}`);if(console.log(`Tasks (${O.tasks.total})`),z.length>0)console.log(` ${z.join(" ")}`);console.log()}for(let M of Y.slice(0,10)){let z=Mv(M.status),B=Rv(M.priority);console.log(` ${z} ${B} [${M.id.slice(-6)}] ${M.title.padEnd(36)} ${M.status}`)}if(Y.length>10)console.log(` ... and ${Y.length-10} more`);console.log(),console.log(`Jobs (${H.length})`);for(let M of H){let z=M.trigger_type==="cron"&&M.cron_expr?`cron(${M.cron_expr})`:M.trigger_type;console.log(` \u25CF ${M.name.padEnd(20)} ${z} runs:${M.run_count}`)}console.log();let F=O?.memories??L.length,j=L.slice(0,5);console.log(`Memories (${j.length} of ${F})`);for(let M of j){let z=M.scope?`[${M.scope}]`:"",B=jv(M.created_at);console.log(` \u2022 ${z} ${M.content.slice(0,50).padEnd(50)} ${B}`)}}),$.command("use <name>").description("Set active project").option("--clear","Unset active project").action(async(w,E)=>{let X=Sj();if(E.clear)return delete X.activeProject,q9(X),console.log("Active project cleared");let G=e(),{data:J,error:A}=await G.projects.getByName(w);if(A||!J)return console.error(`Project not found: ${w}`);if(X.activeProject=w,q9(X),t())return $0({activeProject:w});console.log(`Active project: ${w}`)}),$.command("update <name>").description("Update a project").option("--name <n>","New name").option("-d, --description <text>","Description").option("--status <s>","Status (active/paused/archived)").option("--scope <s>","Scope").option("--tags <csv>","Comma-separated tags").action(async(w,E)=>{let X=e(),{data:G,error:J}=await X.projects.getByName(w);if(J||!G)return console.error(`Project not found: ${w}`);if(g$())return u$("update",`project ${w}`);let A=E.tags?E.tags.split(",").map((W)=>W.trim()):void 0,{data:D,error:N}=await X.projects.update(G.id,{name:E.name,description:E.description,status:E.status,scope:E.scope,tags:A});if(N)return console.error("Error:",N);if(t())return $0(D);console.log(`Updated: ${D?.name} [${D?.id.slice(-6)}]`)}),$.command("archive <name>").description("Archive a project").action(async(w)=>{let E=e(),{data:X,error:G}=await E.projects.getByName(w);if(G||!X)return console.error(`Project not found: ${w}`);if(g$())return u$("archive",`project ${w}`);let{data:J,error:A}=await E.projects.update(X.id,{status:"archived"});if(A)return console.error("Error:",A);if(t())return $0(J);console.log(`Archived: ${J?.name} [${J?.id.slice(-6)}]`)}),$.command("delete <name>").description("Delete a project").action(async(w)=>{let E=e(),{data:X,error:G}=await E.projects.getByName(w);if(G||!X)return console.error(`Project not found: ${w}`);if(g$())return u$("delete",`project ${w}`);let{error:J}=await E.projects.delete(X.id);if(J)return console.error("Error:",J);if(t())return $0({deleted:X.id,name:w});console.log(`Deleted project: ${w} [${X.id.slice(-6)}]`)}),$}function Zj(){let $=new $$("job").description("Manage jobs");return $.command("list").description("List jobs").option("-p, --project <name>","Filter by project name").option("--no-project","Show all jobs").action(async(w)=>{let E=e(),X=w.project===!1,G=X?null:await g1(E,{project:w.project,noProject:X}),{data:J,error:A}=await E.jobs.list(G?{project_id:G.id}:{});if(A)return console.error("Error:",A);let D=J?.jobs??[];if(t())return $0({jobs:D});if(D.length===0)return console.log("No jobs found.");for(let N of D){let W=N.enabled?"\u25CF":"\u25CB",O=N.cron_expr?`cron(${N.cron_expr})`:N.trigger_type;console.log(`${W} ${N.name.padEnd(24)} ${O.padEnd(20)} runs:${N.run_count}`)}}),$.command("add <name>").description("Create a job").requiredOption("-c, --command <cmd>","Shell command to run").option("--trigger <type>","Trigger type (manual/cron/watch/one-shot/webhook)","manual").option("--cron <expr>","Cron expression (e.g. '0 22 * * *' or '*/30 * * * * *' every 30s)").option("--watch <path>","Watch path for file changes").option("--timeout <secs>","Timeout in seconds","300").option("--retries <n>","Max retries","0").option("--notify <when>","Notify on: never/failure/always","failure").option("-d, --description <text>","Description").option("-p, --project <name>","Project name").option("--no-project","Create without project").action(async(w,E)=>{let X=e(),G=E.project===!1,J=G?null:await g1(X,{project:E.project,noProject:G}),{data:A,error:D}=await X.jobs.create({name:w,...J?{project_id:J.id}:{},description:E.description,command:E.command,trigger_type:E.trigger,cron_expr:E.cron,watch_path:E.watch,timeout_secs:Number(E.timeout),max_retries:Number(E.retries),notify_on:E.notify});if(D||!A)return console.error("Error:",D);if(t())return $0(A);console.log(`Created job: ${A.name} [${A.id.slice(-6)}]`)}),$.command("run <name-or-id>").description("Manually trigger a job").action(async(w)=>{let E=e(),{data:X,error:G}=await E.jobs.list();if(G)return console.error("Error:",G);let J=X?.jobs.find((N)=>N.name===w||N.id===w);if(!J)return console.error(`Job not found: ${w}`);let{data:A,error:D}=await E.jobs.trigger(J.id);if(D||!A)return console.error("Error:",D);if(t())return $0(A);console.log(`Triggered job ${J.name} \u2192 run: ${A.run_id}`)}),$.command("show <name-or-id>").description("Show job details").action(async(w)=>{let E=e(),{data:X,error:G}=await E.jobs.list();if(G)return console.error("Error:",G);let J=X?.jobs.find((W)=>W.name===w||W.id===w);if(!J)return console.error(`Job not found: ${w}`);let{data:A,error:D}=await E.jobs.get(J.id);if(D||!A)return console.error("Error:",D);if(t())return $0(A);let N=[["Name",A.name],["ID",A.id],["Description",A.description],["Command",A.command],["Trigger",A.trigger_type],["Cron",A.cron_expr],["Enabled",A.enabled],["Timeout (s)",A.timeout_secs],["Max retries",A.max_retries],["Overlap",A.overlap],["Notify on",A.notify_on],["Project ID",A.project_id],["Run count",A.run_count],["Last run",A.last_run_at],["Created",A.created_at],["Updated",A.updated_at]];for(let[W,O]of N)if(O!==void 0&&O!==null&&O!=="")console.log(`${W.padEnd(14)} ${O}`)}),$.command("delete <name-or-id>").description("Delete a job").action(async(w)=>{let E=e(),{data:X,error:G}=await E.jobs.list();if(G)return console.error("Error:",G);let J=X?.jobs.find((D)=>D.name===w||D.id===w);if(!J)return console.error(`Job not found: ${w}`);if(g$())return u$("delete",`job ${J.name}`);let{error:A}=await E.jobs.delete(J.id);if(A)return console.error("Error:",A);if(t())return $0({deleted:J.id,name:J.name});console.log(`Deleted job: ${J.name} [${J.id.slice(-6)}]`)}),$.command("update <name-or-id>").description("Update a job").option("--name <n>","New name").option("-d, --description <text>","Description").option("-c, --command <cmd>","Shell command").option("--trigger <type>","Trigger type").option("--cron <expr>","Cron expression").option("--timeout <secs>","Timeout in seconds").option("--retries <n>","Max retries").option("--notify <when>","Notify on: never/failure/always").option("--enabled","Enable the job").option("--disabled","Disable the job").action(async(w,E)=>{let X=e(),{data:G,error:J}=await X.jobs.list();if(J)return console.error("Error:",J);let A=G?.jobs.find((O)=>O.name===w||O.id===w);if(!A)return console.error(`Job not found: ${w}`);let D={};if(E.name)D.name=E.name;if(E.description)D.description=E.description;if(E.command)D.command=E.command;if(E.trigger)D.trigger_type=E.trigger;if(E.cron)D.cron_expr=E.cron;if(E.timeout)D.timeout_secs=Number(E.timeout);if(E.retries)D.max_retries=Number(E.retries);if(E.notify)D.notify_on=E.notify;if(E.enabled)D.enabled=!0;if(E.disabled)D.enabled=!1;if(g$())return u$("update",`job ${A.name}`,D);let{data:N,error:W}=await X.jobs.update(A.id,D);if(W||!N)return console.error("Error:",W);if(t())return $0(N);console.log(`Updated job: ${N.name} [${N.id.slice(-6)}]`)}),$.command("runs <name-or-id>").description("Show recent runs for a job").option("-l, --limit <n>","Max results","10").option("-s, --sessions","Show linked agent sessions per run").option("--logs","Show stdout/stderr logs for each run").action(async(w,E)=>{let X=e(),{data:G,error:J}=await X.jobs.list();if(J)return console.error("Error:",J);let A=G?.jobs.find((O)=>O.name===w||O.id===w);if(!A)return console.error(`Job not found: ${w}`);let{data:D,error:N}=await X.jobs.runs(A.id,Number(E.limit));if(N)return console.error("Error:",N);let W=D?.runs??[];if(t())return $0({runs:W});if(W.length===0)return console.log("No runs yet.");for(let O of W){let Y=zv(O.status),H=O.started_at&&O.ended_at?`${Math.round((new Date(O.ended_at).getTime()-new Date(O.started_at).getTime())/1000)}s`:"-";if(console.log(`${Y} ${O.status.padEnd(10)} ${O.created_at.slice(0,19)} ${H} [${O.id.slice(-6)}]`),E.logs){let{data:L}=await X.jobs.runLogs(A.id,O.id);for(let F of L?.logs??[]){let j=F.stream==="stderr"?" ERR":" OUT";console.log(`${j} ${F.line}`)}}if(E.sessions){let{data:L}=await X.sessions.list({job_run_id:O.id,limit:5});for(let F of L?.sessions??[]){let j=F.summary?` ${F.summary.split(`
|
|
586
|
+
`)[0]?.slice(0,60)}`:"";console.log(` \u21B3 session ${F.agent}${F.agent_version?`/${F.agent_version}`:""}${j}`)}}}}),$}function zv($){return{pending:"\u25CB",running:"\u25D0",success:"\u25CF",failed:"\u2715",cancelled:"\u2298",skipped:"\u21B7"}[$]??"?"}function _j(){let $=new $$("mem").description("Manage memory");return $.command("search <query>").description("Search memories").option("-s, --scope <scope>","Scope filter").option("-l, --limit <n>","Max results","10").option("-p, --project <name>","Filter by project name").option("--no-project","Search all memories").action(async(w,E)=>{let X=e(),G=E.project===!1,J=G?null:await g1(X,{project:E.project,noProject:G}),{data:A,error:D}=await X.memories.search(w,{scope:E.scope,...J?{project_id:J.id}:{},limit:Number(E.limit)});if(D)return console.error("Error:",D);let N=A?.results??[];if(t())return $0({results:N});if(N.length===0)return console.log("No memories found.");for(let W of N){let O=Cj(W.created_at),Y=W.scope?`[${W.scope}]`:"";console.log(`\u2022 ${W.content.slice(0,80)} ${Y} ${O}`)}}),$.command("add <content>").description("Store a memory").option("-s, --scope <scope>","Scope").option("--type <type>","Type (fact/decision/event/rule/discovery)","fact").option("--source <source>","Source reference").option("--importance <level>","Importance (low/normal/high/critical)","normal").option("-t, --tags <tags>","Comma-separated tags").option("-p, --project <name>","Project name").option("--no-project","Create without project").action(async(w,E)=>{let X=e(),G=E.project===!1,J=G?null:await g1(X,{project:E.project,noProject:G}),{data:A,error:D}=await X.memories.create({content:w,...J?{project_id:J.id}:{},type:E.type,scope:E.scope,source:E.source,importance:E.importance,...E.tags?{tags:E.tags.split(",").map((N)=>N.trim())}:{}});if(D)return console.error("Error:",D);if(t())return $0(A);console.log(`Stored: [${A?.id.slice(-6)}] [${E.type}] ${A?.content.slice(0,60)}`)}),$.command("list").description("List recent memories").option("-s, --scope <scope>","Scope filter").option("-l, --limit <n>","Max results","20").option("-p, --project <name>","Filter by project name").option("--no-project","Show all memories").action(async(w)=>{let E=e(),X=w.project===!1,G=X?null:await g1(E,{project:w.project,noProject:X}),{data:J,error:A}=await E.memories.list({scope:w.scope,...G?{project_id:G.id}:{},limit:Number(w.limit)});if(A)return console.error("Error:",A);let D=J?.memories??[];if(t())return $0({memories:D});if(D.length===0)return console.log("No memories found.");for(let N of D){let W=Cj(N.created_at),O=N.scope?`[${N.scope}]`:"";console.log(`\u2022 [${N.id.slice(-6)}] ${N.content.slice(0,70)} ${O} ${W}`)}}),$.command("show <id>").description("Show memory details").action(async(w)=>{let E=e(),{data:X,error:G}=await E.memories.list({limit:200});if(G)return console.error("Error:",G);let J=(X?.memories??[]).find((D)=>D.id===w||D.id.endsWith(w));if(!J)return console.error(`Memory not found: ${w}`);if(t())return $0(J);let A=[["ID",J.id],["Content",J.content],["Scope",J.scope],["Source",J.source],["Importance",J.importance],["Project ID",J.project_id],["Tags",J.tags?.join(", ")],["Expires",J.expires_at],["Created",J.created_at],["Updated",J.updated_at]];for(let[D,N]of A)if(N!==void 0&&N!==null&&N!=="")console.log(`${D.padEnd(14)} ${N}`)}),$.command("delete <id>").description("Delete a memory").action(async(w)=>{let E=e(),{data:X,error:G}=await E.memories.list({limit:200});if(G)return console.error("Error:",G);let J=(X?.memories??[]).find((D)=>D.id===w||D.id.endsWith(w));if(!J)return console.error(`Memory not found: ${w}`);if(g$())return u$("delete",`memory [${J.id.slice(-6)}]`,{content:J.content.slice(0,80)});let{error:A}=await E.memories.delete(J.id);if(A)return console.error("Error:",A);if(t())return $0({deleted:J.id});console.log(`Deleted memory: [${J.id.slice(-6)}] ${J.content.slice(0,60)}`)}),$}function Cj($){let w=Date.now()-new Date($).getTime(),E=Math.floor(w/60000);if(E<60)return`${E}m ago`;let X=Math.floor(E/60);if(X<24)return`${X}h ago`;return`${Math.floor(X/24)}d ago`}function vj(){let $=new $$("prompt").description("Manage prompts and skills");return $.command("list").description("List prompts").option("--skill","Show skills only").option("-l, --limit <n>","Max results","20").action(async(w)=>{let E=e(),{data:X,error:G}=await E.prompts.list({limit:Number(w.limit)});if(G)return console.error("Error:",G);let J=X?.prompts??[];if(w.skill)J=J.filter((A)=>A.is_skill);if(t())return $0({prompts:J});if(J.length===0)return console.log("No prompts found.");for(let A of J){let D=A.id.slice(-6),N=A.is_skill?H6(" [skill]","36"):"",W=H6(`v${A.version}`,"2"),O=A.name.length>40?`${A.name.slice(0,39)}\u2026`:A.name;console.log(` [${D}] ${O.padEnd(42)} ${W}${N}`)}}),$.command("show <id>").description("Show prompt details").action(async(w)=>{let E=e(),X=await Y6(E,w);if(!X)return;let{data:G,error:J}=await E.prompts.get(X);if(J)return console.error("Error:",J);if(!G)return console.error("Prompt not found.");if(t())return $0(G);if(console.log(H6(G.name,"1")),console.log(),G.description)console.log(` ${G.description}`);if(console.log(` id: ${G.id}`),console.log(` version: ${G.version}`),console.log(` is_skill: ${G.is_skill}`),G.skill_dir)console.log(` skill_dir: ${G.skill_dir}`);if(G.skill_version)console.log(` skill_ver: ${G.skill_version}`);if(console.log(` pinned: ${G.pinned}`),G.tags?.length)console.log(` tags: ${G.tags.join(", ")}`);if(G.last_used_at)console.log(` last_used: ${G.last_used_at}`);console.log(` created: ${G.created_at}`),console.log(` updated: ${G.updated_at}`),console.log(),console.log(H6("\u2500\u2500 template \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","2")),console.log(G.template)}),$.command("add <name>").description("Create a new prompt").option("-c, --content <text>","Prompt template content").option("-m, --model <model>","Model name").option("-t, --temperature <t>","Temperature").option("--skill","Mark as skill").option("--variables <csv>","Comma-separated variable names").option("-d, --description <text>","Description").option("--tags <csv>","Comma-separated tags").option("--pinned","Pin this prompt").action(async(w,E)=>{let X=e(),G=E.content??"",{data:J,error:A}=await X.prompts.create({name:w,template:G,description:E.description,is_skill:E.skill??!1,tags:E.tags?E.tags.split(",").map((D)=>D.trim()):void 0,pinned:E.pinned??!1});if(A)return console.error("Error:",A);if(t())return $0(J);console.log(`Created: [${J?.id.slice(-6)}] ${J?.name}`)}),$.command("update <id>").description("Update a prompt").option("-c, --content <text>","Prompt template content").option("-n, --name <name>","Prompt name").option("-m, --model <model>","Model name").option("-t, --temperature <t>","Temperature").option("--skill","Mark as skill").option("--no-skill","Unmark as skill").option("--variables <csv>","Comma-separated variable names").option("-d, --description <text>","Description").option("--tags <csv>","Comma-separated tags").option("--pinned","Pin this prompt").option("--no-pinned","Unpin this prompt").action(async(w,E)=>{let X=e(),G=await Y6(X,w);if(!G)return;let J={};if(E.content!==void 0)J.template=E.content;if(E.name!==void 0)J.name=E.name;if(E.description!==void 0)J.description=E.description;if(E.skill!==void 0)J.is_skill=E.skill;if(E.tags)J.tags=E.tags.split(",").map((N)=>N.trim());if(E.pinned!==void 0)J.pinned=E.pinned;if(g$())return u$("update",`prompt [${G.slice(-6)}]`,J);let{data:A,error:D}=await X.prompts.update(G,J);if(D)return console.error("Error:",D);if(t())return $0(A);console.log(`Updated: [${A?.id.slice(-6)}] ${A?.name}`)}),$.command("delete <id>").description("Delete a prompt").action(async(w)=>{let E=e(),X=await Y6(E,w);if(!X)return;if(g$())return u$("delete",`prompt ${X}`);let{error:G}=await E.prompts.delete(X);if(G)return console.error("Error:",G);if(t())return $0({deleted:X});console.log(`Deleted: ${X}`)}),$.command("render <id>").description("Render a prompt with variables").option("--var <key=value>","Variable (repeatable)",Tv,[]).action(async(w,E)=>{let X=e(),G=await Y6(X,w);if(!G)return;let J={};for(let N of E.var){let W=N.indexOf("=");if(W===-1)return console.error(`Invalid variable format: ${N} (expected key=value)`);J[N.slice(0,W)]=N.slice(W+1)}let{data:A,error:D}=await X.prompts.render(G,J);if(D)return console.error("Error:",D);if(t())return $0(A);console.log(A?.rendered)}),$.command("history <id>").description("Show version history").option("-l, --limit <n>","Max results","20").action(async(w,E)=>{let X=e(),G=await Y6(X,w);if(!G)return;let{data:J,error:A}=await X.prompts.history(G,Number(E.limit));if(A)return console.error("Error:",A);let D=J?.history??[];if(t())return $0({history:D});if(D.length===0)return console.log("No history found.");for(let N of D){let W=N.changed_at.slice(0,19).replace("T"," ");console.log(` v${String(N.version).padEnd(4)} ${H6(W,"2")} by ${N.changed_by} ${N.name}`)}}),$}function Tv($,w){return w.concat([$])}async function Y6($,w){if(w.length===26)return w;let{data:E}=await $.prompts.list({limit:200}),X=(E?.prompts??[]).find((G)=>G.id.endsWith(w)||G.id===w);if(!X)return console.error(`Prompt not found: ${w}`),null;return X.id}function H6($,w){return process.stdout.isTTY?`\x1B[${w}m${$}\x1B[0m`:$}C$();var fj=["task","memory","job","project","prompt","session"];function Bv(){try{let $=O0();return`http://${$.api.host}:${$.api.port}`}catch{return process.env.ORC_API_BASE??"http://127.0.0.1:7700"}}function Qv(){let $={},w=process.env.ORC_API_SECRET??(()=>{try{return O0().api.secret}catch{return}})();if(w)$.Authorization=`Bearer ${w}`;return $}var Iv={task:["Task","CreateTask","UpdateTask","Comment","TaskLink"],memory:["Memory","CreateMemory"],job:["Job","CreateJob","UpdateJob","JobRun"],project:["Project","CreateProject","UpdateProject"],prompt:["Prompt","CreatePrompt","UpdatePrompt"],session:["Session"]};function xj(){return new $$("schema").description("Show resource schemas from the OpenAPI spec (requires running API)").argument("[resource]",`Resource name: ${fj.join(", ")}`).option("--list","List available schema names").action(async(w,E)=>{let X;try{X=await fetch(`${Bv()}/openapi.json`,{headers:Qv()})}catch{return console.error("Cannot connect to orc API. Is it running? (orc api or orc daemon)")}if(!X.ok)return console.error(`API error: ${X.status}`);let J=(await X.json()).components?.schemas;if(!J)return console.error("No schemas found in OpenAPI spec.");if(E?.list||!w){console.log("Available schemas:");for(let W of Object.keys(J).sort())console.log(` ${W}`);return}let A=w.toLowerCase(),D=Iv[A];if(!D)return console.error(`Unknown resource: ${w}. Available: ${fj.join(", ")}`);let N={};for(let W of D)if(J[W])N[W]=J[W];if(Object.keys(N).length===0)return console.error(`No schemas found for: ${w}`);console.log(JSON.stringify(N,null,2))})}C$();function yj($){let w=Date.now()-new Date($).getTime(),E=Math.floor(w/60000);if(E<60)return`${E}m ago`;let X=Math.floor(E/60);if(X<24)return`${X}h ago`;return`${Math.floor(X/24)}d ago`}function S9(){try{let $=O0();return`http://${$.api.host}:${$.api.port}`}catch{return process.env.ORC_API_BASE??"http://127.0.0.1:7700"}}function k9(){let $={"Content-Type":"application/json"},w=process.env.ORC_API_SECRET??(()=>{try{return O0().api.secret}catch{return}})();if(w)$.Authorization=`Bearer ${w}`;return $}function gj(){let $=new $$("session").description("View session history");return $.command("list").description("List recent sessions").option("-a, --agent <agent>","Filter by agent (claude-code, cursor, codex)").option("-n, --limit <n>","Max results","20").action(async(w)=>{let E=new URLSearchParams({limit:w.limit});if(w.agent)E.set("agent",w.agent);let X;try{X=await fetch(`${S9()}/sessions?${E}`,{headers:k9()})}catch{return console.error("Cannot connect to orc API. Is it running? (orc api or orc daemon)")}if(!X.ok)return console.error(`API error: ${X.status}`);let J=(await X.json()).sessions;if(t())return $0({sessions:J});if(J.length===0)return console.log("No sessions recorded yet.");console.log(`${"ID".padEnd(8)} ${"AGENT".padEnd(16)} ${"WHEN".padEnd(10)} SUMMARY`),console.log("\u2500".repeat(72));for(let A of J){let D=A.id.slice(-6),N=A.agent.padEnd(16),W=yj(A.created_at).padEnd(10),O=(A.summary??"\u2014").slice(0,40);console.log(`${D} ${N} ${W} ${O}`)}}),$.command("show <id>").description("Show session detail with events").option("-e, --events","Show recorded events").option("-s, --snapshot","Show snapshot XML").option("-n, --limit <n>","Max events to show","50").action(async(w,E)=>{let X=w;if(w.length<26){let A=await fetch(`${S9()}/sessions?limit=100`,{headers:k9()}).catch(()=>null);if(A?.ok){let N=(await A.json()).sessions.find((W)=>W.id.endsWith(w)||W.id===w);if(N)X=N.id}}let G;try{G=await fetch(`${S9()}/sessions/${X}`,{headers:k9()})}catch{return console.error("Cannot connect to orc API.")}if(G.status===404)return console.error(`Session not found: ${w}`);if(!G.ok)return console.error(`API error: ${G.status}`);let J=await G.json();if(t())return $0(J);if(console.log(`Session: ${J.id}`),console.log(`Agent: ${J.agent}`),console.log(`When: ${new Date(J.created_at).toLocaleString()} (${yj(J.created_at)})`),J.project_id)console.log(`Project: ${J.project_id}`);if(J.tokens_used)console.log(`Tokens: ${J.tokens_used}`);if(J.summary)console.log(`
|
|
587
587
|
Summary:`),console.log(` ${J.summary}`);if(E.events&&J.events.length>0){let A=Number(E.limit),D=J.events.slice(0,A);console.log(`
|
|
588
588
|
Events (${D.length}/${J.events.length}):`);let N={file:"\uD83D\uDCC4",task:"\u2713",decision:"\uD83D\uDCA1",git:"\u2387",error:"\u2717",env:"\u2699",rule:"\uD83D\uDCCC",plan:"\uD83D\uDCCB",intent:"\u2192",subagent:"\u25CE"};for(let W of D){let O=N[W.type]??"\xB7",Y=new Date(W.created_at).toLocaleTimeString(),H=(()=>{try{let L=JSON.parse(W.data);return Object.entries(L).map(([F,j])=>`${F}=${String(j).slice(0,50)}`).join(" ")}catch{return W.data.slice(0,80)}})();console.log(` ${O} [${W.type.padEnd(10)}] ${Y} ${H}`)}}if(E.snapshot&&J.snapshot)console.log(`
|
|
589
589
|
Snapshot:`),console.log(J.snapshot);else if(E.snapshot&&!J.snapshot)console.log(`
|
|
590
|
-
No snapshot stored for this session.`)}),$.command("log <summary>").description("Log a session summary (calls session_log MCP tool)").option("-a, --agent <name>","Agent name","human").option("--agent-version <v>","Agent version string").action(async(w,E)=>{let X=O0(),G=`http://${X.api.host}:${X.api.port}`,J={"Content-Type":"application/json"};if(X.api.secret)J.Authorization=`Bearer ${X.api.secret}`;let A=await fetch(`${G}/mcp/tool`,{method:"POST",headers:J,body:JSON.stringify({name:"session_log",args:{agent:E.agent,agent_version:E.agentVersion,summary:w}})}),D=await A.json();if(!A.ok)return console.error("Error:",D.error);if(t())return $0(D);console.log(D.result)}),$}function
|
|
590
|
+
No snapshot stored for this session.`)}),$.command("log <summary>").description("Log a session summary (calls session_log MCP tool)").option("-a, --agent <name>","Agent name","human").option("--agent-version <v>","Agent version string").action(async(w,E)=>{let X=O0(),G=`http://${X.api.host}:${X.api.port}`,J={"Content-Type":"application/json"};if(X.api.secret)J.Authorization=`Bearer ${X.api.secret}`;let A=await fetch(`${G}/mcp/tool`,{method:"POST",headers:J,body:JSON.stringify({name:"session_log",args:{agent:E.agent,agent_version:E.agentVersion,summary:w}})}),D=await A.json();if(!A.ok)return console.error("Error:",D.error);if(t())return $0(D);console.log(D.result)}),$}function uj(){return new $$("status").description("Show system status").action(async()=>{let $=e(),{data:w,error:E}=await $.health.check();if(E){console.error("API unreachable \u2014 is `orc api` running?");return}console.log(`orc API \u25CF running v${w?.version} uptime: ${w?.uptime}s`);let{data:X}=await $.tasks.list({limit:100}),{data:G}=await $.jobs.list(),{data:J}=await $.memories.list();if(t())return $0({api:w,tasks:X?.tasks??[],jobs:G?.jobs??[],memories:J?.memories??[]});let A=Kv(X?.tasks??[],"status");console.log(`
|
|
591
591
|
Tasks:`);for(let[D,N]of Object.entries(A))console.log(` ${D.padEnd(20)} ${N}`);console.log(`
|
|
592
|
-
Jobs: ${G?.jobs.length??0} defined`),console.log(`Memory: ${J?.memories.length??0} recent entries`)})}function
|
|
593
|
-
`);let w=[{label:"DB",path:$.db.path},{label:"config",path:`${tw}/config.json`},{label:"pid",path:
|
|
592
|
+
Jobs: ${G?.jobs.length??0} defined`),console.log(`Memory: ${J?.memories.length??0} recent entries`)})}function Kv($,w){return $.reduce((E,X)=>{let G=String(X[w]);return E[G]=(E[G]??0)+1,E},{})}async function KE($,w){if(w.length===26)return w;let{data:E}=await $.tasks.list({limit:100}),X=(E?.tasks??[]).find((G)=>G.id.endsWith(w)||G.id===w);if(!X)return console.error(`Task not found: ${w}`),null;return X.id}function cj(){let $=new $$("task").description("Manage tasks");return $.command("list").description("List tasks").option("-p, --project <name>","Filter by project name").option("--no-project","Show all tasks across projects").option("-s, --status <status>","Filter by status").option("-t, --tag <tag>","Filter by tag").option("-l, --limit <n>","Max results","20").option("--flat","Disable status grouping").action(async(w)=>{let E=e(),X=w.project===!1,G=X?null:await g1(E,{project:w.project,noProject:X}),{data:J,error:A}=await E.tasks.list({...G?{project_id:G.id}:{},status:w.status,tag:w.tag,limit:Number(w.limit)});if(A){if(t())return M1(String(A));return console.error("Error:",A)}let D=J?.tasks??[];if(t())return $0({tasks:D,project:G?.name??null});if(D.length===0)return console.log("No tasks found.");let N=new Map;if(X){let{data:O}=await E.projects.list({limit:100});for(let Y of O?.projects??[])N.set(Y.id,Y.name)}else if(G)console.log(VE(G.name,"1")),console.log();let W=X;if(w.status||w.flat)for(let O of D){let Y=hj(O,W?N:void 0);console.log(Y)}else{let O=["review","changes_requested","doing","blocked","todo"],Y=new Map;for(let H of D){let L=Y.get(H.status)??[];L.push(H),Y.set(H.status,L)}for(let H of O){let L=Y.get(H);if(!L||L.length===0)continue;let F=`\u2500\u2500 ${H} (${L.length}) `;console.log(b9(F.padEnd(50,"\u2500"),H));for(let j of L)console.log(hj(j,W?N:void 0));console.log()}}}),$.command("add <title>").description("Create a new task").option("-p, --project <name>","Project name").option("--no-project","Create without project").option("--priority <p>","Priority (low/normal/high/critical)","normal").option("-b, --body <text>","Task body").action(async(w,E)=>{let X=e(),G=E.project===!1,J=G?null:await g1(X,{project:E.project,noProject:G}),{data:A,error:D}=await X.tasks.create({title:w,body:E.body,...J?{project_id:J.id}:{},priority:E.priority});if(D){if(t())return M1(String(D));return console.error("Error:",D)}if(t())return $0(A);console.log(`Created: [${A?.id.slice(-6)}] ${A?.title}`)}),$.command("done <id>").description("Mark task as done (accepts full ULID or last-6 suffix)").action(async(w)=>{let E=e(),X=await KE(E,w);if(!X)return;let{data:G,error:J}=await E.tasks.update(X,{status:"done"});if(J){if(t())return M1(String(J));return console.error("Error:",J)}if(t())return $0(G);console.log(`Done: [${G?.id.slice(-6)}] ${G?.title}`)}),$.command("review <id>").description("Submit task for review").action(async(w)=>{let E=e(),X=await KE(E,w);if(!X)return;let{data:G,error:J}=await E.tasks.update(X,{status:"review"});if(J){if(t())return M1(String(J));return console.error("Error:",J)}if(t())return $0(G);console.log(`In review: [${G?.id.slice(-6)}] ${G?.title}`)}),$.command("approve <id>").description("Approve a task in review (HITL)").option("-c, --comment <text>","Optional comment to add").action(async(w,E)=>{let X=e(),G=await KE(X,w);if(!G)return;let{data:J,error:A}=await X.tasks.get(G);if(A){if(t())return M1(String(A));return console.error("Error:",A)}if(J?.status!=="review")return console.error(`Task is not in review (current: ${J?.status})`);let{data:D,error:N}=await X.tasks.update(G,{status:"done"});if(N){if(t())return M1(String(N));return console.error("Error:",N)}if(E.comment)await X.tasks.addComment(G,E.comment,"human");if(t())return $0(D);console.log(`Approved: [${D?.id.slice(-6)}] ${D?.title}`)}),$.command("reject <id>").description("Reject a task in review, request changes (HITL)").option("-r, --reason <text>","Reason for rejection").action(async(w,E)=>{let X=e(),G=await KE(X,w);if(!G)return;let{data:J,error:A}=await X.tasks.get(G);if(A){if(t())return M1(String(A));return console.error("Error:",A)}if(J?.status!=="review")return console.error(`Task is not in review (current: ${J?.status})`);let{data:D,error:N}=await X.tasks.update(G,{status:"changes_requested"});if(N){if(t())return M1(String(N));return console.error("Error:",N)}if(E.reason)await X.tasks.addComment(G,E.reason,"human");if(t())return $0(D);console.log(`Changes requested: [${D?.id.slice(-6)}] ${D?.title}`)}),$.command("show <id>").description("Show task details").action(async(w)=>{let E=e(),X=await KE(E,w);if(!X)return;let{data:G,error:J}=await E.tasks.get(X);if(J){if(t())return M1(String(J));return console.error("Error:",J)}if(!G)return console.error("Task not found");if(t()){let{data:W}=await E.tasks.listLinks(X),O=W?.links??[];return $0({...G,links:O})}let A=(W,O)=>{if(O!=null)console.log(` ${VE(W.padEnd(14),"2")} ${O}`)};if(console.log(),console.log(` ${b9(Z9(G.status),G.status)} ${VE(G.title,"1")}`),console.log(),A("ID",G.id),A("Status",`${Z9(G.status)} ${G.status}`),A("Priority",`${nj(G.priority)} ${G.priority}`),A("Progress",`${G.progress}%`),A("Project",G.project_id??void 0),A("Tags",G.tags?.join(", ")??void 0),A("Due",G.due_at??void 0),A("Author",G.author),A("Claimed by",G.claimed_by??void 0),A("Created",G.created_at),A("Updated",G.updated_at),G.body)console.log(),console.log(` ${VE("Body","2")}`),console.log(` ${G.body}`);let{data:D}=await E.tasks.listLinks(X),N=D?.links??[];if(N.length>0){console.log(),console.log(` ${VE("Links","2")}`);for(let W of N){let O=W.from_task_id===X?W.to_task_id:W.from_task_id;console.log(` ${W.link_type} \u2192 [${O.slice(-6)}]`)}}console.log()}),$.command("update <id>").description("Update a task").option("--title <t>","New title").option("--body <text>","New body").option("--status <s>","New status (todo/doing/review/changes_requested/blocked/done/cancelled)").option("--priority <p>","Priority (low/normal/high/critical)").option("--progress <n>","Progress (0-100)").option("--tags <csv>","Comma-separated tags").option("-p, --project <name>","Move to project").option("--no-project","Remove from project").action(async(w,E)=>{let X=e(),G=await KE(X,w);if(!G)return;let J={};if(E.title)J.title=E.title;if(E.body)J.body=E.body;if(E.status)J.status=E.status;if(E.priority)J.priority=E.priority;if(E.progress!==void 0&&E.progress!==!0)J.progress=Number(E.progress);if(E.tags)J.tags=E.tags.split(",").map((W)=>W.trim());if(E.project===!1)J.project_id=null;else if(typeof E.project==="string"){let W=await g1(X,{project:E.project,noProject:!1});if(W)J.project_id=W.id}if(Object.keys(J).length===0)return console.error("No updates specified. Use --help to see options.");if(g$())return u$("update",`task [${G.slice(-6)}]`,J);let{data:D,error:N}=await X.tasks.update(G,J);if(N){if(t())return M1(String(N));return console.error("Error:",N)}if(t())return $0(D);console.log(`Updated: [${D?.id.slice(-6)}] ${D?.title}`)}),$.command("delete <id>").description("Delete a task").action(async(w)=>{let E=e(),X=await KE(E,w);if(!X)return;if(g$())return u$("delete",`task [${X.slice(-6)}]`);let{error:G}=await E.tasks.delete(X);if(G){if(t())return M1(String(G));return console.error("Error:",G)}if(t())return $0({deleted:X});console.log(`Deleted: [${X.slice(-6)}]`)}),$}function VE($,w){return process.stdout.isTTY?`\x1B[${w}m${$}\x1B[0m`:$}var Vv={review:"33",changes_requested:"33",doing:"36",blocked:"31",todo:"2",done:"32",cancelled:"2"};function b9($,w){return VE($,Vv[w]??"0")}function Z9($){return{todo:"\u25CB",doing:"\u25D0",review:"\u25C9",changes_requested:"\u21A9",blocked:"\u2298",done:"\u25CF",cancelled:"\u2715"}[$]??"?"}function nj($){return{low:"\u2193",normal:"\u2192",high:"\u2191",critical:"\u203C"}[$]??" "}function hj($,w){let E=Z9($.status),X=nj($.priority),G=$.id.slice(-6),J=$.title.length>40?`${$.title.slice(0,39)}\u2026`:$.title,A=` ${b9(E,$.status)} ${X} [${G}] ${J.padEnd(40)}`;if(w&&$.project_id)A+=` ${VE(w.get($.project_id)??$.project_id.slice(-6),"2")}`;return A}var m$=new $$().name("orc").description("Human + AI Orchestration Hub").version(lE).option("--db <path>","DB file path (overrides ORC_DB_PATH / config.json)").option("--port <n>","API port (overrides ORC_API_PORT / config.json)").option("--host <host>","API host (overrides ORC_API_HOST / config.json)").option("--secret <secret>","API bearer secret (overrides ORC_API_SECRET / config.json)").option("--log-level <level>","Log level: debug|info|warn|error (overrides ORC_LOG_LEVEL)").option("--runner-timeout <secs>","Default job timeout in seconds (overrides ORC_RUNNER_TIMEOUT)").option("--runner-max-jobs <n>","Max concurrent jobs (overrides ORC_RUNNER_MAX_JOBS)").option("--snapshot-max-bytes <n>","Session snapshot budget bytes (overrides ORC_SNAPSHOT_MAX_BYTES)").option("--json","Machine-readable JSON output").option("--dry-run","Preview changes without executing").hook("preSubcommand",($,w)=>{let E=m$.opts();if(E.db)process.env.ORC_DB_PATH=E.db;if(E.port)process.env.ORC_API_PORT=E.port;if(E.host)process.env.ORC_API_HOST=E.host;if(E.secret)process.env.ORC_API_SECRET=E.secret;if(E.logLevel)process.env.ORC_LOG_LEVEL=E.logLevel;if(E.runnerTimeout)process.env.ORC_RUNNER_TIMEOUT=E.runnerTimeout;if(E.runnerMaxJobs)process.env.ORC_RUNNER_MAX_JOBS=E.runnerMaxJobs;if(E.snapshotMaxBytes)process.env.ORC_SNAPSHOT_MAX_BYTES=E.snapshotMaxBytes});m$.addCommand(cj());m$.addCommand(bj());m$.addCommand(_j());m$.addCommand(Zj());m$.addCommand(gj());m$.addCommand(Pj());m$.addCommand(qj());m$.addCommand(vj());m$.addCommand(uj());m$.addCommand(xj());m$.command("api").description("Start the API server (use --port / --host / --db / --secret to configure)").action(async()=>{await Promise.resolve().then(() => (P9(),V9)),await new Promise(()=>{})});m$.command("home").description("Show ~/.orc directory contents and daemon state").action(()=>{let $=O0();console.log(`ORC home: ${tw}
|
|
593
|
+
`);let w=[{label:"DB",path:$.db.path},{label:"config",path:`${tw}/config.json`},{label:"pid",path:bX},{label:"daemon log",path:`${tw}/daemon.log`}];for(let X of w)if(sp(X.path)){let G=Math.round(ap(X.path).size/1024);console.log(` \u2713 ${X.label.padEnd(12)} ${X.path} (${G}KB)`)}else console.log(` \xB7 ${X.label.padEnd(12)} ${X.path} (not found)`);let E=aA();if(console.log(),E)try{process.kill(E,0),console.log(` daemon \u25CF running pid:${E}`)}catch{console.log(` daemon \u25CB stopped (stale pid: ${E})`)}else console.log(" daemon \u25CB not running");console.log(),console.log(` config port:${$.api.port} host:${$.api.host} secret:${$.api.secret?"***":"(none)"}`)});m$.command("mcp").description("Start the MCP server (stdio)").action(async()=>{let{startStdioServer:$}=await PV().then(() => VV);await $()});m$.parseAsync(process.argv).catch(($)=>{console.error($ instanceof Error?$.message:$),process.exit(1)});
|