orc-ai 0.1.3 → 0.1.5
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 +225 -145
- 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 sI=Object.create;var{getPrototypeOf:aI,defineProperty:nG,getOwnPropertyNames:UD,getOwnPropertyDescriptor:eI}=Object,OD=Object.prototype.hasOwnProperty;function ND($){return this[$]}var $j,wj,pE=($,w,X)=>{var G=$!=null&&typeof $==="object";if(G){var E=w?$j??=new WeakMap:wj??=new WeakMap,J=E.get($);if(J)return J}X=$!=null?sI(aI($)):{};let W=w||!$||!$.__esModule?nG(X,"default",{value:$,enumerable:!0}):X;for(let Y of UD($))if(!OD.call(W,Y))nG(W,Y,{get:ND.bind($,Y),enumerable:!0});if(G)E.set($,W);return W},HD=($)=>{var w=(DD??=new WeakMap).get($),X;if(w)return w;if(w=nG({},"__esModule",{value:!0}),$&&typeof $==="object"||typeof $==="function"){for(var G of UD($))if(!OD.call(w,G))nG(w,G,{get:ND.bind($,G),enumerable:!(X=eI($,G))||X.enumerable})}return DD.set($,w),w},DD,b=($,w)=>()=>(w||$((w={exports:{}}).exports,w),w.exports);var Xj=($)=>$;function Gj($,w){this[$]=Xj.bind(null,w)}var e1=($,w)=>{for(var X in w)nG($,X,{get:w[X],enumerable:!0,configurable:!0,set:Gj.bind(w,X)})};var B=($,w)=>()=>($&&(w=$($=0)),w);var B$=import.meta.require;var Y0,W5,_,g1=($)=>{switch(typeof $){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;return _.object;default:return _.unknown}};var pG=B(()=>{(function($){$.assertEqual=(E)=>{};function w(E){}$.assertIs=w;function X(E){throw Error()}$.assertNever=X,$.arrayToEnum=(E)=>{let J={};for(let W of E)J[W]=W;return J},$.getValidEnumValues=(E)=>{let J=$.objectKeys(E).filter((Y)=>typeof E[E[Y]]!=="number"),W={};for(let Y of J)W[Y]=E[Y];return $.objectValues(W)},$.objectValues=(E)=>{return $.objectKeys(E).map(function(J){return E[J]})},$.objectKeys=typeof Object.keys==="function"?(E)=>Object.keys(E):(E)=>{let J=[];for(let W in E)if(Object.prototype.hasOwnProperty.call(E,W))J.push(W);return J},$.find=(E,J)=>{for(let W of E)if(J(W))return W;return},$.isInteger=typeof Number.isInteger==="function"?(E)=>Number.isInteger(E):(E)=>typeof E==="number"&&Number.isFinite(E)&&Math.floor(E)===E;function G(E,J=" | "){return E.map((W)=>typeof W==="string"?`'${W}'`:W).join(J)}$.joinValues=G,$.jsonStringifyReplacer=(E,J)=>{if(typeof J==="bigint")return J.toString();return J}})(Y0||(Y0={}));(function($){$.mergeShapes=(w,X)=>{return{...w,...X}}})(W5||(W5={}));_=Y0.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"])});var C,Ej=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")},_$;var rE=B(()=>{pG();C=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"]);_$=class _$ extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(X)=>{this.issues=[...this.issues,X]},this.addIssues=(X=[])=>{this.issues=[...this.issues,...X]};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(E){return E.message},X={_errors:[]},G=(E)=>{for(let J of E.issues)if(J.code==="invalid_union")J.unionErrors.map(G);else if(J.code==="invalid_return_type")G(J.returnTypeError);else if(J.code==="invalid_arguments")G(J.argumentsError);else if(J.path.length===0)X._errors.push(w(J));else{let W=X,Y=0;while(Y<J.path.length){let A=J.path[Y];if(Y!==J.path.length-1)W[A]=W[A]||{_errors:[]};else W[A]=W[A]||{_errors:[]},W[A]._errors.push(w(J));W=W[A],Y++}}};return G(this),X}static assert($){if(!($ instanceof _$))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={},X=[];for(let G of this.issues)if(G.path.length>0){let E=G.path[0];w[E]=w[E]||[],w[E].push($(G))}else X.push($(G));return{formErrors:X,fieldErrors:w}}get formErrors(){return this.flatten()}};_$.create=($)=>{return new _$($)}});var Jj=($,w)=>{let X;switch($.code){case C.invalid_type:if($.received===_.undefined)X="Required";else X=`Expected ${$.expected}, received ${$.received}`;break;case C.invalid_literal:X=`Invalid literal value, expected ${JSON.stringify($.expected,Y0.jsonStringifyReplacer)}`;break;case C.unrecognized_keys:X=`Unrecognized key(s) in object: ${Y0.joinValues($.keys,", ")}`;break;case C.invalid_union:X="Invalid input";break;case C.invalid_union_discriminator:X=`Invalid discriminator value. Expected ${Y0.joinValues($.options)}`;break;case C.invalid_enum_value:X=`Invalid enum value. Expected ${Y0.joinValues($.options)}, received '${$.received}'`;break;case C.invalid_arguments:X="Invalid function arguments";break;case C.invalid_return_type:X="Invalid function return type";break;case C.invalid_date:X="Invalid date";break;case C.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(X=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")X=`${X} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)X=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)X=`Invalid input: must end with "${$.validation.endsWith}"`;else Y0.assertNever($.validation);else if($.validation!=="regex")X=`Invalid ${$.validation}`;else X="Invalid";break;case C.too_small:if($.type==="array")X=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")X=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")X=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="bigint")X=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")X=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else X="Invalid input";break;case C.too_big:if($.type==="array")X=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")X=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")X=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")X=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")X=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else X="Invalid input";break;case C.custom:X="Invalid input";break;case C.invalid_intersection_types:X="Intersection results could not be merged";break;case C.not_multiple_of:X=`Number must be a multiple of ${$.multipleOf}`;break;case C.not_finite:X="Number must be finite";break;default:X=w.defaultError,Y0.assertNever($)}return{message:X}},$w;var Y5=B(()=>{rE();pG();$w=Jj});function Wj($){LD=$}function IX(){return LD}var LD;var iE=B(()=>{Y5();LD=$w});function y($,w){let X=IX(),G=rG({issueData:w,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,X,X===$w?void 0:$w].filter((E)=>!!E)});$.common.issues.push(G)}class O${constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,w){let X=[];for(let G of w){if(G.status==="aborted")return i;if(G.status==="dirty")$.dirty();X.push(G.value)}return{status:$.value,value:X}}static async mergeObjectAsync($,w){let X=[];for(let G of w){let E=await G.key,J=await G.value;X.push({key:E,value:J})}return O$.mergeObjectSync($,X)}static mergeObjectSync($,w){let X={};for(let G of w){let{key:E,value:J}=G;if(E.status==="aborted")return i;if(J.status==="aborted")return i;if(E.status==="dirty")$.dirty();if(J.status==="dirty")$.dirty();if(E.value!=="__proto__"&&(typeof J.value<"u"||G.alwaysSet))X[E.value]=J.value}return{status:$.value,value:X}}}var rG=($)=>{let{data:w,path:X,errorMaps:G,issueData:E}=$,J=[...X,...E.path||[]],W={...E,path:J};if(E.message!==void 0)return{...E,path:J,message:E.message};let Y="",A=G.filter((D)=>!!D).slice().reverse();for(let D of A)Y=D(W,{data:w,defaultError:Y}).message;return{...E,path:J,message:Y}},Yj,i,dw=($)=>({status:"dirty",value:$}),K$=($)=>({status:"valid",value:$}),oE=($)=>$.status==="aborted",tE=($)=>$.status==="dirty",Kw=($)=>$.status==="valid",jX=($)=>typeof Promise<"u"&&$ instanceof Promise;var A5=B(()=>{iE();Y5();Yj=[];i=Object.freeze({status:"aborted"})});var FD=()=>{};var c;var MD=B(()=>{(function($){$.errToObj=(w)=>typeof w==="string"?{message:w}:w||{},$.toString=(w)=>typeof w==="string"?w:w?.message})(c||(c={}))});class K1{constructor($,w,X,G){this._cachedPath=[],this.parent=$,this.data=w,this._path=X,this._key=G}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 $0($){if(!$)return{};let{errorMap:w,invalid_type_error:X,required_error:G,description:E}=$;if(w&&(X||G))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(w)return{errorMap:w,description:E};return{errorMap:(W,Y)=>{let{message:A}=$;if(W.code==="invalid_enum_value")return{message:A??Y.defaultError};if(typeof Y.data>"u")return{message:A??G??Y.defaultError};if(W.code!=="invalid_type")return{message:Y.defaultError};return{message:A??X??Y.defaultError}},description:E}}class w0{get description(){return this._def.description}_getType($){return g1($.data)}_getOrReturnCtx($,w){return w||{common:$.parent.common,data:$.data,parsedType:g1($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new O$,ctx:{common:$.parent.common,data:$.data,parsedType:g1($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let w=this._parse($);if(jX(w))throw Error("Synchronous parse encountered promise.");return w}_parseAsync($){let w=this._parse($);return Promise.resolve(w)}parse($,w){let X=this.safeParse($,w);if(X.success)return X.data;throw X.error}safeParse($,w){let X={common:{issues:[],async:w?.async??!1,contextualErrorMap:w?.errorMap},path:w?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:g1($)},G=this._parseSync({data:$,path:X.path,parent:X});return zD(X,G)}"~validate"($){let w={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:g1($)};if(!this["~standard"].async)try{let X=this._parseSync({data:$,path:[],parent:w});return Kw(X)?{value:X.value}:{issues:w.common.issues}}catch(X){if(X?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;w.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:w}).then((X)=>Kw(X)?{value:X.value}:{issues:w.common.issues})}async parseAsync($,w){let X=await this.safeParseAsync($,w);if(X.success)return X.data;throw X.error}async safeParseAsync($,w){let X={common:{issues:[],contextualErrorMap:w?.errorMap,async:!0},path:w?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:g1($)},G=this._parse({data:$,path:X.path,parent:X}),E=await(jX(G)?G:Promise.resolve(G));return zD(X,E)}refine($,w){let X=(G)=>{if(typeof w==="string"||typeof w>"u")return{message:w};else if(typeof w==="function")return w(G);else return w};return this._refinement((G,E)=>{let J=$(G),W=()=>E.addIssue({code:C.custom,...X(G)});if(typeof Promise<"u"&&J instanceof Promise)return J.then((Y)=>{if(!Y)return W(),!1;else return!0});if(!J)return W(),!1;else return!0})}refinement($,w){return this._refinement((X,G)=>{if(!$(X))return G.addIssue(typeof w==="function"?w(X,G):w),!1;else return!0})}_refinement($){return new V1({schema:this,typeName:d.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 B1.create(this,this._def)}nullable(){return Xw.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Q1.create(this)}promise(){return ew.create(this,this._def)}or($){return kX.create([this,$],this._def)}and($){return CX.create(this,$,this._def)}transform($){return new V1({...$0(this._def),schema:this,typeName:d.ZodEffects,effect:{type:"transform",transform:$}})}default($){let w=typeof $==="function"?$:()=>$;return new xX({...$0(this._def),innerType:this,defaultValue:w,typeName:d.ZodDefault})}brand(){return new lE({typeName:d.ZodBranded,type:this,...$0(this._def)})}catch($){let w=typeof $==="function"?$:()=>$;return new yX({...$0(this._def),innerType:this,catchValue:w,typeName:d.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return sG.create(this,$)}readonly(){return gX.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}function KD($){let w="[0-5]\\d";if($.precision)w=`${w}\\.\\d{${$.precision}}`;else if($.precision==null)w=`${w}(\\.\\d+)?`;let X=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${w})${X}`}function Ij($){return new RegExp(`^${KD($)}$`)}function VD($){let w=`${BD}T${KD($)}`,X=[];if(X.push($.local?"Z?":"Z"),$.offset)X.push("([+-]\\d{2}:?\\d{2})");return w=`${w}(${X.join("|")})`,new RegExp(`^${w}$`)}function jj($,w){if((w==="v4"||!w)&&zj.test($))return!0;if((w==="v6"||!w)&&Bj.test($))return!0;return!1}function Pj($,w){if(!Hj.test($))return!1;try{let[X]=$.split(".");if(!X)return!1;let G=X.replace(/-/g,"+").replace(/_/g,"/").padEnd(X.length+(4-X.length%4)%4,"="),E=JSON.parse(atob(G));if(typeof E!=="object"||E===null)return!1;if("typ"in E&&E?.typ!=="JWT")return!1;if(!E.alg)return!1;if(w&&E.alg!==w)return!1;return!0}catch{return!1}}function qj($,w){if((w==="v4"||!w)&&Qj.test($))return!0;if((w==="v6"||!w)&&Kj.test($))return!0;return!1}function Sj($,w){let X=($.toString().split(".")[1]||"").length,G=(w.toString().split(".")[1]||"").length,E=X>G?X:G,J=Number.parseInt($.toFixed(E).replace(".","")),W=Number.parseInt(w.toFixed(E).replace(".",""));return J%W/10**E}function PX($){if($ instanceof m0){let w={};for(let X in $.shape){let G=$.shape[X];w[X]=B1.create(PX(G))}return new m0({...$._def,shape:()=>w})}else if($ instanceof Q1)return new Q1({...$._def,type:PX($.element)});else if($ instanceof B1)return B1.create(PX($.unwrap()));else if($ instanceof Xw)return Xw.create(PX($.unwrap()));else if($ instanceof u1)return u1.create($.items.map((w)=>PX(w)));else return $}function U5($,w){let X=g1($),G=g1(w);if($===w)return{valid:!0,data:$};else if(X===_.object&&G===_.object){let E=Y0.objectKeys(w),J=Y0.objectKeys($).filter((Y)=>E.indexOf(Y)!==-1),W={...$,...w};for(let Y of J){let A=U5($[Y],w[Y]);if(!A.valid)return{valid:!1};W[Y]=A.data}return{valid:!0,data:W}}else if(X===_.array&&G===_.array){if($.length!==w.length)return{valid:!1};let E=[];for(let J=0;J<$.length;J++){let W=$[J],Y=w[J],A=U5(W,Y);if(!A.valid)return{valid:!1};E.push(A.data)}return{valid:!0,data:E}}else if(X===_.date&&G===_.date&&+$===+w)return{valid:!0,data:$};else return{valid:!1}}function RD($,w){return new Iw({values:$,typeName:d.ZodEnum,...$0(w)})}function QD($,w){let X=typeof $==="function"?$(w):typeof $==="string"?{message:$}:$;return typeof X==="string"?{message:X}:X}function TD($,w={},X){if($)return sw.create().superRefine((G,E)=>{let J=$(G);if(J instanceof Promise)return J.then((W)=>{if(!W){let Y=QD(w,G),A=Y.fatal??X??!0;E.addIssue({code:"custom",...Y,fatal:A})}});if(!J){let W=QD(w,G),Y=W.fatal??X??!0;E.addIssue({code:"custom",...W,fatal:Y})}return});return sw.create()}var zD=($,w)=>{if(Kw(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 X=new _$($.common.issues);return this._error=X,this._error}}}},Aj,Dj,Uj,Oj,Nj,Hj,Lj,Fj,Mj="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",D5,zj,Qj,Bj,Kj,Vj,Rj,BD="((\\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])))",Tj,z1,Rw,Tw,SX,lw,iG,ZX,bX,sw,Vw,h1,oG,Q1,m0,kX,ww=($)=>{if($ instanceof vX)return ww($.schema);else if($ instanceof V1)return ww($.innerType());else if($ instanceof _X)return[$.value];else if($ instanceof Iw)return $.options;else if($ instanceof fX)return Y0.objectValues($.enum);else if($ instanceof xX)return ww($._def.innerType);else if($ instanceof ZX)return[void 0];else if($ instanceof bX)return[null];else if($ instanceof B1)return[void 0,...ww($.unwrap())];else if($ instanceof Xw)return[null,...ww($.unwrap())];else if($ instanceof lE)return ww($.unwrap());else if($ instanceof gX)return ww($.unwrap());else if($ instanceof yX)return ww($._def.innerType);else return[]},dE,CX,u1,tG,dG,aw,qX,vX,_X,Iw,fX,ew,V1,B1,Xw,xX,yX,lG,Zj,lE,sG,gX,bj,d,kj=($,w={message:`Input not instance of ${$.name}`})=>TD((X)=>X instanceof $,w),ID,jD,Cj,vj,PD,_j,fj,xj,yj,gj,hj,uj,cj,mj,nj,pj,rj,ij,oj,tj,dj,lj,sj,aj,ej,$P,wP,XP,GP,EP,JP,WP,YP,AP,DP=()=>ID().optional(),UP=()=>jD().optional(),OP=()=>PD().optional(),NP,HP;var qD=B(()=>{rE();iE();MD();A5();pG();Aj=/^c[^\s-]{8,}$/i,Dj=/^[0-9a-z]+$/,Uj=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Oj=/^[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,Nj=/^[a-z0-9_-]{21}$/i,Hj=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Lj=/^[-+]?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)?)??$/,Fj=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,zj=/^(?:(?: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])$/,Qj=/^(?:(?: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])$/,Bj=/^(([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]))$/,Kj=/^(([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])$/,Vj=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Rj=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Tj=new RegExp(`^${BD}$`);z1=class z1 extends w0{_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==_.string){let E=this._getOrReturnCtx($);return y(E,{code:C.invalid_type,expected:_.string,received:E.parsedType}),i}let X=new O$,G=void 0;for(let E of this._def.checks)if(E.kind==="min"){if($.data.length<E.value)G=this._getOrReturnCtx($,G),y(G,{code:C.too_small,minimum:E.value,type:"string",inclusive:!0,exact:!1,message:E.message}),X.dirty()}else if(E.kind==="max"){if($.data.length>E.value)G=this._getOrReturnCtx($,G),y(G,{code:C.too_big,maximum:E.value,type:"string",inclusive:!0,exact:!1,message:E.message}),X.dirty()}else if(E.kind==="length"){let J=$.data.length>E.value,W=$.data.length<E.value;if(J||W){if(G=this._getOrReturnCtx($,G),J)y(G,{code:C.too_big,maximum:E.value,type:"string",inclusive:!0,exact:!0,message:E.message});else if(W)y(G,{code:C.too_small,minimum:E.value,type:"string",inclusive:!0,exact:!0,message:E.message});X.dirty()}}else if(E.kind==="email"){if(!Fj.test($.data))G=this._getOrReturnCtx($,G),y(G,{validation:"email",code:C.invalid_string,message:E.message}),X.dirty()}else if(E.kind==="emoji"){if(!D5)D5=new RegExp(Mj,"u");if(!D5.test($.data))G=this._getOrReturnCtx($,G),y(G,{validation:"emoji",code:C.invalid_string,message:E.message}),X.dirty()}else if(E.kind==="uuid"){if(!Oj.test($.data))G=this._getOrReturnCtx($,G),y(G,{validation:"uuid",code:C.invalid_string,message:E.message}),X.dirty()}else if(E.kind==="nanoid"){if(!Nj.test($.data))G=this._getOrReturnCtx($,G),y(G,{validation:"nanoid",code:C.invalid_string,message:E.message}),X.dirty()}else if(E.kind==="cuid"){if(!Aj.test($.data))G=this._getOrReturnCtx($,G),y(G,{validation:"cuid",code:C.invalid_string,message:E.message}),X.dirty()}else if(E.kind==="cuid2"){if(!Dj.test($.data))G=this._getOrReturnCtx($,G),y(G,{validation:"cuid2",code:C.invalid_string,message:E.message}),X.dirty()}else if(E.kind==="ulid"){if(!Uj.test($.data))G=this._getOrReturnCtx($,G),y(G,{validation:"ulid",code:C.invalid_string,message:E.message}),X.dirty()}else if(E.kind==="url")try{new URL($.data)}catch{G=this._getOrReturnCtx($,G),y(G,{validation:"url",code:C.invalid_string,message:E.message}),X.dirty()}else if(E.kind==="regex"){if(E.regex.lastIndex=0,!E.regex.test($.data))G=this._getOrReturnCtx($,G),y(G,{validation:"regex",code:C.invalid_string,message:E.message}),X.dirty()}else if(E.kind==="trim")$.data=$.data.trim();else if(E.kind==="includes"){if(!$.data.includes(E.value,E.position))G=this._getOrReturnCtx($,G),y(G,{code:C.invalid_string,validation:{includes:E.value,position:E.position},message:E.message}),X.dirty()}else if(E.kind==="toLowerCase")$.data=$.data.toLowerCase();else if(E.kind==="toUpperCase")$.data=$.data.toUpperCase();else if(E.kind==="startsWith"){if(!$.data.startsWith(E.value))G=this._getOrReturnCtx($,G),y(G,{code:C.invalid_string,validation:{startsWith:E.value},message:E.message}),X.dirty()}else if(E.kind==="endsWith"){if(!$.data.endsWith(E.value))G=this._getOrReturnCtx($,G),y(G,{code:C.invalid_string,validation:{endsWith:E.value},message:E.message}),X.dirty()}else if(E.kind==="datetime"){if(!VD(E).test($.data))G=this._getOrReturnCtx($,G),y(G,{code:C.invalid_string,validation:"datetime",message:E.message}),X.dirty()}else if(E.kind==="date"){if(!Tj.test($.data))G=this._getOrReturnCtx($,G),y(G,{code:C.invalid_string,validation:"date",message:E.message}),X.dirty()}else if(E.kind==="time"){if(!Ij(E).test($.data))G=this._getOrReturnCtx($,G),y(G,{code:C.invalid_string,validation:"time",message:E.message}),X.dirty()}else if(E.kind==="duration"){if(!Lj.test($.data))G=this._getOrReturnCtx($,G),y(G,{validation:"duration",code:C.invalid_string,message:E.message}),X.dirty()}else if(E.kind==="ip"){if(!jj($.data,E.version))G=this._getOrReturnCtx($,G),y(G,{validation:"ip",code:C.invalid_string,message:E.message}),X.dirty()}else if(E.kind==="jwt"){if(!Pj($.data,E.alg))G=this._getOrReturnCtx($,G),y(G,{validation:"jwt",code:C.invalid_string,message:E.message}),X.dirty()}else if(E.kind==="cidr"){if(!qj($.data,E.version))G=this._getOrReturnCtx($,G),y(G,{validation:"cidr",code:C.invalid_string,message:E.message}),X.dirty()}else if(E.kind==="base64"){if(!Vj.test($.data))G=this._getOrReturnCtx($,G),y(G,{validation:"base64",code:C.invalid_string,message:E.message}),X.dirty()}else if(E.kind==="base64url"){if(!Rj.test($.data))G=this._getOrReturnCtx($,G),y(G,{validation:"base64url",code:C.invalid_string,message:E.message}),X.dirty()}else Y0.assertNever(E);return{status:X.value,value:$.data}}_regex($,w,X){return this.refinement((G)=>$.test(G),{validation:w,code:C.invalid_string,...c.errToObj(X)})}_addCheck($){return new z1({...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 z1({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new z1({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new z1({...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 $}};z1.create=($)=>{return new z1({checks:[],typeName:d.ZodString,coerce:$?.coerce??!1,...$0($)})};Rw=class Rw extends w0{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($)!==_.number){let E=this._getOrReturnCtx($);return y(E,{code:C.invalid_type,expected:_.number,received:E.parsedType}),i}let X=void 0,G=new O$;for(let E of this._def.checks)if(E.kind==="int"){if(!Y0.isInteger($.data))X=this._getOrReturnCtx($,X),y(X,{code:C.invalid_type,expected:"integer",received:"float",message:E.message}),G.dirty()}else if(E.kind==="min"){if(E.inclusive?$.data<E.value:$.data<=E.value)X=this._getOrReturnCtx($,X),y(X,{code:C.too_small,minimum:E.value,type:"number",inclusive:E.inclusive,exact:!1,message:E.message}),G.dirty()}else if(E.kind==="max"){if(E.inclusive?$.data>E.value:$.data>=E.value)X=this._getOrReturnCtx($,X),y(X,{code:C.too_big,maximum:E.value,type:"number",inclusive:E.inclusive,exact:!1,message:E.message}),G.dirty()}else if(E.kind==="multipleOf"){if(Sj($.data,E.value)!==0)X=this._getOrReturnCtx($,X),y(X,{code:C.not_multiple_of,multipleOf:E.value,message:E.message}),G.dirty()}else if(E.kind==="finite"){if(!Number.isFinite($.data))X=this._getOrReturnCtx($,X),y(X,{code:C.not_finite,message:E.message}),G.dirty()}else Y0.assertNever(E);return{status:G.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,X,G){return new Rw({...this._def,checks:[...this._def.checks,{kind:$,value:w,inclusive:X,message:c.toString(G)}]})}_addCheck($){return new Rw({...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 X of this._def.checks)if(X.kind==="finite"||X.kind==="int"||X.kind==="multipleOf")return!0;else if(X.kind==="min"){if(w===null||X.value>w)w=X.value}else if(X.kind==="max"){if($===null||X.value<$)$=X.value}return Number.isFinite(w)&&Number.isFinite($)}};Rw.create=($)=>{return new Rw({checks:[],typeName:d.ZodNumber,coerce:$?.coerce||!1,...$0($)})};Tw=class Tw extends w0{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($)!==_.bigint)return this._getInvalidInput($);let X=void 0,G=new O$;for(let E of this._def.checks)if(E.kind==="min"){if(E.inclusive?$.data<E.value:$.data<=E.value)X=this._getOrReturnCtx($,X),y(X,{code:C.too_small,type:"bigint",minimum:E.value,inclusive:E.inclusive,message:E.message}),G.dirty()}else if(E.kind==="max"){if(E.inclusive?$.data>E.value:$.data>=E.value)X=this._getOrReturnCtx($,X),y(X,{code:C.too_big,type:"bigint",maximum:E.value,inclusive:E.inclusive,message:E.message}),G.dirty()}else if(E.kind==="multipleOf"){if($.data%E.value!==BigInt(0))X=this._getOrReturnCtx($,X),y(X,{code:C.not_multiple_of,multipleOf:E.value,message:E.message}),G.dirty()}else Y0.assertNever(E);return{status:G.value,value:$.data}}_getInvalidInput($){let w=this._getOrReturnCtx($);return y(w,{code:C.invalid_type,expected:_.bigint,received:w.parsedType}),i}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,X,G){return new Tw({...this._def,checks:[...this._def.checks,{kind:$,value:w,inclusive:X,message:c.toString(G)}]})}_addCheck($){return new Tw({...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 $}};Tw.create=($)=>{return new Tw({checks:[],typeName:d.ZodBigInt,coerce:$?.coerce??!1,...$0($)})};SX=class SX extends w0{_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==_.boolean){let X=this._getOrReturnCtx($);return y(X,{code:C.invalid_type,expected:_.boolean,received:X.parsedType}),i}return K$($.data)}};SX.create=($)=>{return new SX({typeName:d.ZodBoolean,coerce:$?.coerce||!1,...$0($)})};lw=class lw extends w0{_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==_.date){let E=this._getOrReturnCtx($);return y(E,{code:C.invalid_type,expected:_.date,received:E.parsedType}),i}if(Number.isNaN($.data.getTime())){let E=this._getOrReturnCtx($);return y(E,{code:C.invalid_date}),i}let X=new O$,G=void 0;for(let E of this._def.checks)if(E.kind==="min"){if($.data.getTime()<E.value)G=this._getOrReturnCtx($,G),y(G,{code:C.too_small,message:E.message,inclusive:!0,exact:!1,minimum:E.value,type:"date"}),X.dirty()}else if(E.kind==="max"){if($.data.getTime()>E.value)G=this._getOrReturnCtx($,G),y(G,{code:C.too_big,message:E.message,inclusive:!0,exact:!1,maximum:E.value,type:"date"}),X.dirty()}else Y0.assertNever(E);return{status:X.value,value:new Date($.data.getTime())}}_addCheck($){return new lw({...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}};lw.create=($)=>{return new lw({checks:[],coerce:$?.coerce||!1,typeName:d.ZodDate,...$0($)})};iG=class iG extends w0{_parse($){if(this._getType($)!==_.symbol){let X=this._getOrReturnCtx($);return y(X,{code:C.invalid_type,expected:_.symbol,received:X.parsedType}),i}return K$($.data)}};iG.create=($)=>{return new iG({typeName:d.ZodSymbol,...$0($)})};ZX=class ZX extends w0{_parse($){if(this._getType($)!==_.undefined){let X=this._getOrReturnCtx($);return y(X,{code:C.invalid_type,expected:_.undefined,received:X.parsedType}),i}return K$($.data)}};ZX.create=($)=>{return new ZX({typeName:d.ZodUndefined,...$0($)})};bX=class bX extends w0{_parse($){if(this._getType($)!==_.null){let X=this._getOrReturnCtx($);return y(X,{code:C.invalid_type,expected:_.null,received:X.parsedType}),i}return K$($.data)}};bX.create=($)=>{return new bX({typeName:d.ZodNull,...$0($)})};sw=class sw extends w0{constructor(){super(...arguments);this._any=!0}_parse($){return K$($.data)}};sw.create=($)=>{return new sw({typeName:d.ZodAny,...$0($)})};Vw=class Vw extends w0{constructor(){super(...arguments);this._unknown=!0}_parse($){return K$($.data)}};Vw.create=($)=>{return new Vw({typeName:d.ZodUnknown,...$0($)})};h1=class h1 extends w0{_parse($){let w=this._getOrReturnCtx($);return y(w,{code:C.invalid_type,expected:_.never,received:w.parsedType}),i}};h1.create=($)=>{return new h1({typeName:d.ZodNever,...$0($)})};oG=class oG extends w0{_parse($){if(this._getType($)!==_.undefined){let X=this._getOrReturnCtx($);return y(X,{code:C.invalid_type,expected:_.void,received:X.parsedType}),i}return K$($.data)}};oG.create=($)=>{return new oG({typeName:d.ZodVoid,...$0($)})};Q1=class Q1 extends w0{_parse($){let{ctx:w,status:X}=this._processInputParams($),G=this._def;if(w.parsedType!==_.array)return y(w,{code:C.invalid_type,expected:_.array,received:w.parsedType}),i;if(G.exactLength!==null){let J=w.data.length>G.exactLength.value,W=w.data.length<G.exactLength.value;if(J||W)y(w,{code:J?C.too_big:C.too_small,minimum:W?G.exactLength.value:void 0,maximum:J?G.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:G.exactLength.message}),X.dirty()}if(G.minLength!==null){if(w.data.length<G.minLength.value)y(w,{code:C.too_small,minimum:G.minLength.value,type:"array",inclusive:!0,exact:!1,message:G.minLength.message}),X.dirty()}if(G.maxLength!==null){if(w.data.length>G.maxLength.value)y(w,{code:C.too_big,maximum:G.maxLength.value,type:"array",inclusive:!0,exact:!1,message:G.maxLength.message}),X.dirty()}if(w.common.async)return Promise.all([...w.data].map((J,W)=>{return G.type._parseAsync(new K1(w,J,w.path,W))})).then((J)=>{return O$.mergeArray(X,J)});let E=[...w.data].map((J,W)=>{return G.type._parseSync(new K1(w,J,w.path,W))});return O$.mergeArray(X,E)}get element(){return this._def.type}min($,w){return new Q1({...this._def,minLength:{value:$,message:c.toString(w)}})}max($,w){return new Q1({...this._def,maxLength:{value:$,message:c.toString(w)}})}length($,w){return new Q1({...this._def,exactLength:{value:$,message:c.toString(w)}})}nonempty($){return this.min(1,$)}};Q1.create=($,w)=>{return new Q1({type:$,minLength:null,maxLength:null,exactLength:null,typeName:d.ZodArray,...$0(w)})};m0=class m0 extends w0{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($)!==_.object){let A=this._getOrReturnCtx($);return y(A,{code:C.invalid_type,expected:_.object,received:A.parsedType}),i}let{status:X,ctx:G}=this._processInputParams($),{shape:E,keys:J}=this._getCached(),W=[];if(!(this._def.catchall instanceof h1&&this._def.unknownKeys==="strip")){for(let A in G.data)if(!J.includes(A))W.push(A)}let Y=[];for(let A of J){let D=E[A],U=G.data[A];Y.push({key:{status:"valid",value:A},value:D._parse(new K1(G,U,G.path,A)),alwaysSet:A in G.data})}if(this._def.catchall instanceof h1){let A=this._def.unknownKeys;if(A==="passthrough")for(let D of W)Y.push({key:{status:"valid",value:D},value:{status:"valid",value:G.data[D]}});else if(A==="strict"){if(W.length>0)y(G,{code:C.unrecognized_keys,keys:W}),X.dirty()}else if(A==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let A=this._def.catchall;for(let D of W){let U=G.data[D];Y.push({key:{status:"valid",value:D},value:A._parse(new K1(G,U,G.path,D)),alwaysSet:D in G.data})}}if(G.common.async)return Promise.resolve().then(async()=>{let A=[];for(let D of Y){let U=await D.key,N=await D.value;A.push({key:U,value:N,alwaysSet:D.alwaysSet})}return A}).then((A)=>{return O$.mergeObjectSync(X,A)});else return O$.mergeObjectSync(X,Y)}get shape(){return this._def.shape()}strict($){return c.errToObj,new m0({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(w,X)=>{let G=this._def.errorMap?.(w,X).message??X.defaultError;if(w.code==="unrecognized_keys")return{message:c.errToObj($).message??G};return{message:G}}}:{}})}strip(){return new m0({...this._def,unknownKeys:"strip"})}passthrough(){return new m0({...this._def,unknownKeys:"passthrough"})}extend($){return new m0({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new m0({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:d.ZodObject})}setKey($,w){return this.augment({[$]:w})}catchall($){return new m0({...this._def,catchall:$})}pick($){let w={};for(let X of Y0.objectKeys($))if($[X]&&this.shape[X])w[X]=this.shape[X];return new m0({...this._def,shape:()=>w})}omit($){let w={};for(let X of Y0.objectKeys(this.shape))if(!$[X])w[X]=this.shape[X];return new m0({...this._def,shape:()=>w})}deepPartial(){return PX(this)}partial($){let w={};for(let X of Y0.objectKeys(this.shape)){let G=this.shape[X];if($&&!$[X])w[X]=G;else w[X]=G.optional()}return new m0({...this._def,shape:()=>w})}required($){let w={};for(let X of Y0.objectKeys(this.shape))if($&&!$[X])w[X]=this.shape[X];else{let E=this.shape[X];while(E instanceof B1)E=E._def.innerType;w[X]=E}return new m0({...this._def,shape:()=>w})}keyof(){return RD(Y0.objectKeys(this.shape))}};m0.create=($,w)=>{return new m0({shape:()=>$,unknownKeys:"strip",catchall:h1.create(),typeName:d.ZodObject,...$0(w)})};m0.strictCreate=($,w)=>{return new m0({shape:()=>$,unknownKeys:"strict",catchall:h1.create(),typeName:d.ZodObject,...$0(w)})};m0.lazycreate=($,w)=>{return new m0({shape:$,unknownKeys:"strip",catchall:h1.create(),typeName:d.ZodObject,...$0(w)})};kX=class kX extends w0{_parse($){let{ctx:w}=this._processInputParams($),X=this._def.options;function G(E){for(let W of E)if(W.result.status==="valid")return W.result;for(let W of E)if(W.result.status==="dirty")return w.common.issues.push(...W.ctx.common.issues),W.result;let J=E.map((W)=>new _$(W.ctx.common.issues));return y(w,{code:C.invalid_union,unionErrors:J}),i}if(w.common.async)return Promise.all(X.map(async(E)=>{let J={...w,common:{...w.common,issues:[]},parent:null};return{result:await E._parseAsync({data:w.data,path:w.path,parent:J}),ctx:J}})).then(G);else{let E=void 0,J=[];for(let Y of X){let A={...w,common:{...w.common,issues:[]},parent:null},D=Y._parseSync({data:w.data,path:w.path,parent:A});if(D.status==="valid")return D;else if(D.status==="dirty"&&!E)E={result:D,ctx:A};if(A.common.issues.length)J.push(A.common.issues)}if(E)return w.common.issues.push(...E.ctx.common.issues),E.result;let W=J.map((Y)=>new _$(Y));return y(w,{code:C.invalid_union,unionErrors:W}),i}}get options(){return this._def.options}};kX.create=($,w)=>{return new kX({options:$,typeName:d.ZodUnion,...$0(w)})};dE=class dE extends w0{_parse($){let{ctx:w}=this._processInputParams($);if(w.parsedType!==_.object)return y(w,{code:C.invalid_type,expected:_.object,received:w.parsedType}),i;let X=this.discriminator,G=w.data[X],E=this.optionsMap.get(G);if(!E)return y(w,{code:C.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[X]}),i;if(w.common.async)return E._parseAsync({data:w.data,path:w.path,parent:w});else return E._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,X){let G=new Map;for(let E of w){let J=ww(E.shape[$]);if(!J.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let W of J){if(G.has(W))throw Error(`Discriminator property ${String($)} has duplicate value ${String(W)}`);G.set(W,E)}}return new dE({typeName:d.ZodDiscriminatedUnion,discriminator:$,options:w,optionsMap:G,...$0(X)})}};CX=class CX extends w0{_parse($){let{status:w,ctx:X}=this._processInputParams($),G=(E,J)=>{if(oE(E)||oE(J))return i;let W=U5(E.value,J.value);if(!W.valid)return y(X,{code:C.invalid_intersection_types}),i;if(tE(E)||tE(J))w.dirty();return{status:w.value,value:W.data}};if(X.common.async)return Promise.all([this._def.left._parseAsync({data:X.data,path:X.path,parent:X}),this._def.right._parseAsync({data:X.data,path:X.path,parent:X})]).then(([E,J])=>G(E,J));else return G(this._def.left._parseSync({data:X.data,path:X.path,parent:X}),this._def.right._parseSync({data:X.data,path:X.path,parent:X}))}};CX.create=($,w,X)=>{return new CX({left:$,right:w,typeName:d.ZodIntersection,...$0(X)})};u1=class u1 extends w0{_parse($){let{status:w,ctx:X}=this._processInputParams($);if(X.parsedType!==_.array)return y(X,{code:C.invalid_type,expected:_.array,received:X.parsedType}),i;if(X.data.length<this._def.items.length)return y(X,{code:C.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),i;if(!this._def.rest&&X.data.length>this._def.items.length)y(X,{code:C.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),w.dirty();let E=[...X.data].map((J,W)=>{let Y=this._def.items[W]||this._def.rest;if(!Y)return null;return Y._parse(new K1(X,J,X.path,W))}).filter((J)=>!!J);if(X.common.async)return Promise.all(E).then((J)=>{return O$.mergeArray(w,J)});else return O$.mergeArray(w,E)}get items(){return this._def.items}rest($){return new u1({...this._def,rest:$})}};u1.create=($,w)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new u1({items:$,typeName:d.ZodTuple,rest:null,...$0(w)})};tG=class tG extends w0{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:w,ctx:X}=this._processInputParams($);if(X.parsedType!==_.object)return y(X,{code:C.invalid_type,expected:_.object,received:X.parsedType}),i;let G=[],E=this._def.keyType,J=this._def.valueType;for(let W in X.data)G.push({key:E._parse(new K1(X,W,X.path,W)),value:J._parse(new K1(X,X.data[W],X.path,W)),alwaysSet:W in X.data});if(X.common.async)return O$.mergeObjectAsync(w,G);else return O$.mergeObjectSync(w,G)}get element(){return this._def.valueType}static create($,w,X){if(w instanceof w0)return new tG({keyType:$,valueType:w,typeName:d.ZodRecord,...$0(X)});return new tG({keyType:z1.create(),valueType:$,typeName:d.ZodRecord,...$0(w)})}};dG=class dG extends w0{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:w,ctx:X}=this._processInputParams($);if(X.parsedType!==_.map)return y(X,{code:C.invalid_type,expected:_.map,received:X.parsedType}),i;let G=this._def.keyType,E=this._def.valueType,J=[...X.data.entries()].map(([W,Y],A)=>{return{key:G._parse(new K1(X,W,X.path,[A,"key"])),value:E._parse(new K1(X,Y,X.path,[A,"value"]))}});if(X.common.async){let W=new Map;return Promise.resolve().then(async()=>{for(let Y of J){let A=await Y.key,D=await Y.value;if(A.status==="aborted"||D.status==="aborted")return i;if(A.status==="dirty"||D.status==="dirty")w.dirty();W.set(A.value,D.value)}return{status:w.value,value:W}})}else{let W=new Map;for(let Y of J){let{key:A,value:D}=Y;if(A.status==="aborted"||D.status==="aborted")return i;if(A.status==="dirty"||D.status==="dirty")w.dirty();W.set(A.value,D.value)}return{status:w.value,value:W}}}};dG.create=($,w,X)=>{return new dG({valueType:w,keyType:$,typeName:d.ZodMap,...$0(X)})};aw=class aw extends w0{_parse($){let{status:w,ctx:X}=this._processInputParams($);if(X.parsedType!==_.set)return y(X,{code:C.invalid_type,expected:_.set,received:X.parsedType}),i;let G=this._def;if(G.minSize!==null){if(X.data.size<G.minSize.value)y(X,{code:C.too_small,minimum:G.minSize.value,type:"set",inclusive:!0,exact:!1,message:G.minSize.message}),w.dirty()}if(G.maxSize!==null){if(X.data.size>G.maxSize.value)y(X,{code:C.too_big,maximum:G.maxSize.value,type:"set",inclusive:!0,exact:!1,message:G.maxSize.message}),w.dirty()}let E=this._def.valueType;function J(Y){let A=new Set;for(let D of Y){if(D.status==="aborted")return i;if(D.status==="dirty")w.dirty();A.add(D.value)}return{status:w.value,value:A}}let W=[...X.data.values()].map((Y,A)=>E._parse(new K1(X,Y,X.path,A)));if(X.common.async)return Promise.all(W).then((Y)=>J(Y));else return J(W)}min($,w){return new aw({...this._def,minSize:{value:$,message:c.toString(w)}})}max($,w){return new aw({...this._def,maxSize:{value:$,message:c.toString(w)}})}size($,w){return this.min($,w).max($,w)}nonempty($){return this.min(1,$)}};aw.create=($,w)=>{return new aw({valueType:$,minSize:null,maxSize:null,typeName:d.ZodSet,...$0(w)})};qX=class qX extends w0{constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:w}=this._processInputParams($);if(w.parsedType!==_.function)return y(w,{code:C.invalid_type,expected:_.function,received:w.parsedType}),i;function X(W,Y){return rG({data:W,path:w.path,errorMaps:[w.common.contextualErrorMap,w.schemaErrorMap,IX(),$w].filter((A)=>!!A),issueData:{code:C.invalid_arguments,argumentsError:Y}})}function G(W,Y){return rG({data:W,path:w.path,errorMaps:[w.common.contextualErrorMap,w.schemaErrorMap,IX(),$w].filter((A)=>!!A),issueData:{code:C.invalid_return_type,returnTypeError:Y}})}let E={errorMap:w.common.contextualErrorMap},J=w.data;if(this._def.returns instanceof ew){let W=this;return K$(async function(...Y){let A=new _$([]),D=await W._def.args.parseAsync(Y,E).catch((H)=>{throw A.addIssue(X(Y,H)),A}),U=await Reflect.apply(J,this,D);return await W._def.returns._def.type.parseAsync(U,E).catch((H)=>{throw A.addIssue(G(U,H)),A})})}else{let W=this;return K$(function(...Y){let A=W._def.args.safeParse(Y,E);if(!A.success)throw new _$([X(Y,A.error)]);let D=Reflect.apply(J,this,A.data),U=W._def.returns.safeParse(D,E);if(!U.success)throw new _$([G(D,U.error)]);return U.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new qX({...this._def,args:u1.create($).rest(Vw.create())})}returns($){return new qX({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,w,X){return new qX({args:$?$:u1.create([]).rest(Vw.create()),returns:w||Vw.create(),typeName:d.ZodFunction,...$0(X)})}};vX=class vX extends w0{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})}};vX.create=($,w)=>{return new vX({getter:$,typeName:d.ZodLazy,...$0(w)})};_X=class _X extends w0{_parse($){if($.data!==this._def.value){let w=this._getOrReturnCtx($);return y(w,{received:w.data,code:C.invalid_literal,expected:this._def.value}),i}return{status:"valid",value:$.data}}get value(){return this._def.value}};_X.create=($,w)=>{return new _X({value:$,typeName:d.ZodLiteral,...$0(w)})};Iw=class Iw extends w0{_parse($){if(typeof $.data!=="string"){let w=this._getOrReturnCtx($),X=this._def.values;return y(w,{expected:Y0.joinValues(X),received:w.parsedType,code:C.invalid_type}),i}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let w=this._getOrReturnCtx($),X=this._def.values;return y(w,{received:w.data,code:C.invalid_enum_value,options:X}),i}return K$($.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 Iw.create($,{...this._def,...w})}exclude($,w=this._def){return Iw.create(this.options.filter((X)=>!$.includes(X)),{...this._def,...w})}};Iw.create=RD;fX=class fX extends w0{_parse($){let w=Y0.getValidEnumValues(this._def.values),X=this._getOrReturnCtx($);if(X.parsedType!==_.string&&X.parsedType!==_.number){let G=Y0.objectValues(w);return y(X,{expected:Y0.joinValues(G),received:X.parsedType,code:C.invalid_type}),i}if(!this._cache)this._cache=new Set(Y0.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let G=Y0.objectValues(w);return y(X,{received:X.data,code:C.invalid_enum_value,options:G}),i}return K$($.data)}get enum(){return this._def.values}};fX.create=($,w)=>{return new fX({values:$,typeName:d.ZodNativeEnum,...$0(w)})};ew=class ew extends w0{unwrap(){return this._def.type}_parse($){let{ctx:w}=this._processInputParams($);if(w.parsedType!==_.promise&&w.common.async===!1)return y(w,{code:C.invalid_type,expected:_.promise,received:w.parsedType}),i;let X=w.parsedType===_.promise?w.data:Promise.resolve(w.data);return K$(X.then((G)=>{return this._def.type.parseAsync(G,{path:w.path,errorMap:w.common.contextualErrorMap})}))}};ew.create=($,w)=>{return new ew({type:$,typeName:d.ZodPromise,...$0(w)})};V1=class V1 extends w0{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===d.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:w,ctx:X}=this._processInputParams($),G=this._def.effect||null,E={addIssue:(J)=>{if(y(X,J),J.fatal)w.abort();else w.dirty()},get path(){return X.path}};if(E.addIssue=E.addIssue.bind(E),G.type==="preprocess"){let J=G.transform(X.data,E);if(X.common.async)return Promise.resolve(J).then(async(W)=>{if(w.value==="aborted")return i;let Y=await this._def.schema._parseAsync({data:W,path:X.path,parent:X});if(Y.status==="aborted")return i;if(Y.status==="dirty")return dw(Y.value);if(w.value==="dirty")return dw(Y.value);return Y});else{if(w.value==="aborted")return i;let W=this._def.schema._parseSync({data:J,path:X.path,parent:X});if(W.status==="aborted")return i;if(W.status==="dirty")return dw(W.value);if(w.value==="dirty")return dw(W.value);return W}}if(G.type==="refinement"){let J=(W)=>{let Y=G.refinement(W,E);if(X.common.async)return Promise.resolve(Y);if(Y instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return W};if(X.common.async===!1){let W=this._def.schema._parseSync({data:X.data,path:X.path,parent:X});if(W.status==="aborted")return i;if(W.status==="dirty")w.dirty();return J(W.value),{status:w.value,value:W.value}}else return this._def.schema._parseAsync({data:X.data,path:X.path,parent:X}).then((W)=>{if(W.status==="aborted")return i;if(W.status==="dirty")w.dirty();return J(W.value).then(()=>{return{status:w.value,value:W.value}})})}if(G.type==="transform")if(X.common.async===!1){let J=this._def.schema._parseSync({data:X.data,path:X.path,parent:X});if(!Kw(J))return i;let W=G.transform(J.value,E);if(W instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:w.value,value:W}}else return this._def.schema._parseAsync({data:X.data,path:X.path,parent:X}).then((J)=>{if(!Kw(J))return i;return Promise.resolve(G.transform(J.value,E)).then((W)=>({status:w.value,value:W}))});Y0.assertNever(G)}};V1.create=($,w,X)=>{return new V1({schema:$,typeName:d.ZodEffects,effect:w,...$0(X)})};V1.createWithPreprocess=($,w,X)=>{return new V1({schema:w,effect:{type:"preprocess",transform:$},typeName:d.ZodEffects,...$0(X)})};B1=class B1 extends w0{_parse($){if(this._getType($)===_.undefined)return K$(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}};B1.create=($,w)=>{return new B1({innerType:$,typeName:d.ZodOptional,...$0(w)})};Xw=class Xw extends w0{_parse($){if(this._getType($)===_.null)return K$(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}};Xw.create=($,w)=>{return new Xw({innerType:$,typeName:d.ZodNullable,...$0(w)})};xX=class xX extends w0{_parse($){let{ctx:w}=this._processInputParams($),X=w.data;if(w.parsedType===_.undefined)X=this._def.defaultValue();return this._def.innerType._parse({data:X,path:w.path,parent:w})}removeDefault(){return this._def.innerType}};xX.create=($,w)=>{return new xX({innerType:$,typeName:d.ZodDefault,defaultValue:typeof w.default==="function"?w.default:()=>w.default,...$0(w)})};yX=class yX extends w0{_parse($){let{ctx:w}=this._processInputParams($),X={...w,common:{...w.common,issues:[]}},G=this._def.innerType._parse({data:X.data,path:X.path,parent:{...X}});if(jX(G))return G.then((E)=>{return{status:"valid",value:E.status==="valid"?E.value:this._def.catchValue({get error(){return new _$(X.common.issues)},input:X.data})}});else return{status:"valid",value:G.status==="valid"?G.value:this._def.catchValue({get error(){return new _$(X.common.issues)},input:X.data})}}removeCatch(){return this._def.innerType}};yX.create=($,w)=>{return new yX({innerType:$,typeName:d.ZodCatch,catchValue:typeof w.catch==="function"?w.catch:()=>w.catch,...$0(w)})};lG=class lG extends w0{_parse($){if(this._getType($)!==_.nan){let X=this._getOrReturnCtx($);return y(X,{code:C.invalid_type,expected:_.nan,received:X.parsedType}),i}return{status:"valid",value:$.data}}};lG.create=($)=>{return new lG({typeName:d.ZodNaN,...$0($)})};Zj=Symbol("zod_brand");lE=class lE extends w0{_parse($){let{ctx:w}=this._processInputParams($),X=w.data;return this._def.type._parse({data:X,path:w.path,parent:w})}unwrap(){return this._def.type}};sG=class sG extends w0{_parse($){let{status:w,ctx:X}=this._processInputParams($);if(X.common.async)return(async()=>{let E=await this._def.in._parseAsync({data:X.data,path:X.path,parent:X});if(E.status==="aborted")return i;if(E.status==="dirty")return w.dirty(),dw(E.value);else return this._def.out._parseAsync({data:E.value,path:X.path,parent:X})})();else{let G=this._def.in._parseSync({data:X.data,path:X.path,parent:X});if(G.status==="aborted")return i;if(G.status==="dirty")return w.dirty(),{status:"dirty",value:G.value};else return this._def.out._parseSync({data:G.value,path:X.path,parent:X})}}static create($,w){return new sG({in:$,out:w,typeName:d.ZodPipeline})}};gX=class gX extends w0{_parse($){let w=this._def.innerType._parse($),X=(G)=>{if(Kw(G))G.value=Object.freeze(G.value);return G};return jX(w)?w.then((G)=>X(G)):X(w)}unwrap(){return this._def.innerType}};gX.create=($,w)=>{return new gX({innerType:$,typeName:d.ZodReadonly,...$0(w)})};bj={object:m0.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"})(d||(d={}));ID=z1.create,jD=Rw.create,Cj=lG.create,vj=Tw.create,PD=SX.create,_j=lw.create,fj=iG.create,xj=ZX.create,yj=bX.create,gj=sw.create,hj=Vw.create,uj=h1.create,cj=oG.create,mj=Q1.create,nj=m0.create,pj=m0.strictCreate,rj=kX.create,ij=dE.create,oj=CX.create,tj=u1.create,dj=tG.create,lj=dG.create,sj=aw.create,aj=qX.create,ej=vX.create,$P=_X.create,wP=Iw.create,XP=fX.create,GP=ew.create,EP=V1.create,JP=B1.create,WP=Xw.create,YP=V1.createWithPreprocess,AP=sG.create,NP={string:($)=>z1.create({...$,coerce:!0}),number:($)=>Rw.create({...$,coerce:!0}),boolean:($)=>SX.create({...$,coerce:!0}),bigint:($)=>Tw.create({...$,coerce:!0}),date:($)=>lw.create({...$,coerce:!0})},HP=i});var O={};e1(O,{void:()=>cj,util:()=>Y0,unknown:()=>hj,union:()=>rj,undefined:()=>xj,tuple:()=>tj,transformer:()=>EP,symbol:()=>fj,string:()=>ID,strictObject:()=>pj,setErrorMap:()=>Wj,set:()=>sj,record:()=>dj,quotelessJson:()=>Ej,promise:()=>GP,preprocess:()=>YP,pipeline:()=>AP,ostring:()=>DP,optional:()=>JP,onumber:()=>UP,oboolean:()=>OP,objectUtil:()=>W5,object:()=>nj,number:()=>jD,nullable:()=>WP,null:()=>yj,never:()=>uj,nativeEnum:()=>XP,nan:()=>Cj,map:()=>lj,makeIssue:()=>rG,literal:()=>$P,lazy:()=>ej,late:()=>bj,isValid:()=>Kw,isDirty:()=>tE,isAsync:()=>jX,isAborted:()=>oE,intersection:()=>oj,instanceof:()=>kj,getParsedType:()=>g1,getErrorMap:()=>IX,function:()=>aj,enum:()=>wP,effect:()=>EP,discriminatedUnion:()=>ij,defaultErrorMap:()=>$w,datetimeRegex:()=>VD,date:()=>_j,custom:()=>TD,coerce:()=>NP,boolean:()=>PD,bigint:()=>vj,array:()=>mj,any:()=>gj,addIssueToContext:()=>y,ZodVoid:()=>oG,ZodUnknown:()=>Vw,ZodUnion:()=>kX,ZodUndefined:()=>ZX,ZodType:()=>w0,ZodTuple:()=>u1,ZodTransformer:()=>V1,ZodSymbol:()=>iG,ZodString:()=>z1,ZodSet:()=>aw,ZodSchema:()=>w0,ZodRecord:()=>tG,ZodReadonly:()=>gX,ZodPromise:()=>ew,ZodPipeline:()=>sG,ZodParsedType:()=>_,ZodOptional:()=>B1,ZodObject:()=>m0,ZodNumber:()=>Rw,ZodNullable:()=>Xw,ZodNull:()=>bX,ZodNever:()=>h1,ZodNativeEnum:()=>fX,ZodNaN:()=>lG,ZodMap:()=>dG,ZodLiteral:()=>_X,ZodLazy:()=>vX,ZodIssueCode:()=>C,ZodIntersection:()=>CX,ZodFunction:()=>qX,ZodFirstPartyTypeKind:()=>d,ZodError:()=>_$,ZodEnum:()=>Iw,ZodEffects:()=>V1,ZodDiscriminatedUnion:()=>dE,ZodDefault:()=>xX,ZodDate:()=>lw,ZodCatch:()=>yX,ZodBranded:()=>lE,ZodBoolean:()=>SX,ZodBigInt:()=>Tw,ZodArray:()=>Q1,ZodAny:()=>sw,Schema:()=>w0,ParseStatus:()=>O$,OK:()=>K$,NEVER:()=>HP,INVALID:()=>i,EMPTY_PATH:()=>Yj,DIRTY:()=>dw,BRAND:()=>Zj});var O5=B(()=>{iE();A5();FD();pG();qD();rE()});var aG=B(()=>{O5();O5()});import{existsSync as SD,readFileSync as LP}from"fs";import{homedir as kD}from"os";import{join as N5}from"path";function BP($){if($.startsWith("~/"))return N5(kD(),$.slice(2));return $}function bD($){try{return JSON.parse(LP($,"utf-8"))}catch{return{}}}function eG($,w){let X={...$};for(let[G,E]of Object.entries(w))if(E!==null&&typeof E==="object"&&!Array.isArray(E)&&typeof X[G]==="object"&&X[G]!==null)X[G]=eG(X[G],E);else X[G]=E;return X}function KP(){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 X={};if(process.env.ORC_RUNNER_TIMEOUT)X.default_timeout_secs=Number(process.env.ORC_RUNNER_TIMEOUT);if(process.env.ORC_RUNNER_MAX_JOBS)X.max_concurrent_jobs=Number(process.env.ORC_RUNNER_MAX_JOBS);if(process.env.ORC_RUNNER_LOG_DAYS)X.log_retention_days=Number(process.env.ORC_RUNNER_LOG_DAYS);if(Object.keys(X).length)$.runner=X;let G={};if(process.env.ORC_SNAPSHOT_MAX_BYTES)G.snapshot_max_bytes=Number(process.env.ORC_SNAPSHOT_MAX_BYTES);if(process.env.ORC_LAYER1_TASKS)G.layer1_task_limit=Number(process.env.ORC_LAYER1_TASKS);if(process.env.ORC_LAYER1_MEMORIES)G.layer1_memory_limit=Number(process.env.ORC_LAYER1_MEMORIES);if(Object.keys(G).length)$.context=G;let E={};if(process.env.ORC_TELEGRAM_TOKEN)E.telegram={token:process.env.ORC_TELEGRAM_TOKEN,enabled:!0};if(process.env.ORC_SLACK_BOT_TOKEN||process.env.ORC_SLACK_APP_TOKEN)E.slack={bot_token:process.env.ORC_SLACK_BOT_TOKEN,app_token:process.env.ORC_SLACK_APP_TOKEN,enabled:!0};if(Object.keys(E).length)$.gateway=E;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 W={};if(process.env.ORC_TTS_PROVIDER)W.provider=process.env.ORC_TTS_PROVIDER;if(process.env.ORC_TTS_VOICE)W.voice=process.env.ORC_TTS_VOICE;if(process.env.ORC_TTS_MODE)W.mode=process.env.ORC_TTS_MODE;if(Object.keys(W).length)W.enabled=!0,$.tts=W;return $}function Q0($){if(sE&&!$)return sE;let w=N5(kD(),".orc","config.json"),X=N5(process.cwd(),".orc","config.json"),G={};if(SD(w))G=eG(G,bD(w));if(SD(X))G=eG(G,bD(X));if(G=eG(G,KP()),$)G=eG(G,$);if(G.bridge&&!G.gateway)G.gateway=G.bridge;delete G.bridge;let E=QP.safeParse(G);if(!E.success)throw Error(`Invalid orc config:
|
|
4
|
-
${
|
|
5
|
-
`)}displayWidth($){return
|
|
6
|
-
`+" ".repeat(w+
|
|
7
|
-
${J}`)}boxWrap($,w){if(w<this.minWidthToWrap)return $;let
|
|
8
|
-
`)}}function
|
|
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=dP(G.data.db.path),HJ=G.data,HJ}var pP,pO,UG,oP,tP,iP,HJ=null;var C$=R(()=>{WG();pP=U.enum(["direct","agent:claude","agent:codex","agent:cursor","multi"]).or(U.string().startsWith("job:")).default("direct"),pO=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:pP,allow_channel_mentions:U.boolean().default(!0),share_session_in_channel:U.boolean().default(!1),streaming_preview:U.boolean().default(!0)}),UG=U.object({api_key:U.string().optional(),base_url:U.string().optional(),model:U.string().optional()}),oP=U.object({enabled:U.boolean().default(!1),provider:U.enum(["openai","groq","qwen"]).default("openai"),language:U.string().default(""),openai:UG.default({}),groq:UG.default({}),qwen:UG.default({})}),tP=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:UG.default({}),qwen:UG.default({})}),iP=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:pO.default({}),slack:pO.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:oP.default({}),tts:tP.default({}),activeProject:U.string().optional()})});var YG=Z((sP)=>{class qD 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 iO extends qD{constructor($){super(1,"commander.invalidArgument",$);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}sP.CommanderError=qD;sP.InvalidArgumentError=iO});var LJ=Z((Eq)=>{var{InvalidArgumentError:$q}=YG();class dO{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 $q(`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 wq($){let w=$.name()+($.variadic===!0?"...":"");return $.required?"<"+w+">":"["+w+"]"}Eq.Argument=dO;Eq.humanReadableArgName=wq});var SD=Z((Aq)=>{var{humanReadableArgName:Jq}=LJ();class lO{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)=>Jq(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 sO($).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
|
+
`+" ".repeat(w+D));return J+A+" ".repeat(D)+O.replace(/\n/g,`
|
|
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 sO($){let w=/\x1b\[\d*(;\d*)*m/g;return $.replace(w,"")}Aq.Help=lO;Aq.stripColor=sO});var kD=Z((Uq)=>{var{InvalidArgumentError:Wq}=YG();class eO{constructor($,w){this.flags=$,this.description=w||"",this.required=$.includes("<"),this.optional=$.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test($),this.mandatory=!1;let E=Oq($);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 Wq(`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 aO(this.name().replace(/^no-/,""));return aO(this.name())}is($){return this.short===$||this.long===$}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class $U{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 aO($){return $.split("-").reduce((w,E)=>{return w+E[0].toUpperCase()+E.slice(1)})}function Oq($){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
|
-
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(
|
|
12
|
-
- too many short flags`);if(
|
|
13
|
-
- too many long flags`);throw Error(`${
|
|
14
|
-
- unrecognised flag format`)}if(w===void 0&&
|
|
15
|
-
(Did you mean one of ${
|
|
16
|
-
(Did you mean ${
|
|
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 '${
|
|
19
|
-
- already used by option '${w.flags}'`)}this.options.push($)}_registerCommand($){let w=(
|
|
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,
|
|
21
|
-
- if '${
|
|
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
|
+
- too many short flags`);if(G.test(A))throw Error(`${D}
|
|
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}}Uq.Option=eO;Uq.DualOptions=$U});var wU=Z((jq)=>{function Lq($,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 Fq($,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=Lq($,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
|
+
(Did you mean one of ${X.join(", ")}?)`;if(X.length===1)return`
|
|
16
|
+
(Did you mean ${X[0]}?)`;return""}jq.suggestSimilar=Fq});var JU=Z((Kq)=>{var Rq=V$("events").EventEmitter,bD=V$("child_process"),Hw=V$("path"),FJ=V$("fs"),Q0=V$("process"),{Argument:zq,humanReadableArgName:Tq}=LJ(),{CommanderError:ZD}=YG(),{Help:Bq,stripColor:Qq}=SD(),{Option:EU,DualOptions:Iq}=kD(),{suggestSimilar:XU}=wU();class _D extends Rq{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:()=>CD()??(Q0.stdout.isTTY&&Q0.stdout.hasColors?.()),getErrHasColors:()=>CD()??(Q0.stderr.isTTY&&Q0.stderr.hasColors?.()),stripColor:(w)=>Qq(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 _D($)}createHelp(){return Object.assign(new Bq,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 zq($,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 ZD($,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 EU($,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 EU)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(FJ.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
|
+
- 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
|
-
- ${
|
|
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(FJ.existsSync(Y))return Y;if(X.includes(Hw.extname(O)))return;let H=X.find((L)=>FJ.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=FJ.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=GU(Q0.execArgv).concat(w),D=bD.spawn(Q0.argv[0],w,{stdio:"inherit"});else D=bD.spawn(J,w,{stdio:"inherit"});else this._checkForMissingExecutable(J,A,$._name),w.unshift(J),w=GU(Q0.execArgv).concat(w),D=bD.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 ZD(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 ZD(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
|
|
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
|
|
28
|
-
Expecting one of '${
|
|
29
|
-
`)}),this}_outputHelpIfRequested($){let w=this._getHelpOption();if(w&&$.find((G)=>w.is(G)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function mD($){return $.map((w)=>{if(!w.startsWith("--inspect"))return w;let X,G="127.0.0.1",E="9229",J;if((J=w.match(/^(--inspect(-brk)?)$/))!==null)X=J[1];else if((J=w.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(X=J[1],/^\d+$/.test(J[3]))E=J[3];else G=J[3];else if((J=w.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)X=J[1],G=J[3],E=J[4];if(X&&E!=="0")return`${X}=${G}:${parseInt(E)+1}`;return w})}function Q5(){if(B0.env.NO_COLOR||B0.env.FORCE_COLOR==="0"||B0.env.FORCE_COLOR==="false")return!1;if(B0.env.FORCE_COLOR||B0.env.CLICOLOR_FORCE!==void 0)return!0;return}tP.Command=B5;tP.useColor=Q5});var oD=b((eP)=>{var{Argument:pD}=aE(),{Command:K5}=nD(),{CommanderError:sP,InvalidArgumentError:rD}=w6(),{Help:aP}=L5(),{Option:iD}=F5();eP.program=new K5;eP.createCommand=($)=>new K5($);eP.createOption=($,w)=>new iD($,w);eP.createArgument=($,w)=>new pD($,w);eP.Command=K5;eP.Option=iD;eP.Argument=pD;eP.Help=aP;eP.CommanderError=sP;eP.InvalidArgumentError=rD;eP.InvalidOptionArgumentError=rD});function $4($,w,X,G){if(dD[$]<dD[N2])return;let E=new Date().toISOString(),W=`${O2[$]}[${$.toUpperCase()}]\x1B[0m ${E} [${w}]`;if(G!==void 0)console.error(`${W} ${X}`,G);else console.error(`${W} ${X}`)}function P0($){return{debug:(w,X)=>$4("debug",$,w,X),info:(w,X)=>$4("info",$,w,X),warn:(w,X)=>$4("warn",$,w,X),error:(w,X)=>$4("error",$,w,X)}}var dD,O2,N2;var f$=B(()=>{dD={debug:0,info:1,warn:2,error:3},O2={debug:"\x1B[36m",info:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m"},N2=process.env.ORC_LOG_LEVEL??"info"});import{randomBytes as H2}from"crypto";function M2($,w){let X="";for(let G=w-1;G>=0;G--){let E=$%V5;X=R5[E]+X,$=Math.floor($/V5)}return X}function z2($){let w=H2($),X="";for(let G=0;G<$;G++)X+=R5[(w[G]??0)%V5];return X}function e(){return M2(Date.now(),L2)+z2(F2)}var R5="0123456789ABCDEFGHJKMNPQRSTVWXYZ",V5,L2=10,F2=16;var l$=B(()=>{V5=R5.length});function Z($,w){if(!$||typeof $!=="object")return!1;if($ instanceof w)return!0;if(!Object.prototype.hasOwnProperty.call(w,I))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 X=Object.getPrototypeOf($).constructor;if(X)while(X){if(I in X&&X[I]===w[I])return!0;X=Object.getPrototypeOf(X)}return!1}var I;var a=B(()=>{I=Symbol.for("drizzle:entityKind")});var lD,T5,I5;var w4=B(()=>{a();lD=class lD{static[I]="ConsoleLogWriter";write($){console.log($)}};T5=class T5{static[I]="DefaultLogger";writer;constructor($){this.writer=$?.writer??new lD}logQuery($,w){let X=w.map((E)=>{try{return JSON.stringify(E)}catch{return String(E)}}),G=X.length?` -- params: [${X.join(", ")}]`:"";this.writer.write(`Query: ${$}${G}`)}};I5=class I5{static[I]="NoopLogger";logQuery(){}}});var s$;var X6=B(()=>{s$=Symbol.for("drizzle:Name")});function jw($){return $[s$]}function $X($){return`${$[X4]??"public"}.${$[s$]}`}var X4,G4,sD,j5,P5,G6,aD,Q2,x;var q$=B(()=>{a();X6();X4=Symbol.for("drizzle:Schema"),G4=Symbol.for("drizzle:Columns"),sD=Symbol.for("drizzle:ExtraConfigColumns"),j5=Symbol.for("drizzle:OriginalName"),P5=Symbol.for("drizzle:BaseName"),G6=Symbol.for("drizzle:IsAlias"),aD=Symbol.for("drizzle:ExtraConfigBuilder"),Q2=Symbol.for("drizzle:IsDrizzleTable");x=class x{static[I]="Table";static Symbol={Name:s$,Schema:X4,OriginalName:j5,Columns:G4,ExtraConfigColumns:sD,BaseName:P5,IsAlias:G6,ExtraConfigBuilder:aD};[s$];[j5];[X4];[G4];[sD];[P5];[G6]=!1;[Q2]=!0;[aD]=void 0;constructor($,w,X){this[s$]=this[j5]=$,this[X4]=w,this[P5]=X}}});var V0;var R1=B(()=>{a();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[I]="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 q5;var S5=B(()=>{a();q5=class q5{static[I]="ColumnBuilder";config;constructor($,w,X){this.config={name:$,keyAsName:$==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:w,columnType:X,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 eD($,...w){return $(...w)}var $U=()=>{};function wU($,w){return`${$[s$]}_${w.join("_")}_unique`}var XU=B(()=>{X6()});var E4,B2;var GU=B(()=>{R1();a();XU();E4=class E4 extends V0{constructor($,w){if(!w.uniqueName)w.uniqueName=wU($,[w.name]);super($,w);this.table=$}static[I]="PgColumn"};B2=class B2 extends E4{static[I]="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 JU($){return!!$&&typeof $==="function"&&EU in $&&$[EU]===!0}var EU,K2;var WU=B(()=>{a();GU();EU=Symbol.for("drizzle:isPgEnum");K2=class K2 extends E4{static[I]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor($,w){super($,w);this.enum=w.enum}getSQLType(){return this.enum.enumName}}});var W$,E6;var c1=B(()=>{a();W$=class W${static[I]="Subquery";constructor($,w,X,G=!1){this._={brand:"Subquery",sql:$,selectedFields:w,alias:X,isWith:G}}};E6=class E6 extends W${static[I]="WithSubquery"}});var YU="0.41.0";var AU=()=>{};var Z5,b5,DU;var UU=B(()=>{$U();AU();DU={startActiveSpan($,w){if(!Z5)return w();if(!b5)b5=Z5.trace.getTracer("drizzle-orm",YU);return eD((X,G)=>G.startActiveSpan($,(E)=>{try{return w(E)}catch(J){throw E.setStatus({code:X.SpanStatusCode.ERROR,message:J instanceof Error?J.message:"Unknown error"}),J}finally{E.end()}}),Z5,b5)}}});var n0;var Ew=B(()=>{n0=Symbol.for("drizzle:ViewBaseConfig")});function k5($){return $!==null&&$!==void 0&&typeof $.getSQL==="function"}function V2($){let w={sql:"",params:[]};for(let X of $)if(w.sql+=X.sql,w.params.push(...X.params),X.typings?.length){if(!w.typings)w.typings=[];w.typings.push(...X.typings)}return w}function OU($){return typeof $==="object"&&$!==null&&"mapToDriverValue"in $&&typeof $.mapToDriverValue==="function"}function K($,...w){let X=[];if(w.length>0||$.length>0&&$[0]!=="")X.push(new G$($[0]));for(let[G,E]of w.entries())X.push(E,new G$($[G+1]));return new u(X)}function J6($,w){return $.map((X)=>{if(Z(X,Pw)){if(!(X.name in w))throw Error(`No value for placeholder "${X.name}" was provided`);return w[X.name]}if(Z(X,a$)&&Z(X.value,Pw)){if(!(X.value.name in w))throw Error(`No value for placeholder "${X.value.name}" was provided`);return X.encoder.mapToDriverValue(w[X.value.name])}return X})}var G$,u,J4,NU,HU,Pi,a$,Pw,R2,E1;var R$=B(()=>{a();WU();c1();UU();Ew();R1();q$();G$=class G${static[I]="StringChunk";value;constructor($){this.value=Array.isArray($)?$:[$]}getSQL(){return new u([this])}};u=class u{constructor($){this.queryChunks=$}static[I]="SQL";decoder=NU;shouldInlineParams=!1;append($){return this.queryChunks.push(...$.queryChunks),this}toQuery($){return DU.startActiveSpan("drizzle.buildSQL",(w)=>{let X=this.buildQueryFromSourceParams(this.queryChunks,$);return w?.setAttributes({"drizzle.query.text":X.sql,"drizzle.query.params":JSON.stringify(X.params)}),X})}buildQueryFromSourceParams($,w){let X=Object.assign({},w,{inlineParams:w.inlineParams||this.shouldInlineParams,paramStartIndex:w.paramStartIndex||{value:0}}),{casing:G,escapeName:E,escapeParam:J,prepareTyping:W,inlineParams:Y,paramStartIndex:A}=X;return V2($.map((D)=>{if(Z(D,G$))return{sql:D.value.join(""),params:[]};if(Z(D,J4))return{sql:E(D.value),params:[]};if(D===void 0)return{sql:"",params:[]};if(Array.isArray(D)){let U=[new G$("(")];for(let[N,H]of D.entries())if(U.push(H),N<D.length-1)U.push(new G$(", "));return U.push(new G$(")")),this.buildQueryFromSourceParams(U,X)}if(Z(D,u))return this.buildQueryFromSourceParams(D.queryChunks,{...X,inlineParams:Y||D.shouldInlineParams});if(Z(D,x)){let U=D[x.Symbol.Schema],N=D[x.Symbol.Name];return{sql:U===void 0||D[G6]?E(N):E(U)+"."+E(N),params:[]}}if(Z(D,V0)){let U=G.getColumnCasing(D);if(w.invokeSource==="indexes")return{sql:E(U),params:[]};let N=D.table[x.Symbol.Schema];return{sql:D.table[G6]||N===void 0?E(D.table[x.Symbol.Name])+"."+E(U):E(N)+"."+E(D.table[x.Symbol.Name])+"."+E(U),params:[]}}if(Z(D,E1)){let U=D[n0].schema,N=D[n0].name;return{sql:U===void 0||D[n0].isAlias?E(N):E(U)+"."+E(N),params:[]}}if(Z(D,a$)){if(Z(D.value,Pw))return{sql:J(A.value++,D),params:[D],typings:["none"]};let U=D.value===null?null:D.encoder.mapToDriverValue(D.value);if(Z(U,u))return this.buildQueryFromSourceParams([U],X);if(Y)return{sql:this.mapInlineParam(U,X),params:[]};let N=["none"];if(W)N=[W(D.encoder)];return{sql:J(A.value++,U),params:[U],typings:N}}if(Z(D,Pw))return{sql:J(A.value++,D),params:[D],typings:["none"]};if(Z(D,u.Aliased)&&D.fieldAlias!==void 0)return{sql:E(D.fieldAlias),params:[]};if(Z(D,W$)){if(D._.isWith)return{sql:E(D._.alias),params:[]};return this.buildQueryFromSourceParams([new G$("("),D._.sql,new G$(") "),new J4(D._.alias)],X)}if(JU(D)){if(D.schema)return{sql:E(D.schema)+"."+E(D.enumName),params:[]};return{sql:E(D.enumName),params:[]}}if(k5(D)){if(D.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([D.getSQL()],X);return this.buildQueryFromSourceParams([new G$("("),D.getSQL(),new G$(")")],X)}if(Y)return{sql:this.mapInlineParam(D,X),params:[]};return{sql:J(A.value++,D),params:[D],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 X=$.toString();if(X==="[object Object]")return w(JSON.stringify($));return w(X)}throw Error("Unexpected param value: "+$)}getSQL(){return this}as($){if($===void 0)return this;return new u.Aliased(this,$)}mapWith($){return this.decoder=typeof $==="function"?{mapFromDriverValue:$}:$,this}inlineParams(){return this.shouldInlineParams=!0,this}if($){return $?this:void 0}};J4=class J4{constructor($){this.value=$}static[I]="Name";brand;getSQL(){return new u([this])}};NU={mapFromDriverValue:($)=>$},HU={mapToDriverValue:($)=>$},Pi={...NU,...HU};a$=class a${constructor($,w=HU){this.value=$,this.encoder=w}static[I]="Param";brand;getSQL(){return new u([this])}};(($)=>{function w(){return new u([])}$.empty=w;function X(A){return new u(A)}$.fromList=X;function G(A){return new u([new G$(A)])}$.raw=G;function E(A,D){let U=[];for(let[N,H]of A.entries()){if(N>0&&D!==void 0)U.push(D);U.push(H)}return new u(U)}$.join=E;function J(A){return new J4(A)}$.identifier=J;function W(A){return new Pw(A)}$.placeholder=W;function Y(A,D){return new a$(A,D)}$.param=Y})(K||(K={}));(($)=>{class w{constructor(X,G){this.sql=X,this.fieldAlias=G}static[I]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new w(this.sql,this.fieldAlias)}}$.Aliased=w})(u||(u={}));Pw=class Pw{constructor($){this.name=$}static[I]="Placeholder";getSQL(){return new u([this])}};R2=Symbol.for("drizzle:IsDrizzleView");E1=class E1{static[I]="View";[n0];[R2]=!0;constructor({name:$,schema:w,selectedFields:X,query:G}){this[n0]={name:$,originalName:$,schema:w,selectedFields:X,query:G,isExisting:!G,isAlias:!1}}getSQL(){return new u([this])}};V0.prototype.getSQL=function(){return new u([this])};x.prototype.getSQL=function(){return new u([this])};W$.prototype.getSQL=function(){return new u([this])}});function C5($,w,X){let G={},E=$.reduce((J,{path:W,field:Y},A)=>{let D;if(Z(Y,V0))D=Y;else if(Z(Y,u))D=Y.decoder;else D=Y.sql.decoder;let U=J;for(let[N,H]of W.entries())if(N<W.length-1){if(!(H in U))U[H]={};U=U[H]}else{let L=w[A],F=U[H]=L===null?null:D.mapFromDriverValue(L);if(X&&Z(Y,V0)&&W.length===2){let M=W[0];if(!(M in G))G[M]=F===null?jw(Y.table):!1;else if(typeof G[M]==="string"&&G[M]!==jw(Y.table))G[M]=!1}}return J},{});if(X&&Object.keys(G).length>0){for(let[J,W]of Object.entries(G))if(typeof W==="string"&&!X[W])E[J]=null}return E}function J1($,w){return Object.entries($).reduce((X,[G,E])=>{if(typeof G!=="string")return X;let J=w?[...w,G]:[G];if(Z(E,V0)||Z(E,u)||Z(E,u.Aliased))X.push({path:J,field:E});else if(Z(E,x))X.push(...J1(E[x.Symbol.Columns],J));else X.push(...J1(E,J));return X},[])}function W6($,w){let X=Object.keys($),G=Object.keys(w);if(X.length!==G.length)return!1;for(let[E,J]of X.entries())if(J!==G[E])return!1;return!0}function W4($,w){let X=Object.entries(w).filter(([,G])=>G!==void 0).map(([G,E])=>{if(Z(E,u)||Z(E,V0))return[G,E];else return[G,new a$(E,$[x.Symbol.Columns][G])]});if(X.length===0)throw Error("No values to set");return Object.fromEntries(X)}function LU($,w){for(let X of w)for(let G of Object.getOwnPropertyNames(X.prototype)){if(G==="constructor")continue;Object.defineProperty($.prototype,G,Object.getOwnPropertyDescriptor(X.prototype,G)||Object.create(null))}}function FU($){return $[x.Symbol.Columns]}function Y6($){return Z($,W$)?$._.alias:Z($,E1)?$[n0].name:Z($,u)?void 0:$[x.Symbol.IsAlias]?$[x.Symbol.Name]:$[x.Symbol.BaseName]}function m1($,w){return{name:typeof $==="string"&&$.length>0?$:"",config:typeof $==="object"?$:w}}function MU($){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 x$=B(()=>{R1();a();R$();c1();q$();Ew()});var zU,QU,v5;var BU=B(()=>{a();q$();zU=Symbol.for("drizzle:PgInlineForeignKeys"),QU=Symbol.for("drizzle:EnableRLS");v5=class v5 extends x{static[I]="PgTable";static Symbol=Object.assign({},x.Symbol,{InlineForeignKeys:zU,EnableRLS:QU});[zU]=[];[QU]=!1;[x.Symbol.ExtraConfigBuilder]=void 0;[x.Symbol.ExtraConfigColumns]={}}});var _5,KU;var VU=B(()=>{a();BU();_5=class _5{static[I]="PgPrimaryKeyBuilder";columns;name;constructor($,w){this.columns=$,this.name=w}build($){return new KU($,this.columns,this.name)}};KU=class KU{constructor($,w,X){this.table=$,this.columns=w,this.name=X}static[I]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[v5.Symbol.Name]}_${this.columns.map(($)=>$.name).join("_")}_pk`}}});function y$($,w){if(OU(w)&&!k5($)&&!Z($,a$)&&!Z($,Pw)&&!Z($,V0)&&!Z($,x)&&!Z($,E1))return new a$($,w);return $}function Y$(...$){let w=$.filter((X)=>X!==void 0);if(w.length===0)return;if(w.length===1)return new u(w);return new u([new G$("("),K.join(w,new G$(" and ")),new G$(")")])}function Y4(...$){let w=$.filter((X)=>X!==void 0);if(w.length===0)return;if(w.length===1)return new u(w);return new u([new G$("("),K.join(w,new G$(" or ")),new G$(")")])}function TU($){return K`not ${$}`}function A4($,w){if(Array.isArray(w)){if(w.length===0)return K`false`;return K`${$} in ${w.map((X)=>y$(X,$))}`}return K`${$} in ${y$(w,$)}`}function SU($,w){if(Array.isArray(w)){if(w.length===0)return K`true`;return K`${$} not in ${w.map((X)=>y$(X,$))}`}return K`${$} not in ${y$(w,$)}`}function ZU($){return K`${$} is null`}function bU($){return K`${$} is not null`}function kU($){return K`exists ${$}`}function CU($){return K`not exists ${$}`}function vU($,w,X){return K`${$} between ${y$(w,$)} and ${y$(X,$)}`}function _U($,w,X){return K`${$} not between ${y$(w,$)} and ${y$(X,$)}`}function fU($,w){return K`${$} like ${w}`}function xU($,w){return K`${$} not like ${w}`}function yU($,w){return K`${$} ilike ${w}`}function gU($,w){return K`${$} not ilike ${w}`}var S=($,w)=>{return K`${$} = ${y$(w,$)}`},RU=($,w)=>{return K`${$} <> ${y$(w,$)}`},IU=($,w)=>{return K`${$} > ${y$(w,$)}`},jU=($,w)=>{return K`${$} >= ${y$(w,$)}`},PU=($,w)=>{return K`${$} < ${y$(w,$)}`},qU=($,w)=>{return K`${$} <= ${y$(w,$)}`};var hU=B(()=>{R1();a();q$();R$()});function D4($){return K`${$} asc`}function p0($){return K`${$} desc`}var uU=B(()=>{R$()});var U4=B(()=>{hU();uU()});function mU(){return{and:Y$,between:vU,eq:S,exists:kU,gt:IU,gte:jU,ilike:yU,inArray:A4,isNull:ZU,isNotNull:bU,like:fU,lt:PU,lte:qU,ne:RU,not:TU,notBetween:_U,notExists:CU,notLike:xU,notIlike:gU,notInArray:SU,or:Y4,sql:K}}function nU(){return{sql:K,asc:D4,desc:p0}}function pU($,w){if(Object.keys($).length===1&&"default"in $&&!Z($.default,x))$=$.default;let X={},G={},E={};for(let[J,W]of Object.entries($))if(Z(W,x)){let Y=$X(W),A=G[Y];X[Y]=J,E[J]={tsName:J,dbName:W[x.Symbol.Name],schema:W[x.Symbol.Schema],columns:W[x.Symbol.Columns],relations:A?.relations??{},primaryKey:A?.primaryKey??[]};for(let U of Object.values(W[x.Symbol.Columns]))if(U.primary)E[J].primaryKey.push(U);let D=W[x.Symbol.ExtraConfigBuilder]?.(W[x.Symbol.ExtraConfigColumns]);if(D){for(let U of Object.values(D))if(Z(U,_5))E[J].primaryKey.push(...U.columns)}}else if(Z(W,cU)){let Y=$X(W.table),A=X[Y],D=W.config(w(W.table)),U;for(let[N,H]of Object.entries(D))if(A){let L=E[A];if(L.relations[N]=H,U)L.primaryKey.push(...U)}else{if(!(Y in G))G[Y]={relations:{},primaryKey:U};G[Y].relations[N]=H}}return{tables:E,tableNamesMap:X}}function T2($){return function(X,G){return new qw($,X,G,G?.fields.reduce((E,J)=>E&&J.notNull,!0)??!1)}}function I2($){return function(X,G){return new A6($,X,G)}}function rU($,w,X){if(Z(X,qw)&&X.config)return{fields:X.config.fields,references:X.config.references};let G=w[$X(X.referencedTable)];if(!G)throw Error(`Table "${X.referencedTable[x.Symbol.Name]}" not found in schema`);let E=$[G];if(!E)throw Error(`Table "${G}" not found in schema`);let J=X.sourceTable,W=w[$X(J)];if(!W)throw Error(`Table "${J[x.Symbol.Name]}" not found in schema`);let Y=[];for(let A of Object.values(E.relations))if(X.relationName&&X!==A&&A.relationName===X.relationName||!X.relationName&&A.referencedTable===X.sourceTable)Y.push(A);if(Y.length>1)throw X.relationName?Error(`There are multiple relations with name "${X.relationName}" in table "${G}"`):Error(`There are multiple relations between "${G}" and "${X.sourceTable[x.Symbol.Name]}". Please specify relation name`);if(Y[0]&&Z(Y[0],qw)&&Y[0].config)return{fields:Y[0].config.references,references:Y[0].config.fields};throw Error(`There is not enough information to infer relation "${W}.${X.fieldName}"`)}function iU($){return{one:T2($),many:I2($)}}function O4($,w,X,G,E=(J)=>J){let J={};for(let[W,Y]of G.entries())if(Y.isJson){let A=w.relations[Y.tsKey],D=X[W],U=typeof D==="string"?JSON.parse(D):D;J[Y.tsKey]=Z(A,qw)?U&&O4($,$[Y.relationTableTsKey],U,Y.selection,E):U.map((N)=>O4($,$[Y.relationTableTsKey],N,Y.selection,E))}else{let A=E(X[W]),D=Y.field,U;if(Z(D,V0))U=D;else if(Z(D,u))U=D.decoder;else U=D.sql.decoder;J[Y.tsKey]=A===null?null:U.mapFromDriverValue(A)}return J}var f5,cU,qw,A6;var D6=B(()=>{q$();R1();a();VU();U4();R$();f5=class f5{constructor($,w,X){this.sourceTable=$,this.referencedTable=w,this.relationName=X,this.referencedTableName=w[x.Symbol.Name]}static[I]="Relation";referencedTableName;fieldName};cU=class cU{constructor($,w){this.table=$,this.config=w}static[I]="Relations"};qw=class qw extends f5{constructor($,w,X,G){super($,w,X?.relationName);this.config=X,this.isNullable=G}static[I]="One";withFieldName($){let w=new qw(this.sourceTable,this.referencedTable,this.config,this.isNullable);return w.fieldName=$,w}};A6=class A6 extends f5{constructor($,w,X){super($,w,X?.relationName);this.config=X}static[I]="Many";withFieldName($){let w=new A6(this.sourceTable,this.referencedTable,this.config);return w.fieldName=$,w}}});function N4($,w){return new Proxy($,new U6(w,!1))}function n1($,w){return new Proxy($,new hX(new Proxy($.table,new U6(w,!1))))}function x5($,w){return new u.Aliased(O6($.sql,w),$.fieldAlias)}function O6($,w){return K.join($.queryChunks.map((X)=>{if(Z(X,V0))return n1(X,w);if(Z(X,u))return O6(X,w);if(Z(X,u.Aliased))return x5(X,w);return X}))}var hX,U6;var H4=B(()=>{R1();a();R$();q$();Ew();hX=class hX{constructor($){this.table=$}static[I]="ColumnAliasProxyHandler";get($,w){if(w==="table")return this.table;return $[w]}};U6=class U6{constructor($,w){this.alias=$,this.replaceOriginalName=w}static[I]="TableAliasProxyHandler";get($,w){if(w===x.Symbol.IsAlias)return!0;if(w===x.Symbol.Name)return this.alias;if(this.replaceOriginalName&&w===x.Symbol.OriginalName)return this.alias;if(w===n0)return{...$[n0],name:this.alias,isAlias:!0};if(w===x.Symbol.Columns){let G=$[x.Symbol.Columns];if(!G)return G;let E={};return Object.keys(G).map((J)=>{E[J]=new Proxy(G[J],new hX(new Proxy($,this)))}),E}let X=$[w];if(Z(X,V0))return new Proxy(X,new hX(new Proxy($,this)));return X}}});var $$;var uX=B(()=>{H4();R1();a();R$();c1();Ew();$$=class $${static[I]="SelectionProxyHandler";config;constructor($){this.config={...$}}get($,w){if(w==="_")return{...$._,selectedFields:new Proxy($._.selectedFields,this)};if(w===n0)return{...$[n0],selectedFields:new Proxy($[n0].selectedFields,this)};if(typeof w==="symbol")return $[w];let G=(Z($,W$)?$._.selectedFields:Z($,E1)?$[n0].selectedFields:$)[w];if(Z(G,u.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!G.isSelectionField)return G.sql;let E=G.clone();return E.isSelectionField=!0,E}if(Z(G,u)){if(this.config.sqlBehavior==="sql")return G;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(Z(G,V0)){if(this.config.alias)return new Proxy(G,new hX(new Proxy(G.table,new U6(this.config.alias,this.config.replaceOriginalName??!1))));return G}if(typeof G!=="object"||G===null)return G;return new Proxy(G,new $$(this.config))}}});var S$;var Jw=B(()=>{a();S$=class S${static[I]="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 y5,oU;var g5=B(()=>{a();X6();y5=class y5{static[I]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor($,w){if(this.reference=()=>{let{name:X,columns:G,foreignColumns:E}=$();return{name:X,columns:G,foreignTable:E[0].table,foreignColumns:E}},w)this._onUpdate=w.onUpdate,this._onDelete=w.onDelete}onUpdate($){return this._onUpdate=$,this}onDelete($){return this._onDelete=$,this}build($){return new oU($,this)}};oU=class oU{constructor($,w){this.table=$,this.reference=w.reference,this.onUpdate=w._onUpdate,this.onDelete=w._onDelete}static[I]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:$,columns:w,foreignColumns:X}=this.reference(),G=w.map((W)=>W.name),E=X.map((W)=>W.name),J=[this.table[s$],...G,X[0].table[s$],...E];return $??`${J.join("_")}_fk`}}});function tU($,w){return`${$[s$]}_${w.join("_")}_unique`}var h5=B(()=>{X6()});var A$,t0;var Sw=B(()=>{S5();R1();a();g5();h5();A$=class A$ extends q5{static[I]="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:X,actions:G})=>{return((E,J)=>{let W=new y5(()=>{let Y=E();return{columns:[$],foreignColumns:[Y]}});if(J.onUpdate)W.onUpdate(J.onUpdate);if(J.onDelete)W.onDelete(J.onDelete);return W.build(w)})(X,G)})}};t0=class t0 extends V0{constructor($,w){if(!w.uniqueName)w.uniqueName=tU($,[w.name]);super($,w);this.table=$}static[I]="SQLiteColumn"}});function wO($,w){let{name:X,config:G}=m1($,w);if(G?.mode==="json")return new sU(X);if(G?.mode==="bigint")return new dU(X);return new eU(X)}var dU,lU,sU,aU,eU,$O;var u5=B(()=>{a();x$();Sw();dU=class dU extends A${static[I]="SQLiteBigIntBuilder";constructor($){super($,"bigint","SQLiteBigInt")}build($){return new lU($,this.config)}};lU=class lU extends t0{static[I]="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())}};sU=class sU extends A${static[I]="SQLiteBlobJsonBuilder";constructor($){super($,"json","SQLiteBlobJson")}build($){return new aU($,this.config)}};aU=class aU extends t0{static[I]="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($))}};eU=class eU extends A${static[I]="SQLiteBlobBufferBuilder";constructor($){super($,"buffer","SQLiteBlobBuffer")}build($){return new $O($,this.config)}};$O=class $O extends t0{static[I]="SQLiteBlobBuffer";mapFromDriverValue($){if(Buffer.isBuffer($))return $;return Buffer.from($)}getSQLType(){return"blob"}}});function EO($){return(w,X)=>{let{name:G,config:E}=m1(w,X);return new XO(G,E,$)}}var XO,GO;var c5=B(()=>{a();x$();Sw();XO=class XO extends A${static[I]="SQLiteCustomColumnBuilder";constructor($,w,X){super($,"custom","SQLiteCustomColumn");this.config.fieldConfig=w,this.config.customTypeParams=X}build($){return new GO($,this.config)}};GO=class GO extends t0{static[I]="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 l($,w){let{name:X,config:G}=m1($,w);if(G?.mode==="timestamp"||G?.mode==="timestamp_ms")return new YO(X,G.mode);if(G?.mode==="boolean")return new DO(X,G.mode);return new JO(X)}var L4,F4,JO,WO,YO,AO,DO,UO;var m5=B(()=>{a();R$();x$();Sw();L4=class L4 extends A${static[I]="SQLiteBaseIntegerBuilder";constructor($,w,X){super($,w,X);this.config.autoIncrement=!1}primaryKey($){if($?.autoIncrement)this.config.autoIncrement=!0;return this.config.hasDefault=!0,super.primaryKey()}};F4=class F4 extends t0{static[I]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}};JO=class JO extends L4{static[I]="SQLiteIntegerBuilder";constructor($){super($,"number","SQLiteInteger")}build($){return new WO($,this.config)}};WO=class WO extends F4{static[I]="SQLiteInteger"};YO=class YO extends L4{static[I]="SQLiteTimestampBuilder";constructor($,w){super($,"date","SQLiteTimestamp");this.config.mode=w}defaultNow(){return this.default(K`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build($){return new AO($,this.config)}};AO=class AO extends F4{static[I]="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}};DO=class DO extends L4{static[I]="SQLiteBooleanBuilder";constructor($,w){super($,"boolean","SQLiteBoolean");this.config.mode=w}build($){return new UO($,this.config)}};UO=class UO extends F4{static[I]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue($){return Number($)===1}mapToDriverValue($){return $?1:0}}});function zO($,w){let{name:X,config:G}=m1($,w),E=G?.mode;return E==="number"?new HO(X):E==="bigint"?new FO(X):new OO(X)}var OO,NO,HO,LO,FO,MO;var n5=B(()=>{a();x$();Sw();OO=class OO extends A${static[I]="SQLiteNumericBuilder";constructor($){super($,"string","SQLiteNumeric")}build($){return new NO($,this.config)}};NO=class NO extends t0{static[I]="SQLiteNumeric";mapFromDriverValue($){if(typeof $==="string")return $;return String($)}getSQLType(){return"numeric"}};HO=class HO extends A${static[I]="SQLiteNumericNumberBuilder";constructor($){super($,"number","SQLiteNumericNumber")}build($){return new LO($,this.config)}};LO=class LO extends t0{static[I]="SQLiteNumericNumber";mapFromDriverValue($){if(typeof $==="number")return $;return Number($)}mapToDriverValue=String;getSQLType(){return"numeric"}};FO=class FO extends A${static[I]="SQLiteNumericBigIntBuilder";constructor($){super($,"bigint","SQLiteNumericBigInt")}build($){return new MO($,this.config)}};MO=class MO extends t0{static[I]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}});function KO($){return new QO($??"")}var QO,BO;var p5=B(()=>{a();Sw();QO=class QO extends A${static[I]="SQLiteRealBuilder";constructor($){super($,"number","SQLiteReal")}build($){return new BO($,this.config)}};BO=class BO extends t0{static[I]="SQLiteReal";getSQLType(){return"real"}}});function q($,w={}){let{name:X,config:G}=m1($,w);if(G.mode==="json")return new TO(X);return new VO(X,G)}var VO,RO,TO,IO;var r5=B(()=>{a();x$();Sw();VO=class VO extends A${static[I]="SQLiteTextBuilder";constructor($,w){super($,"string","SQLiteText");this.config.enumValues=w.enum,this.config.length=w.length}build($){return new RO($,this.config)}};RO=class RO extends t0{static[I]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor($,w){super($,w)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}};TO=class TO extends A${static[I]="SQLiteTextJsonBuilder";constructor($){super($,"json","SQLiteTextJson")}build($){return new IO($,this.config)}};IO=class IO extends t0{static[I]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue($){return JSON.parse($)}mapToDriverValue($){return JSON.stringify($)}}});function jO(){return{blob:wO,customType:EO,integer:l,numeric:zO,real:KO,text:q}}var PO=B(()=>{u5();c5();m5();n5();p5();r5()});function j2($,w,X,G,E=$){let J=new T$($,G,E),W=typeof w==="function"?w(jO()):w,Y=Object.fromEntries(Object.entries(W).map(([D,U])=>{let N=U;N.setName(D);let H=N.build(J);return J[i5].push(...N.buildForeignKeys(H,J)),[D,H]})),A=Object.assign(J,Y);if(A[x.Symbol.Columns]=Y,A[x.Symbol.ExtraConfigColumns]=Y,X)A[T$.Symbol.ExtraConfigBuilder]=X;return A}var i5,T$,N$=($,w,X)=>{return j2($,w,X)};var cX=B(()=>{a();q$();PO();i5=Symbol.for("drizzle:SQLiteInlineForeignKeys");T$=class T$ extends x{static[I]="SQLiteTable";static Symbol=Object.assign({},x.Symbol,{InlineForeignKeys:i5});[x.Symbol.Columns];[i5]=[];[x.Symbol.ExtraConfigBuilder]=void 0}});var M4;var qO=B(()=>{a();Jw();uX();cX();q$();x$();M4=class M4 extends S${constructor($,w,X,G){super();this.table=$,this.session=w,this.dialect=X,this.config={table:$,withList:G}}static[I]="SQLiteDelete";config;where($){return this.config.where=$,this}orderBy(...$){if(typeof $[0]==="function"){let w=$[0](new Proxy(this.config.table[x.Symbol.Columns],new $$({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),X=Array.isArray(w)?w:[w];this.config.orderBy=X}else{let w=$;this.config.orderBy=w}return this}limit($){return this.config.limit=$,this}returning($=this.table[T$.Symbol.Columns]){return this.config.returning=J1($),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 P2($){return($.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((X)=>X.toLowerCase()).join("_")}function q2($){return($.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((X,G,E)=>{let J=E===0?G.toLowerCase():`${G[0].toUpperCase()}${G.slice(1)}`;return X+J},"")}function S2($){return $}var o5;var SO=B(()=>{a();q$();o5=class o5{static[I]="CasingCache";cache={};cachedTables={};convert;constructor($){this.convert=$==="snake_case"?P2:$==="camelCase"?q2:S2}getColumnCasing($){if(!$.keyAsName)return $.name;let w=$.table[x.Symbol.Schema]??"public",X=$.table[x.Symbol.OriginalName],G=`${w}.${X}.${$.name}`;if(!this.cache[G])this.cacheTable($.table);return this.cache[G]}cacheTable($){let w=$[x.Symbol.Schema]??"public",X=$[x.Symbol.OriginalName],G=`${w}.${X}`;if(!this.cachedTables[G]){for(let E of Object.values($[x.Symbol.Columns])){let J=`${G}.${E.name}`;this.cache[J]=this.convert(E.name)}this.cachedTables[G]=!0}}clearCache(){this.cache={},this.cachedTables={}}}});var mX,t5;var z4=B(()=>{a();mX=class mX extends Error{static[I]="DrizzleError";constructor({message:$,cause:w}){super($);this.name="DrizzleError",this.cause=w}};t5=class t5 extends mX{static[I]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}});var ZO=()=>{};var bO=()=>{};var kO=B(()=>{ZO();bO()});var d5=B(()=>{U4();kO();R$()});var l5=B(()=>{u5();Sw();c5();m5();n5();p5();r5()});var wX;var Q4=B(()=>{a();R$();wX=class wX extends E1{static[I]="SQLiteViewBase"}});var N6,H6;var B4=B(()=>{H4();SO();R1();a();z4();D6();d5();R$();l5();cX();c1();q$();x$();Ew();Q4();N6=class N6{static[I]="SQLiteDialect";casing;constructor($){this.casing=new o5($?.casing)}escapeName($){return`"${$}"`}escapeParam($){return"?"}escapeString($){return`'${$.replace(/'/g,"''")}'`}buildWithCTE($){if(!$?.length)return;let w=[K`with `];for(let[X,G]of $.entries())if(w.push(K`${K.identifier(G._.alias)} as (${G._.sql})`),X<$.length-1)w.push(K`, `);return w.push(K` `),K.join(w)}buildDeleteQuery({table:$,where:w,returning:X,withList:G,limit:E,orderBy:J}){let W=this.buildWithCTE(G),Y=X?K` returning ${this.buildSelection(X,{isSingleTable:!0})}`:void 0,A=w?K` where ${w}`:void 0,D=this.buildOrderBy(J),U=this.buildLimit(E);return K`${W}delete from ${$}${A}${Y}${D}${U}`}buildUpdateSet($,w){let X=$[x.Symbol.Columns],G=Object.keys(X).filter((J)=>w[J]!==void 0||X[J]?.onUpdateFn!==void 0),E=G.length;return K.join(G.flatMap((J,W)=>{let Y=X[J],A=w[J]??K.param(Y.onUpdateFn(),Y),D=K`${K.identifier(this.casing.getColumnCasing(Y))} = ${A}`;if(W<E-1)return[D,K.raw(", ")];return[D]}))}buildUpdateQuery({table:$,set:w,where:X,returning:G,withList:E,joins:J,from:W,limit:Y,orderBy:A}){let D=this.buildWithCTE(E),U=this.buildUpdateSet($,w),N=W&&K.join([K.raw(" from "),this.buildFromTable(W)]),H=this.buildJoins(J),L=G?K` returning ${this.buildSelection(G,{isSingleTable:!0})}`:void 0,F=X?K` where ${X}`:void 0,M=this.buildOrderBy(A),z=this.buildLimit(Y);return K`${D}update ${$} set ${U}${N}${H}${F}${L}${M}${z}`}buildSelection($,{isSingleTable:w=!1}={}){let X=$.length,G=$.flatMap(({field:E},J)=>{let W=[];if(Z(E,u.Aliased)&&E.isSelectionField)W.push(K.identifier(E.fieldAlias));else if(Z(E,u.Aliased)||Z(E,u)){let Y=Z(E,u.Aliased)?E.sql:E;if(w)W.push(new u(Y.queryChunks.map((A)=>{if(Z(A,V0))return K.identifier(this.casing.getColumnCasing(A));return A})));else W.push(Y);if(Z(E,u.Aliased))W.push(K` as ${K.identifier(E.fieldAlias)}`)}else if(Z(E,V0)){let Y=E.table[x.Symbol.Name];if(E.columnType==="SQLiteNumericBigInt")if(w)W.push(K`cast(${K.identifier(this.casing.getColumnCasing(E))} as text)`);else W.push(K`cast(${K.identifier(Y)}.${K.identifier(this.casing.getColumnCasing(E))} as text)`);else if(w)W.push(K.identifier(this.casing.getColumnCasing(E)));else W.push(K`${K.identifier(Y)}.${K.identifier(this.casing.getColumnCasing(E))}`)}if(J<X-1)W.push(K`, `);return W});return K.join(G)}buildJoins($){if(!$||$.length===0)return;let w=[];if($)for(let[X,G]of $.entries()){if(X===0)w.push(K` `);let E=G.table;if(Z(E,T$)){let J=E[T$.Symbol.Name],W=E[T$.Symbol.Schema],Y=E[T$.Symbol.OriginalName],A=J===Y?void 0:G.alias;w.push(K`${K.raw(G.joinType)} join ${W?K`${K.identifier(W)}.`:void 0}${K.identifier(Y)}${A&&K` ${K.identifier(A)}`} on ${G.on}`)}else w.push(K`${K.raw(G.joinType)} join ${E} on ${G.on}`);if(X<$.length-1)w.push(K` `)}return K.join(w)}buildLimit($){return typeof $==="object"||typeof $==="number"&&$>=0?K` limit ${$}`:void 0}buildOrderBy($){let w=[];if($){for(let[X,G]of $.entries())if(w.push(G),X<$.length-1)w.push(K`, `)}return w.length>0?K` order by ${K.join(w)}`:void 0}buildFromTable($){if(Z($,x)&&$[x.Symbol.IsAlias])return K`${K`${K.identifier($[x.Symbol.Schema]??"")}.`.if($[x.Symbol.Schema])}${K.identifier($[x.Symbol.OriginalName])} ${K.identifier($[x.Symbol.Name])}`;return $}buildSelectQuery({withList:$,fields:w,fieldsFlat:X,where:G,having:E,table:J,joins:W,orderBy:Y,groupBy:A,limit:D,offset:U,distinct:N,setOperators:H}){let L=X??J1(w);for(let K0 of L)if(Z(K0.field,V0)&&jw(K0.field.table)!==(Z(J,W$)?J._.alias:Z(J,wX)?J[n0].name:Z(J,u)?void 0:jw(J))&&!((J$)=>W?.some(({alias:G1})=>G1===(J$[x.Symbol.IsAlias]?jw(J$):J$[x.Symbol.BaseName])))(K0.field.table)){let J$=jw(K0.field.table);throw Error(`Your "${K0.path.join("->")}" field references a column "${J$}"."${K0.field.name}", but the table "${J$}" is not part of the query! Did you forget to join it?`)}let F=!W||W.length===0,M=this.buildWithCTE($),z=N?K` distinct`:void 0,Q=this.buildSelection(L,{isSingleTable:F}),R=this.buildFromTable(J),T=this.buildJoins(W),v=G?K` where ${G}`:void 0,f=E?K` having ${E}`:void 0,k=[];if(A){for(let[K0,J$]of A.entries())if(k.push(J$),K0<A.length-1)k.push(K`, `)}let m=k.length>0?K` group by ${K.join(k)}`:void 0,F0=this.buildOrderBy(Y),b0=this.buildLimit(D),f0=U?K` offset ${U}`:void 0,c0=K`${M}select${z} ${Q} from ${R}${T}${v}${m}${f}${F0}${b0}${f0}`;if(H.length>0)return this.buildSetOperations(c0,H);return c0}buildSetOperations($,w){let[X,...G]=w;if(!X)throw Error("Cannot pass undefined values to any set operator");if(G.length===0)return this.buildSetOperationQuery({leftSelect:$,setOperator:X});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:$,setOperator:X}),G)}buildSetOperationQuery({leftSelect:$,setOperator:{type:w,isAll:X,rightSelect:G,limit:E,orderBy:J,offset:W}}){let Y=K`${$.getSQL()} `,A=K`${G.getSQL()}`,D;if(J&&J.length>0){let L=[];for(let F of J)if(Z(F,t0))L.push(K.identifier(F.name));else if(Z(F,u)){for(let M=0;M<F.queryChunks.length;M++){let z=F.queryChunks[M];if(Z(z,t0))F.queryChunks[M]=K.identifier(this.casing.getColumnCasing(z))}L.push(K`${F}`)}else L.push(K`${F}`);D=K` order by ${K.join(L,K`, `)}`}let U=typeof E==="object"||typeof E==="number"&&E>=0?K` limit ${E}`:void 0,N=K.raw(`${w} ${X?"all ":""}`),H=W?K` offset ${W}`:void 0;return K`${Y}${N}${A}${D}${U}${H}`}buildInsertQuery({table:$,values:w,onConflict:X,returning:G,withList:E,select:J}){let W=[],Y=$[x.Symbol.Columns],A=Object.entries(Y).filter(([F,M])=>!M.shouldDisableInsert()),D=A.map(([,F])=>K.identifier(this.casing.getColumnCasing(F)));if(J){let F=w;if(Z(F,u))W.push(F);else W.push(F.getSQL())}else{let F=w;W.push(K.raw("values "));for(let[M,z]of F.entries()){let Q=[];for(let[R,T]of A){let v=z[R];if(v===void 0||Z(v,a$)&&v.value===void 0){let f;if(T.default!==null&&T.default!==void 0)f=Z(T.default,u)?T.default:K.param(T.default,T);else if(T.defaultFn!==void 0){let k=T.defaultFn();f=Z(k,u)?k:K.param(k,T)}else if(!T.default&&T.onUpdateFn!==void 0){let k=T.onUpdateFn();f=Z(k,u)?k:K.param(k,T)}else f=K`null`;Q.push(f)}else Q.push(v)}if(W.push(Q),M<F.length-1)W.push(K`, `)}}let U=this.buildWithCTE(E),N=K.join(W),H=G?K` returning ${this.buildSelection(G,{isSingleTable:!0})}`:void 0,L=X?.length?K.join(X):void 0;return K`${U}insert into ${$} ${D} ${N}${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:X,table:G,tableConfig:E,queryConfig:J,tableAlias:W,nestedQueryRelation:Y,joinOn:A}){let D=[],U,N,H=[],L,F=[];if(J===!0)D=Object.entries(E.columns).map(([Q,R])=>({dbKey:R.name,tsKey:Q,field:n1(R,W),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let z=Object.fromEntries(Object.entries(E.columns).map(([k,m])=>[k,n1(m,W)]));if(J.where){let k=typeof J.where==="function"?J.where(z,mU()):J.where;L=k&&O6(k,W)}let Q=[],R=[];if(J.columns){let k=!1;for(let[m,F0]of Object.entries(J.columns)){if(F0===void 0)continue;if(m in E.columns){if(!k&&F0===!0)k=!0;R.push(m)}}if(R.length>0)R=k?R.filter((m)=>J.columns?.[m]===!0):Object.keys(E.columns).filter((m)=>!R.includes(m))}else R=Object.keys(E.columns);for(let k of R){let m=E.columns[k];Q.push({tsKey:k,value:m})}let T=[];if(J.with)T=Object.entries(J.with).filter((k)=>!!k[1]).map(([k,m])=>({tsKey:k,queryConfig:m,relation:E.relations[k]}));let v;if(J.extras){v=typeof J.extras==="function"?J.extras(z,{sql:K}):J.extras;for(let[k,m]of Object.entries(v))Q.push({tsKey:k,value:x5(m,W)})}for(let{tsKey:k,value:m}of Q)D.push({dbKey:Z(m,u.Aliased)?m.fieldAlias:E.columns[k].name,tsKey:k,field:Z(m,V0)?n1(m,W):m,relationTableTsKey:void 0,isJson:!1,selection:[]});let f=typeof J.orderBy==="function"?J.orderBy(z,nU()):J.orderBy??[];if(!Array.isArray(f))f=[f];H=f.map((k)=>{if(Z(k,V0))return n1(k,W);return O6(k,W)}),U=J.limit,N=J.offset;for(let{tsKey:k,queryConfig:m,relation:F0}of T){let b0=rU(w,X,F0),f0=$X(F0.referencedTable),c0=X[f0],K0=`${W}_${k}`,J$=Y$(...b0.fields.map((dI,lI)=>S(n1(b0.references[lI],K0),n1(dI,W)))),G1=this.buildRelationalQuery({fullSchema:$,schema:w,tableNamesMap:X,table:$[c0],tableConfig:w[c0],queryConfig:Z(F0,qw)?m===!0?{limit:1}:{...m,limit:1}:m,tableAlias:K0,joinOn:J$,nestedQueryRelation:F0}),tI=K`(${G1.sql})`.as(k);D.push({dbKey:k,tsKey:k,field:tI,relationTableTsKey:c0,isJson:!0,selection:G1.selection})}}if(D.length===0)throw new mX({message:`No fields selected for table "${E.tsName}" ("${W}"). 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 M;if(L=Y$(A,L),Y){let z=K`json_array(${K.join(D.map(({field:T})=>Z(T,t0)?K.identifier(this.casing.getColumnCasing(T)):Z(T,u.Aliased)?T.sql:T),K`, `)})`;if(Z(Y,A6))z=K`coalesce(json_group_array(${z}), json_array())`;let Q=[{dbKey:"data",tsKey:"data",field:z.as("data"),isJson:!0,relationTableTsKey:E.tsName,selection:D}];if(U!==void 0||N!==void 0||H.length>0)M=this.buildSelectQuery({table:N4(G,W),fields:{},fieldsFlat:[{path:[],field:K.raw("*")}],where:L,limit:U,offset:N,orderBy:H,setOperators:[]}),L=void 0,U=void 0,N=void 0,H=void 0;else M=N4(G,W);M=this.buildSelectQuery({table:Z(M,T$)?M:new W$(M,{},W),fields:{},fieldsFlat:Q.map(({field:T})=>({path:[],field:Z(T,V0)?n1(T,W):T})),joins:F,where:L,limit:U,offset:N,orderBy:H,setOperators:[]})}else M=this.buildSelectQuery({table:N4(G,W),fields:{},fieldsFlat:D.map(({field:z})=>({path:[],field:Z(z,V0)?n1(z,W):z})),joins:F,where:L,limit:U,offset:N,orderBy:H,setOperators:[]});return{tableTsKey:E.tsName,sql:M,selection:D}}};H6=class H6 extends N6{static[I]="SQLiteSyncDialect";migrate($,w,X){let G=X===void 0?"__drizzle_migrations":typeof X==="string"?"__drizzle_migrations":X.migrationsTable??"__drizzle_migrations",E=K`
|
|
30
|
-
CREATE TABLE IF NOT EXISTS ${
|
|
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 Iq(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=XU($,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=XU($,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 Tq(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
|
+
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`
|
|
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(E);let W=w.values(K`SELECT id, hash, created_at FROM ${K.identifier(G)} ORDER BY created_at DESC LIMIT 1`)[0]??void 0;w.run(K`BEGIN`);try{for(let Y of $)if(!W||Number(W[2])<Y.folderMillis){for(let A of Y.sql)w.run(K.raw(A));w.run(K`INSERT INTO ${K.identifier(G)} ("hash", "created_at") VALUES(${Y.hash}, ${Y.folderMillis})`)}w.run(K`COMMIT`)}catch(Y){throw w.run(K`ROLLBACK`),Y}}}});var s5;var CO=B(()=>{a();s5=class s5{static[I]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}});function K4($,w){return(X,G,...E)=>{let J=[G,...E].map((W)=>({type:$,isAll:w,rightSelect:W}));for(let W of J)if(!W6(X.getSelectedFields(),W.rightSelect.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return X.addSetOperators(J)}}var T1,vO,a5,Z2=()=>({union:b2,unionAll:k2,intersect:C2,except:v2}),b2,k2,C2,v2;var e5=B(()=>{a();CO();Jw();uX();R$();c1();q$();x$();Ew();Q4();T1=class T1{static[I]="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,X;if(this.fields)X=this.fields;else if(Z($,W$))X=Object.fromEntries(Object.keys($._.selectedFields).map((G)=>[G,$[G]]));else if(Z($,wX))X=$[n0].selectedFields;else if(Z($,u))X={};else X=FU($);return new a5({table:$,fields:X,isPartialSelect:w,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}};vO=class vO extends s5{static[I]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:$,fields:w,isPartialSelect:X,session:G,dialect:E,withList:J,distinct:W}){super();this.config={withList:J,table:$,fields:{...w},distinct:W,setOperators:[]},this.isPartialSelect=X,this.session=G,this.dialect=E,this._={selectedFields:w},this.tableName=Y6($),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin($){return(w,X)=>{let G=this.tableName,E=Y6(w);if(typeof E==="string"&&this.config.joins?.some((J)=>J.alias===E))throw Error(`Alias "${E}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof G==="string")this.config.fields={[G]:this.config.fields};if(typeof E==="string"&&!Z(w,u)){let J=Z(w,W$)?w._.selectedFields:Z(w,E1)?w[n0].selectedFields:w[x.Symbol.Columns];this.config.fields[E]=J}}if(typeof X==="function")X=X(new Proxy(this.config.fields,new $$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:X,table:w,joinType:$,alias:E}),typeof E==="string")switch($){case"left":{this.joinsNotNullableMap[E]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[E]=!0;break}case"inner":{this.joinsNotNullableMap[E]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[E]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");createSetOperator($,w){return(X)=>{let G=typeof X==="function"?X(Z2()):X;if(!W6(this.getSelectedFields(),G.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:G}),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 $$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=$,this}having($){if(typeof $==="function")$=$(new Proxy(this.config.fields,new $$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=$,this}groupBy(...$){if(typeof $[0]==="function"){let w=$[0](new Proxy(this.config.fields,new $$({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 $$({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),X=Array.isArray(w)?w:[w];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=X;else this.config.orderBy=X}else{let w=$;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=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 W$(this.getSQL(),this.config.fields,$),new $$({alias:$,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new $$({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}};a5=class a5 extends vO{static[I]="SQLiteSelect";_prepare($=!0){if(!this.session)throw Error("Cannot execute a query on a query builder. Please use a database instance instead.");let w=J1(this.config.fields),X=this.session[$?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),w,"all",!0);return X.joinsNotNullableMap=this.joinsNotNullableMap,X}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()}};LU(a5,[S$]);b2=K4("union",!1),k2=K4("union",!0),C2=K4("intersect",!1),v2=K4("except",!1)});var L6;var $9=B(()=>{a();uX();B4();c1();e5();L6=class L6{static[I]="SQLiteQueryBuilder";dialect;dialectConfig;constructor($){this.dialect=Z($,N6)?$:void 0,this.dialectConfig=Z($,N6)?void 0:$}$with=($,w)=>{let X=this;return{as:(E)=>{if(typeof E==="function")E=E(X);return new Proxy(new E6(E.getSQL(),w??("getSelectedFields"in E?E.getSelectedFields()??{}:{}),$,!0),new $$({alias:$,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...$){let w=this;function X(E){return new T1({fields:E??void 0,session:void 0,dialect:w.getDialect(),withList:$})}function G(E){return new T1({fields:E??void 0,session:void 0,dialect:w.getDialect(),withList:$,distinct:!0})}return{select:X,selectDistinct:G}}select($){return new T1({fields:$??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct($){return new T1({fields:$??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new H6(this.dialectConfig);return this.dialect}}});var V4,w9;var _O=B(()=>{a();Jw();R$();cX();q$();x$();$9();V4=class V4{constructor($,w,X,G){this.table=$,this.session=w,this.dialect=X,this.withList=G}static[I]="SQLiteInsertBuilder";values($){if($=Array.isArray($)?$:[$],$.length===0)throw Error("values() must be called with at least one value");let w=$.map((X)=>{let G={},E=this.table[x.Symbol.Columns];for(let J of Object.keys(X)){let W=X[J];G[J]=Z(W,u)?W:new a$(W,E[J])}return G});return new w9(this.table,w,this.session,this.dialect,this.withList)}select($){let w=typeof $==="function"?$(new L6):$;if(!Z(w,u)&&!W6(this.table[G4],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 w9(this.table,w,this.session,this.dialect,this.withList,!0)}};w9=class w9 extends S${constructor($,w,X,G,E,J){super();this.session=X,this.dialect=G,this.config={table:$,values:w,withList:E,select:J}}static[I]="SQLiteInsert";config;returning($=this.config.table[T$.Symbol.Columns]){return this.config.returning=J1($),this}onConflictDoNothing($={}){if(!this.config.onConflict)this.config.onConflict=[];if($.target===void 0)this.config.onConflict.push(K` on conflict do nothing`);else{let w=Array.isArray($.target)?K`${$.target}`:K`${[$.target]}`,X=$.where?K` where ${$.where}`:K``;this.config.onConflict.push(K` on conflict ${w} do nothing${X}`)}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?K` where ${$.where}`:void 0,X=$.targetWhere?K` where ${$.targetWhere}`:void 0,G=$.setWhere?K` where ${$.setWhere}`:void 0,E=Array.isArray($.target)?K`${$.target}`:K`${[$.target]}`,J=this.dialect.buildUpdateSet(this.config.table,W4(this.config.table,$.set));return this.config.onConflict.push(K` on conflict ${E}${X} do update set ${J}${w}${G}`),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 R4,fO;var xO=B(()=>{a();Jw();uX();cX();c1();q$();x$();Ew();Q4();R4=class R4{constructor($,w,X,G){this.table=$,this.session=w,this.dialect=X,this.withList=G}static[I]="SQLiteUpdateBuilder";set($){return new fO(this.table,W4(this.table,$),this.session,this.dialect,this.withList)}};fO=class fO extends S${constructor($,w,X,G,E){super();this.session=X,this.dialect=G,this.config={set:w,table:$,withList:E,joins:[]}}static[I]="SQLiteUpdate";config;from($){return this.config.from=$,this}createJoin($){return(w,X)=>{let G=Y6(w);if(typeof G==="string"&&this.config.joins.some((E)=>E.alias===G))throw Error(`Alias "${G}" is already used in this query`);if(typeof X==="function"){let E=this.config.from?Z(w,T$)?w[x.Symbol.Columns]:Z(w,W$)?w._.selectedFields:Z(w,wX)?w[n0].selectedFields:void 0:void 0;X=X(new Proxy(this.config.table[x.Symbol.Columns],new $$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),E&&new Proxy(E,new $$({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:X,table:w,joinType:$,alias:G}),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[x.Symbol.Columns],new $$({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),X=Array.isArray(w)?w:[w];this.config.orderBy=X}else{let w=$;this.config.orderBy=w}return this}limit($){return this.config.limit=$,this}returning($=this.config.table[T$.Symbol.Columns]){return this.config.returning=J1($),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 X9=B(()=>{qO();_O();$9();e5();xO()});var F6;var yO=B(()=>{a();R$();F6=class F6 extends u{constructor($){super(F6.buildEmbeddedCount($.source,$.filters).queryChunks);this.params=$,this.session=$.session,this.sql=F6.buildCount($.source,$.filters)}sql;static[I]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount($,w){return K`(select count(*) from ${$}${K.raw(" where ").if(w)}${w})`}static buildCount($,w){return K`select count(*) from ${$}${K.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 E9,T4,G9;var gO=B(()=>{a();Jw();D6();E9=class E9{constructor($,w,X,G,E,J,W,Y){this.mode=$,this.fullSchema=w,this.schema=X,this.tableNamesMap=G,this.table=E,this.tableConfig=J,this.dialect=W,this.session=Y}static[I]="SQLiteAsyncRelationalQueryBuilder";findMany($){return this.mode==="sync"?new G9(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,$?$:{},"many"):new T4(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,$?$:{},"many")}findFirst($){return this.mode==="sync"?new G9(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,$?{...$,limit:1}:{limit:1},"first"):new T4(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,$?{...$,limit:1}:{limit:1},"first")}};T4=class T4 extends S${constructor($,w,X,G,E,J,W,Y,A){super();this.fullSchema=$,this.schema=w,this.tableNamesMap=X,this.table=G,this.tableConfig=E,this.dialect=J,this.session=W,this.config=Y,this.mode=A}static[I]="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:X}=this._toSQL();return this.session[$?"prepareOneTimeQuery":"prepareQuery"](X,void 0,this.mode==="first"?"get":"all",!0,(G,E)=>{let J=G.map((W)=>O4(this.schema,this.tableConfig,W,w.selection,E));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()}};G9=class G9 extends T4{static[I]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}});var nX;var hO=B(()=>{a();Jw();nX=class nX extends S${constructor($,w,X,G,E){super();this.execute=$,this.getSQL=w,this.dialect=G,this.mapBatchResult=E,this.config={action:X}}static[I]="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 M6;var I4=B(()=>{a();uX();R$();X9();c1();yO();gO();hO();M6=class M6{constructor($,w,X,G){this.resultKind=$,this.dialect=w,this.session=X,this._=G?{schema:G.schema,fullSchema:G.fullSchema,tableNamesMap:G.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let E=this.query;if(this._.schema)for(let[J,W]of Object.entries(this._.schema))E[J]=new E9($,G.fullSchema,this._.schema,this._.tableNamesMap,G.fullSchema[J],W,w,X)}static[I]="BaseSQLiteDatabase";query;$with=($,w)=>{let X=this;return{as:(E)=>{if(typeof E==="function")E=E(new L6(X.dialect));return new Proxy(new E6(E.getSQL(),w??("getSelectedFields"in E?E.getSelectedFields()??{}:{}),$,!0),new $$({alias:$,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count($,w){return new F6({source:$,filters:w,session:this.session})}with(...$){let w=this;function X(Y){return new T1({fields:Y??void 0,session:w.session,dialect:w.dialect,withList:$})}function G(Y){return new T1({fields:Y??void 0,session:w.session,dialect:w.dialect,withList:$,distinct:!0})}function E(Y){return new R4(Y,w.session,w.dialect,$)}function J(Y){return new V4(Y,w.session,w.dialect,$)}function W(Y){return new M4(Y,w.session,w.dialect,$)}return{select:X,selectDistinct:G,update:E,insert:J,delete:W}}select($){return new T1({fields:$??void 0,session:this.session,dialect:this.dialect})}selectDistinct($){return new T1({fields:$??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update($){return new R4($,this.session,this.dialect)}insert($){return new V4($,this.session,this.dialect)}delete($){return new M4($,this.session,this.dialect)}run($){let w=typeof $==="string"?K.raw($):$.getSQL();if(this.resultKind==="async")return new nX(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"?K.raw($):$.getSQL();if(this.resultKind==="async")return new nX(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"?K.raw($):$.getSQL();if(this.resultKind==="async")return new nX(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"?K.raw($):$.getSQL();if(this.resultKind==="async")return new nX(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 uO=()=>{};var cO=()=>{};function XX($){return new J9($,!1)}function j4($){return new J9($,!0)}var J9,mO,nO;var pO=B(()=>{a();J9=class J9{constructor($,w){this.name=$,this.unique=w}static[I]="SQLiteIndexBuilderOn";on(...$){return new mO(this.name,$,this.unique)}};mO=class mO{static[I]="SQLiteIndexBuilder";config;constructor($,w,X){this.config={name:$,columns:w,unique:X,where:void 0}}where($){return this.config.where=$,this}build($){return new nO(this.config,$)}};nO=class nO{static[I]="SQLiteIndex";config;constructor($,w){this.config={...$,table:w}}}});var rO=()=>{};var iO,W9,Y9,A9;var D9=B(()=>{a();z4();Jw();I4();iO=class iO extends S${constructor($){super();this.resultCb=$}static[I]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}};W9=class W9{constructor($,w,X){this.mode=$,this.executeMethod=w,this.query=X}static[I]="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 iO(()=>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)}}};Y9=class Y9{constructor($){this.dialect=$}static[I]="SQLiteSession";prepareOneTimeQuery($,w,X,G){return this.prepareQuery($,w,X,G)}run($){let w=this.dialect.sqlToQuery($);try{return this.prepareOneTimeQuery(w,void 0,"run",!1).run()}catch(X){throw new mX({cause:X,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")}};A9=class A9 extends M6{constructor($,w,X,G,E=0){super($,w,X,G);this.schema=G,this.nestedIndex=E}static[I]="SQLiteTransaction";rollback(){throw new t5}}});var oO=()=>{};var tO=()=>{};var U9=B(()=>{uO();cO();l5();I4();B4();g5();pO();rO();X9();D9();cX();h5();oO();tO()});var O9,N9,dO;var H9=B(()=>{a();w4();R$();U9();D9();x$();O9=class O9 extends Y9{constructor($,w,X,G={}){super(w);this.client=$,this.schema=X,this.logger=G.logger??new I5}static[I]="SQLiteBunSession";logger;exec($){this.client.exec($)}prepareQuery($,w,X,G,E){let J=this.client.prepare($.sql);return new dO(J,$,this.logger,w,X,G,E)}transaction($,w={}){let X=new N9("sync",this.dialect,this,this.schema),G;return this.client.transaction(()=>{G=$(X)})[w.behavior??"deferred"](),G}};N9=class N9 extends A9{static[I]="SQLiteBunTransaction";transaction($){let w=`sp${this.nestedIndex}`,X=new N9("sync",this.dialect,this.session,this.schema,this.nestedIndex+1);this.session.run(K.raw(`savepoint ${w}`));try{let G=$(X);return this.session.run(K.raw(`release savepoint ${w}`)),G}catch(G){throw this.session.run(K.raw(`rollback to savepoint ${w}`)),G}}};dO=class dO extends W9{constructor($,w,X,G,E,J,W){super("sync",E,w);this.stmt=$,this.logger=X,this.fields=G,this._isResponseInArrayMode=J,this.customResultMapper=W}static[I]="SQLiteBunPreparedQuery";run($){let w=J6(this.query.params,$??{});return this.logger.logQuery(this.query.sql,w),this.stmt.run(...w)}all($){let{fields:w,query:X,logger:G,joinsNotNullableMap:E,stmt:J,customResultMapper:W}=this;if(!w&&!W){let A=J6(X.params,$??{});return G.logQuery(X.sql,A),J.all(...A)}let Y=this.values($);if(W)return W(Y);return Y.map((A)=>C5(w,A,E))}get($){let w=J6(this.query.params,$??{});this.logger.logQuery(this.query.sql,w);let X=this.stmt.values(...w)[0];if(!X)return;let{fields:G,joinsNotNullableMap:E,customResultMapper:J}=this;if(!G&&!J)return X;if(J)return J([X]);return C5(G,X,E)}values($){let w=J6(this.query.params,$??{});return this.logger.logQuery(this.query.sql,w),this.stmt.values(...w)}isResponseInArrayMode(){return this._isResponseInArrayMode}}});import{Database as P4}from"bun:sqlite";function pX($,w={}){let X=new H6({casing:w.casing}),G;if(w.logger===!0)G=new T5;else if(w.logger!==!1)G=w.logger;let E;if(w.schema){let Y=pU(w.schema,iU);E={fullSchema:w.schema,schema:Y.tables,tableNamesMap:Y.tableNamesMap}}let J=new O9($,X,E,{logger:G}),W=new lO("sync",X,J,E);return W.$client=$,W}function q4(...$){if($[0]===void 0||typeof $[0]==="string"){let w=$[0]===void 0?new P4:new P4($[0]);return pX(w,$[1])}if(MU($[0])){let{connection:w,client:X,...G}=$[0];if(X)return pX(X,G);if(typeof w==="object"){let{source:J,...W}=w,Y=Object.values(W).filter((D)=>D!==void 0).length?W:void 0,A=new P4(J,Y);return pX(A,G)}let E=new P4(w);return pX(E,G)}return pX($[0],$[1])}var lO;var sO=B(()=>{a();w4();D6();I4();B4();x$();H9();lO=class lO extends M6{static[I]="BunSQLiteDatabase"};(($)=>{function w(X){return pX({},X)}$.mock=w})(q4||(q4={}))});var aO=B(()=>{sO();H9()});var eO=B(()=>{U4()});var g$=B(()=>{H4();S5();R1();a();z4();eO();w4();Jw();D6();d5();c1();q$();x$();Ew()});var F9={};e1(F9,{webhooks:()=>_2,tasks:()=>r,task_notes:()=>e$,task_links:()=>I1,sessions:()=>j1,prompts:()=>w$,prompt_history:()=>Q6,projects:()=>Z$,memories:()=>h$,jobs:()=>d0,job_runs:()=>l0,job_run_logs:()=>Zw,gateway_sessions:()=>b$,bridge_permissions:()=>rX,bridge_messages:()=>L9,bridge_chats:()=>s0});var z6,Z$,r,e$,I1,h$,w$,Q6,d0,l0,Zw,j1,s0,L9,rX,b$,_2;var u$=B(()=>{g$();U9();z6={created_at:l("created_at",{mode:"timestamp"}).notNull().default(K`(unixepoch())`),updated_at:l("updated_at",{mode:"timestamp"}).notNull().default(K`(unixepoch())`)},Z$=N$("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"),...z6}),r=N$("tasks",{id:q("id").primaryKey(),project_id:q("project_id").references(()=>Z$.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:l("progress").default(0).notNull(),due_at:l("due_at",{mode:"timestamp"}),tags:q("tags",{mode:"json"}).$type(),author:q("author").default("human").notNull(),claimed_by:q("claimed_by"),claim_expires_at:l("claim_expires_at",{mode:"timestamp"}),...z6}),e$=N$("task_notes",{id:q("id").primaryKey(),task_id:q("task_id").notNull().references(()=>r.id,{onDelete:"cascade"}),content:q("content").notNull(),author:q("author").default("human").notNull(),created_at:l("created_at",{mode:"timestamp"}).notNull().default(K`(unixepoch())`)}),I1=N$("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:l("created_at",{mode:"timestamp"}).notNull().default(K`(unixepoch())`)},($)=>[XX("task_links_from_idx").on($.from_task_id),XX("task_links_to_idx").on($.to_task_id)]),h$=N$("memories",{id:q("id").primaryKey(),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:l("expires_at",{mode:"timestamp"}),...z6}),w$=N$("prompts",{id:q("id").primaryKey(),name:q("name").notNull(),description:q("description"),template:q("template").notNull(),is_skill:l("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:l("version").default(1).notNull(),pinned:l("pinned",{mode:"boolean"}).default(!1).notNull(),last_used_at:l("last_used_at",{mode:"timestamp"}),...z6},($)=>[j4("prompts_name_idx").on($.name)]),Q6=N$("prompt_history",{id:q("id").primaryKey(),prompt_id:q("prompt_id").notNull().references(()=>w$.id,{onDelete:"cascade"}),version:l("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:l("changed_at",{mode:"timestamp"}).notNull().default(K`(unixepoch())`)},($)=>[XX("prompt_history_prompt_id_idx").on($.prompt_id,$.version)]),d0=N$("jobs",{id:q("id").primaryKey(),name:q("name").notNull(),description:q("description"),command:q("command").notNull(),prompt_id:q("prompt_id").references(()=>w$.id),prompt_vars:q("prompt_vars",{mode:"json"}).$type(),inject_context:l("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:l("run_at",{mode:"timestamp"}),timeout_secs:l("timeout_secs").default(300).notNull(),max_retries:l("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:l("os_installed",{mode:"boolean"}).default(!1).notNull(),enabled:l("enabled",{mode:"boolean"}).default(!0).notNull(),last_run_at:l("last_run_at",{mode:"timestamp"}),next_run_at:l("next_run_at",{mode:"timestamp"}),run_count:l("run_count").default(0).notNull(),...z6},($)=>[j4("jobs_name_idx").on($.name)]),l0=N$("job_runs",{id:q("id").primaryKey(),job_id:q("job_id").notNull().references(()=>d0.id,{onDelete:"cascade"}),status:q("status",{enum:["pending","running","success","failed","cancelled","skipped"]}).notNull(),trigger_by:q("trigger_by"),started_at:l("started_at",{mode:"timestamp"}),ended_at:l("ended_at",{mode:"timestamp"}),exit_code:l("exit_code"),stdout:q("stdout"),stderr:q("stderr"),error_msg:q("error_msg"),retry_num:l("retry_num").default(0).notNull(),created_at:l("created_at",{mode:"timestamp"}).notNull().default(K`(unixepoch())`)},($)=>[XX("job_runs_job_id_idx").on($.job_id)]),Zw=N$("job_run_logs",{id:l("id",{mode:"number"}).primaryKey({autoIncrement:!0}),run_id:q("run_id").notNull().references(()=>l0.id,{onDelete:"cascade"}),ts:l("ts",{mode:"timestamp"}).notNull(),stream:q("stream",{enum:["stdout","stderr"]}).notNull(),line:q("line").notNull()},($)=>[XX("job_run_logs_run_id_idx").on($.run_id,$.ts)]),j1=N$("sessions",{id:q("id").primaryKey(),agent:q("agent").notNull(),agent_version:q("agent_version"),project_id:q("project_id").references(()=>Z$.id),job_run_id:q("job_run_id").references(()=>l0.id),summary:q("summary"),events:q("events",{mode:"json"}).$type(),snapshot:q("snapshot"),tokens_used:l("tokens_used"),created_at:l("created_at",{mode:"timestamp"}).notNull().default(K`(unixepoch())`)}),s0=N$("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:l("authorized",{mode:"boolean"}).default(!1).notNull(),session_id:q("session_id"),thread_id:q("thread_id"),working_dir:q("working_dir"),updated_at:l("updated_at",{mode:"timestamp"}).notNull().default(K`(unixepoch())`),created_at:l("created_at",{mode:"timestamp"}).notNull().default(K`(unixepoch())`)},($)=>[j4("bridge_chats_platform_chat_idx").on($.platform,$.chat_id)]),L9=N$("bridge_messages",{id:q("id").primaryKey(),chat_id:q("chat_id").references(()=>s0.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(()=>l0.id),gateway_session_id:q("gateway_session_id").references(()=>b$.id),platform_msg_id:q("platform_msg_id"),thread_id:q("thread_id"),metadata:q("metadata",{mode:"json"}).$type(),created_at:l("created_at",{mode:"timestamp"}).notNull().default(K`(unixepoch())`)}),rX=N$("bridge_permissions",{id:q("id").primaryKey(),chat_id:q("chat_id"),gateway_session_id:q("gateway_session_id").references(()=>b$.id),job_run_id:q("job_run_id").references(()=>l0.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:l("expires_at",{mode:"timestamp"}),created_at:l("created_at",{mode:"timestamp"}).notNull().default(K`(unixepoch())`),resolved_at:l("resolved_at",{mode:"timestamp"})}),b$=N$("gateway_sessions",{id:q("id").primaryKey(),chat_id:q("chat_id").notNull().references(()=>s0.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:l("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:l("last_activity_at",{mode:"timestamp"}),created_at:l("created_at",{mode:"timestamp"}).notNull().default(K`(unixepoch())`),updated_at:l("updated_at",{mode:"timestamp"}).notNull().default(K`(unixepoch())`)},($)=>[XX("gateway_sessions_chat_idx").on($.chat_id,$.updated_at)]),_2=N$("webhooks",{id:q("id").primaryKey(),job_id:q("job_id").notNull().references(()=>d0.id,{onDelete:"cascade"}),token:q("token").notNull().unique(),enabled:l("enabled",{mode:"boolean"}).default(!0).notNull(),created_at:l("created_at",{mode:"timestamp"}).notNull().default(K`(unixepoch())`)})});import{Database as f2}from"bun:sqlite";import{mkdirSync as x2}from"fs";import{dirname as y2}from"path";function g2($){$.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 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(`
|
|
36
36
|
CREATE TABLE IF NOT EXISTS projects (
|
|
37
37
|
id TEXT PRIMARY KEY,
|
|
38
38
|
name TEXT NOT NULL,
|
|
@@ -62,14 +62,17 @@ Expecting one of '${X.join("', '")}'`);let G=`${$}Help`;return this.on(G,(E)=>{l
|
|
|
62
62
|
updated_at INTEGER NOT NULL DEFAULT (unixepoch())
|
|
63
63
|
);
|
|
64
64
|
|
|
65
|
-
CREATE TABLE IF NOT EXISTS
|
|
65
|
+
CREATE TABLE IF NOT EXISTS comments (
|
|
66
66
|
id TEXT PRIMARY KEY,
|
|
67
|
-
|
|
67
|
+
resource_type TEXT NOT NULL,
|
|
68
|
+
resource_id TEXT NOT NULL,
|
|
68
69
|
content TEXT NOT NULL,
|
|
69
70
|
author TEXT NOT NULL DEFAULT 'human',
|
|
70
71
|
created_at INTEGER NOT NULL DEFAULT (unixepoch())
|
|
71
72
|
);
|
|
72
73
|
|
|
74
|
+
CREATE INDEX IF NOT EXISTS comments_resource_idx ON comments(resource_type, resource_id);
|
|
75
|
+
|
|
73
76
|
CREATE TABLE IF NOT EXISTS task_links (
|
|
74
77
|
id TEXT PRIMARY KEY,
|
|
75
78
|
from_task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
|
|
@@ -309,6 +312,33 @@ Expecting one of '${X.join("', '")}'`);let G=`${$}Help`;return this.on(G,(E)=>{l
|
|
|
309
312
|
VALUES (new.id, new.content, COALESCE(new.title, ''), COALESCE(new.tags, ''), COALESCE(new.scope, ''));
|
|
310
313
|
END;
|
|
311
314
|
|
|
315
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS tasks_fts USING fts5(
|
|
316
|
+
id UNINDEXED,
|
|
317
|
+
title,
|
|
318
|
+
body,
|
|
319
|
+
tags,
|
|
320
|
+
tokenize='porter ascii'
|
|
321
|
+
);
|
|
322
|
+
|
|
323
|
+
CREATE TRIGGER IF NOT EXISTS tasks_ai AFTER INSERT ON tasks BEGIN
|
|
324
|
+
INSERT INTO tasks_fts(id, title, body, tags)
|
|
325
|
+
VALUES (new.id, COALESCE(new.title, ''), COALESCE(new.body, ''), COALESCE(new.tags, ''));
|
|
326
|
+
END;
|
|
327
|
+
|
|
328
|
+
CREATE TRIGGER IF NOT EXISTS tasks_ad AFTER DELETE ON tasks BEGIN
|
|
329
|
+
DELETE FROM tasks_fts WHERE id = old.id;
|
|
330
|
+
END;
|
|
331
|
+
|
|
332
|
+
CREATE TRIGGER IF NOT EXISTS tasks_au AFTER UPDATE ON tasks BEGIN
|
|
333
|
+
DELETE FROM tasks_fts WHERE id = old.id;
|
|
334
|
+
INSERT INTO tasks_fts(id, title, body, tags)
|
|
335
|
+
VALUES (new.id, COALESCE(new.title, ''), COALESCE(new.body, ''), COALESCE(new.tags, ''));
|
|
336
|
+
END;
|
|
337
|
+
|
|
338
|
+
INSERT OR IGNORE INTO tasks_fts(id, title, body, tags)
|
|
339
|
+
SELECT id, COALESCE(title, ''), COALESCE(body, ''), COALESCE(tags, '')
|
|
340
|
+
FROM tasks;
|
|
341
|
+
|
|
312
342
|
CREATE TABLE IF NOT EXISTS session_events (
|
|
313
343
|
id TEXT PRIMARY KEY,
|
|
314
344
|
session_id TEXT NOT NULL,
|
|
@@ -329,185 +359,235 @@ Expecting one of '${X.join("', '")}'`);let G=`${$}Help`;return this.on(G,(E)=>{l
|
|
|
329
359
|
);
|
|
330
360
|
|
|
331
361
|
CREATE INDEX IF NOT EXISTS idx_snapshots_session ON session_snapshots(session_id, created_at DESC);
|
|
332
|
-
`);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'"];for(let
|
|
333
|
-
`);
|
|
334
|
-
`).slice(0,65536),stderr:
|
|
335
|
-
`).slice(0,16384)}).where(
|
|
336
|
-
`);
|
|
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 F2($){let w=O0(),E=$??w.db.path;if(E!==":memory:")Y2(H2(E),{recursive:!0});let X=new U2(E);return X.exec("PRAGMA journal_mode=WAL;"),X.exec("PRAGMA foreign_keys=ON;"),X.exec("PRAGMA synchronous=NORMAL;"),L2(X),nJ(X,{schema:k8})}function x(){if(!b8)b8=F2();return b8}var b8=null;var y$=R(()=>{C$();LY();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)),Z8.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
|
+
`);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
|
+
`).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}),Z8.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)),Z8.error(`Job ${E.name} [${X}] crashed: ${N}`),D}}var Z8;var nw=R(()=>{X1();p$();y$();d$();i$();Z8=Z0("runner:executor")});function mJ($,w){jY.set($,w)}function MY($,w){let E=jY.get($);if(!E)throw Error(`No adapter registered for: ${$}`);return E(w)}var jY;var rJ=R(()=>{jY=new Map});async function XX($,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 GX($,w){if(!$||typeof $==="number")return;$.write(w)}function pJ($){if(!$||typeof $==="number")return;$.end()}function JX($,w){C8.set($,w)}function oJ($){let w=C8.get($);if(!w)throw Error(`No agent backend registered for: ${$}`);return w()}function RY(){return[...C8.keys()]}var C8;var tJ=R(()=>{C8=new Map});var zY={};Ww(zY,{startCodexSession:()=>_8,CodexSession:()=>iJ});function M2(){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 iJ{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:M2()}),this.proc.stdout)XX(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)XX(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});GX(this.proc?.stdin,new TextEncoder().encode(`${D}
|
|
337
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(`
|
|
338
|
-
`).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:$});
|
|
339
|
-
`))}respondPermission($,w){let
|
|
340
|
-
`);if(
|
|
341
|
-
`))}async send($){let w={type:"user",message:{role:"user",content:$}};
|
|
342
|
-
`))}respondPermission($,w){let
|
|
343
|
-
${
|
|
344
|
-
<b>Tool:</b> ${
|
|
345
|
-
<b>Command:</b> <code>${
|
|
346
|
-
`)}async function
|
|
347
|
-
`)}}if(
|
|
348
|
-
`)}}if(
|
|
349
|
-
`),buttons:
|
|
350
|
-
`)}}if(
|
|
351
|
-
`)}}if(
|
|
352
|
-
`)}}if(
|
|
353
|
-
`)}}if(J==="switch"){let
|
|
354
|
-
|
|
355
|
-
Type /help for available commands.`}}async function
|
|
356
|
-
\u2026`:w;if(
|
|
357
|
-
\u2026`:w;if(!X.degraded&&G!==X.lastText)await this.doEdit(X,G);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 X=w.pendingText;w.pendingText=null,await this.doEdit(w,X)}async doEdit($,w){try{await this.adapter.updateMessage($.chatId,$.msgId,w),$.lastText=w,$.lastEditAt=Date.now()}catch{$.degraded=!0}}}class b9{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 wq($){let w=Q0(),X=w.gateway.slack.bot_token,G=w.gateway.slack.app_token;if(!X||!G)throw Error("Slack bot_token and app_token are required.");let E=null,J=null,W=!1,Y=new Map;function A(z){let Q=w.gateway.slack.authorized_users.map(String);return Q.length>0&&Q.includes(z)}function D(z){let Q=Date.now();if(Y.has(z))return!0;Y.set(z,Q);for(let[R,T]of Y)if(Q-T>$q)Y.delete(R);return!1}function U(z){if(!z)return!1;return parseFloat(z)*1000<$}async function N(){let z=await fetch("https://slack.com/api/apps.connections.open",{method:"POST",headers:{Authorization:`Bearer ${G}`}}),Q=await z.json();if(!z.ok||!Q.ok||!Q.url)throw Error(Q.error??`Slack socket connect failed (${z.status})`);return new WebSocket(Q.url)}async function H(z){if(!E||!z||E.readyState!==WebSocket.OPEN)return;E.send(JSON.stringify({envelope_id:z}))}async function L(z){let Q=JSON.parse(z.data);if(await H(Q.envelope_id),!J)return;if(Q.type==="interactive"){let k=Q.payload??{},m=k.actions?.[0]?.value,F0=k.user?.id,b0=k.channel?.id;if(!m||!F0||!b0||!A(F0))return;await J({platform:"slack",chatId:b0,userId:F0,username:k.user?.username,displayName:k.user?.name,text:m,threadId:k.message?.ts});return}let T=(Q.payload??{}).event;if(!T?.type||!T.user||!T.channel)return;if(!A(T.user))return;if(T.type!=="app_mention"&&!(T.type==="message"&&T.channel_type==="im"))return;if(T.ts&&D(T.ts))return;if(U(T.ts))return;let v=[];for(let k of T.files??[]){if(!k.url_private_download||!k.mimetype?.startsWith("audio/"))continue;try{let m=await fetch(k.url_private_download,{headers:{Authorization:`Bearer ${X}`}});v.push({kind:"audio",data:new Uint8Array(await m.arrayBuffer()),mimeType:k.mimetype,format:k.mimetype.split("/").at(1)??"mp3"})}catch{}}let f=(T.text??"").replace(/^<@[^>]+>\s*/,"").trim();await J({platform:"slack",chatId:T.channel,userId:T.user,text:f,threadId:T.thread_ts??T.ts,platformMessageId:T.ts,attachments:v.length>0?v:void 0})}async function F(z,Q){let R=await fetch(`https://slack.com/api/${z}`,{method:"POST",headers:{Authorization:`Bearer ${X}`,"Content-Type":"application/json; charset=utf-8"},body:JSON.stringify(Q)}),T=await R.json();if(!R.ok||T.ok!==!0)throw Error(String(T.error??`Slack request failed (${R.status})`));return T}function M(z,Q){if(!Q?.length)return;return[{type:"section",text:{type:"mrkdwn",text:z}},{type:"actions",elements:Q.flat().map((R)=>({type:"button",text:{type:"plain_text",text:R.label},value:R.value,action_id:R.value}))}]}return{platform:"slack",async start(z){J=z,W=!0;async function Q(){E=await N(),E.addEventListener("message",(R)=>{L(R)}),E.addEventListener("close",async()=>{if(!W)return;g4.warn("Slack socket closed; reconnecting in 5s"),await new Promise((R)=>setTimeout(R,5000));try{await Q()}catch(R){g4.error("Slack reconnect failed",{err:R})}}),E.addEventListener("error",(R)=>{g4.warn("Slack socket error",{err:R})}),g4.info("Slack gateway adapter connected")}await Q()},async stop(){W=!1,E?.close()},async send(z,Q,R){let T=M(Q,R?.buttons),v=await F("chat.postMessage",{channel:z,text:Q,thread_ts:R?.threadId,...T?{blocks:T}:{}});return`${String(v.channel??z)}:${String(v.ts??"")}`},async updateMessage(z,Q,R,T){let[v,f]=Q.split(":");if(!v||!f)return;let k=M(R,T?.buttons);await F("chat.update",{channel:v,ts:f,text:R,...k?{blocks:k}:{}})},async sendWithButtons(z,Q,R,T){let v=M(Q,R),f=await F("chat.postMessage",{channel:z,text:Q,thread_ts:T?.threadId,...v?{blocks:v}:{}});return`${String(f.channel??z)}:${String(f.ts??"")}`}}}var g4,$q=60000;var qN=B(()=>{d$();f$();Z4();g4=P0("gateway:slack");S4("slack",($)=>wq($))});import{mkdtempSync as Xq,readFileSync as Gq,rmSync as SN,writeFileSync as Eq}from"fs";import{tmpdir as Jq}from"os";import{join as k9}from"path";function Wq(){return Bun.which("ffmpeg")??null}function bN($){let w=$.toLowerCase();if(w==="oga"||w==="opus")return"ogg";if(w==="mpeg"||w==="mpga")return"mp3";return w}function ZN($){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 kN($,w,X){let G=Wq();if(!G)throw Error("ffmpeg is required for voice support.");let E=Xq(k9(Jq(),"orc-gateway-")),J=k9(E,`input.${bN(w)}`),W=k9(E,`output.${X}`);Eq(J,$);let Y=["-y","-i",J];if(X==="mp3")Y.push("-ac","1","-ar","16000");if(X==="ogg")Y.push("-c:a","libopus");Y.push(W);let A=Bun.spawnSync({cmd:[G,...Y],stdout:"ignore",stderr:"pipe"});if(A.exitCode!==0){let U=new TextDecoder().decode(A.stderr);throw SN(E,{recursive:!0,force:!0}),Error(U||"ffmpeg conversion failed")}let D=Gq(W);return SN(E,{recursive:!0,force:!0}),new Uint8Array(D)}function Yq($){return!["mp3","wav","webm","m4a","mp4"].includes($.toLowerCase())}async function CN($){let w=Q0();if(!w.speech.enabled)throw Error("Speech support is not enabled.");let{audio:X,format:G}=$;if(Yq(G))X=kN(X,G,"mp3"),G="mp3";if(w.speech.provider==="qwen"){let D=w.speech.qwen.api_key;if(!D)throw Error("Qwen speech API key is not configured.");let U=w.speech.qwen.base_url??"https://dashscope.aliyuncs.com/compatible-mode/v1",N={model:w.speech.qwen.model??"qwen3-asr-flash",messages:[{role:"user",content:[{type:"input_audio",input_audio:{data:`data:${ZN(G)};base64,${Buffer.from(X).toString("base64")}`}}]}]},H=await fetch(`${U.replace(/\/$/,"")}/chat/completions`,{method:"POST",headers:{Authorization:`Bearer ${D}`,"Content-Type":"application/json"},body:JSON.stringify(N)}),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 E=w.speech.provider==="groq"?w.speech.groq:w.speech.openai;if(!E.api_key)throw Error("Speech API key is not configured.");let J=E.base_url??(w.speech.provider==="groq"?"https://api.groq.com/openai/v1":"https://api.openai.com/v1"),W=new FormData;if(W.append("model",E.model??(w.speech.provider==="groq"?"whisper-large-v3-turbo":"whisper-1")),W.append("response_format","text"),w.speech.language)W.append("language",w.speech.language);W.append("file",new File([X],`audio.${bN(G)}`,{type:ZN(G)}));let Y=await fetch(`${J.replace(/\/$/,"")}/audio/transcriptions`,{method:"POST",headers:{Authorization:`Bearer ${E.api_key}`},body:W}),A=await Y.text();if(!Y.ok)throw Error(A||`Speech request failed (${Y.status})`);return A.trim()}async function vN($){let w=Q0();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 W=w.tts.qwen.api_key;if(!W)throw Error("Qwen TTS API key is not configured.");let Y=await fetch(w.tts.qwen.base_url??"https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation",{method:"POST",headers:{Authorization:`Bearer ${W}`,"Content-Type":"application/json"},body:JSON.stringify({model:w.tts.qwen.model??"qwen3-tts-flash",input:{text:$,voice:w.tts.voice||"Cherry"}})}),A=await Y.json();if(!Y.ok||A.code)throw Error(A.message??`TTS request failed (${Y.status})`);if(!A.output?.audio?.url)throw Error("Qwen TTS did not return audio.");let D=await fetch(A.output.audio.url),U=new Uint8Array(await D.arrayBuffer());return{audio:kN(U,"wav","ogg"),format:"ogg"}}let X=w.tts.openai.api_key??w.speech.openai.api_key;if(!X)throw Error("OpenAI TTS API key is not configured.");let G=w.tts.openai.base_url??"https://api.openai.com/v1",E=await fetch(`${G.replace(/\/$/,"")}/audio/speech`,{method:"POST",headers:{Authorization:`Bearer ${X}`,"Content-Type":"application/json"},body:JSON.stringify({model:w.tts.openai.model??"tts-1",input:$,voice:w.tts.voice||"alloy"})});if(!E.ok)throw Error(await E.text());return{audio:new Uint8Array(await E.arrayBuffer()),format:"mp3"}}var _N=B(()=>{d$()});var c4=b((oN)=>{Object.defineProperty(oN,"__esModule",{value:!0});oN.matchFilter=Aq;oN.parse=pN;oN.preprocess=rN;var fN=new Map;function Aq($){var w;let X=Array.isArray($)?$:[$],G=X.join(","),E=(w=fN.get(G))!==null&&w!==void 0?w:(()=>{let J=pN(X),W=Dq(J);return fN.set(G,W),W})();return(J)=>E(J)}function pN($){return Array.isArray($)?$.map((w)=>w.split(":")):[$.split(":")]}function Dq($){let w=$.flatMap((E)=>Uq(E,rN(E))),X=Nq(w),G=Hq(X);return(E)=>!!G(E.update,E)}function rN($){let w=u4,X=[$].flatMap((G)=>{let[E,J,W]=G;if(!(E in nN))return[G];if(!E&&!J&&!W)return[G];let A=nN[E].map((D)=>[D,J,W]);if(J===void 0)return A;if(J in v9&&(J||W))return A;return A.filter(([D])=>{var U;return!!((U=w[D])===null||U===void 0?void 0:U[J])})}).flatMap((G)=>{let[E,J,W]=G;if(!(J in v9))return[G];if(!J&&!W)return[G];let A=v9[J].map((D)=>[E,D,W]);if(W===void 0)return A;return A.filter(([,D])=>{var U,N;return!!((N=(U=w[E])===null||U===void 0?void 0:U[D])===null||N===void 0?void 0:N[W])})});if(X.length===0)throw Error(`Shortcuts in '${$.join(":")}' do not expand to any valid filter query`);return X}function Uq($,w){if(w.length===0)throw Error("Empty filter query given");let X=w.map(Oq).filter((G)=>G!==!0);if(X.length===0)return w;else if(X.length===1)throw Error(X[0]);else throw Error(`Invalid filter query '${$.join(":")}'. There are ${X.length} errors after expanding the contained shortcuts: ${X.join("; ")}`)}function Oq($){let[w,X,G,...E]=$;if(w===void 0)return"Empty filter query given";if(!(w in u4)){let Y=Object.keys(u4);return`Invalid L1 filter '${w}' given in '${$.join(":")}'. Permitted values are: ${Y.map((A)=>`'${A}'`).join(", ")}.`}if(X===void 0)return!0;let J=u4[w];if(!(X in J)){let Y=Object.keys(J);return`Invalid L2 filter '${X}' given in '${$.join(":")}'. Permitted values are: ${Y.map((A)=>`'${A}'`).join(", ")}.`}if(G===void 0)return!0;let W=J[X];if(!(G in W)){let Y=Object.keys(W);return`Invalid L3 filter '${G}' given in '${$.join(":")}'. ${Y.length===0?`No further filtering is possible after '${w}:${X}'.`:`Permitted values are: ${Y.map((A)=>`'${A}'`).join(", ")}.`}`}if(E.length===0)return!0;return`Cannot filter further than three levels, ':${E.join(":")}' is invalid!`}function Nq($){var w,X;let G={};for(let[E,J,W]of $){let Y=(w=G[E])!==null&&w!==void 0?w:G[E]={};if(J!==void 0){let A=(X=Y[J])!==null&&X!==void 0?X:Y[J]=new Set;if(W!==void 0)A.add(W)}}return G}function C9($,w){return(X,G)=>$(X,G)||w(X,G)}function xN($,w){return(X,G)=>{let E=$(X,G);return E&&w(E,G)}}function yN($){return(w,X)=>$(w,X)!=null}function Hq($){let w=Object.entries($).map(([X,G])=>{let E=(W)=>W[X],J=Object.entries(G).map(([W,Y])=>{let A=(U)=>U[W],D=Array.from(Y).map((U)=>{return U==="me"?(H,L)=>{let F=L.me.id;return gN(H,(M)=>M.id===F)}:(H)=>gN(H,(L)=>L[U]||L.type===U)});return D.length===0?yN(A):xN(A,D.reduce(C9))});return J.length===0?yN(E):xN(E,J.reduce(C9))});if(w.length===0)throw Error("Cannot create filter function for empty query");return w.reduce(C9)}function gN($,w){let X=(G)=>G!=null&&w(G);return Array.isArray($)?$.some(X):X($)}var hN={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:{}},_9={me:{},is_bot:{},is_premium:{},added_to_attachment_menu:{}},Lq={user:{},hidden_user:{},chat:{},channel:{}},Fq={is_video:{},is_animated:{},premium_animation:{}},f9={emoji:{},custom_emoji:{},paid:{}},uN={can_be_upgraded:{},is_upgrade_separate:{},is_private:{}},iN={forward_origin:Lq,is_topic_message:{},is_automatic_forward:{},business_connection_id:{},text:{},animation:{},audio:{},document:{},paid_media:{},photo:{},sticker:Fq,story:{},video:{},video_note:{},voice:{},contact:{},dice:{},game:{},poll:{},venue:{},location:{},entities:hN,caption_entities:hN,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:uN,gift_upgrade_sent:uN,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:{}},h4={...iN,direct_messages_topic:{},chat_owner_left:{new_owner:{}},chat_owner_changd:{},new_chat_members:_9,left_chat_member:_9,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:{}},cN={...iN,channel_chat_created:{},direct_message_price_changed:{},is_paid_post:{}},Mq={can_reply:{},is_enabled:{}},zq={old_reaction:f9,new_reaction:f9},Qq={reactions:f9},Bq={data:{},game_short_name:{}},mN={from:_9},u4={message:h4,edited_message:h4,channel_post:cN,edited_channel_post:cN,business_connection:Mq,business_message:h4,edited_business_message:h4,deleted_business_messages:{},inline_query:{},chosen_inline_result:{},callback_query:Bq,shipping_query:{},pre_checkout_query:{},poll:{},poll_answer:{},my_chat_member:mN,chat_member:mN,chat_join_request:{},message_reaction:zq,message_reaction_count:Qq,chat_boost:{},removed_chat_boost:{},purchased_paid_media:{}},nN={"":["message","channel_post"],msg:["message","channel_post"],edit:["edited_message","edited_channel_post"]},v9={"":["entities","caption_entities"],media:["photo","video"],file:["photo","animation","audio","document","video","video_note","voice","sticker"]}});var n4=b((tN)=>{Object.defineProperty(tN,"__esModule",{value:!0});tN.Context=void 0;var Tq=c4(),r1={filterQuery($){let w=(0,Tq.matchFilter)($);return(X)=>w(X)},text($){let w=r1.filterQuery([":text",":caption"]),X=GX($);return(G)=>{var E,J;if(!w(G))return!1;let W=(E=G.message)!==null&&E!==void 0?E:G.channelPost,Y=(J=W.text)!==null&&J!==void 0?J:W.caption;return EX(G,Y,X)}},command($){let w=r1.filterQuery(":entities:bot_command"),X=new Set,G=new Set;return m4($).forEach((E)=>{if(E.startsWith("/"))throw Error(`Do not include '/' when registering command handlers (use '${E.substring(1)}' not '${E}')`);(E.includes("@")?X:G).add(E)}),(E)=>{var J,W;if(!w(E))return!1;let Y=(J=E.message)!==null&&J!==void 0?J:E.channelPost,A=(W=Y.text)!==null&&W!==void 0?W:Y.caption;return Y.entities.some((D)=>{if(D.type!=="bot_command")return!1;if(D.offset!==0)return!1;let U=A.substring(1,D.length);if(G.has(U)||X.has(U))return E.match=A.substring(U.length+1).trimStart(),!0;let N=U.indexOf("@");if(N===-1)return!1;let H=U.substring(N+1).toLowerCase(),L=E.me.username.toLowerCase();if(H!==L)return!1;let F=U.substring(0,N);if(G.has(F))return E.match=A.substring(U.length+1).trimStart(),!0;return!1})}},reaction($){let w=r1.filterQuery("message_reaction"),X=typeof $==="string"?[{type:"emoji",emoji:$}]:(Array.isArray($)?$:[$]).map((W)=>typeof W==="string"?{type:"emoji",emoji:W}:W),G=new Set(X.filter((W)=>W.type==="emoji").map((W)=>W.emoji)),E=new Set(X.filter((W)=>W.type==="custom_emoji").map((W)=>W.custom_emoji_id)),J=X.some((W)=>W.type==="paid");return(W)=>{if(!w(W))return!1;let{old_reaction:Y,new_reaction:A}=W.messageReaction;for(let D of A){let U=!1;if(D.type==="emoji")for(let N of Y){if(N.type!=="emoji")continue;if(N.emoji===D.emoji){U=!0;break}}else if(D.type==="custom_emoji")for(let N of Y){if(N.type!=="custom_emoji")continue;if(N.custom_emoji_id===D.custom_emoji_id){U=!0;break}}else if(D.type==="paid")for(let N of Y){if(N.type!=="paid")continue;U=!0;break}if(U)continue;if(D.type==="emoji"){if(G.has(D.emoji))return!0}else if(D.type==="custom_emoji"){if(E.has(D.custom_emoji_id))return!0}else if(D.type==="paid"){if(J)return!0}else return!0}return!1}},chatType($){let w=new Set(m4($));return(X)=>{var G;return((G=X.chat)===null||G===void 0?void 0:G.type)!==void 0&&w.has(X.chat.type)}},callbackQuery($){let w=r1.filterQuery("callback_query:data"),X=GX($);return(G)=>w(G)&&EX(G,G.callbackQuery.data,X)},gameQuery($){let w=r1.filterQuery("callback_query:game_short_name"),X=GX($);return(G)=>w(G)&&EX(G,G.callbackQuery.game_short_name,X)},inlineQuery($){let w=r1.filterQuery("inline_query"),X=GX($);return(G)=>w(G)&&EX(G,G.inlineQuery.query,X)},chosenInlineResult($){let w=r1.filterQuery("chosen_inline_result"),X=GX($);return(G)=>w(G)&&EX(G,G.chosenInlineResult.result_id,X)},preCheckoutQuery($){let w=r1.filterQuery("pre_checkout_query"),X=GX($);return(G)=>w(G)&&EX(G,G.preCheckoutQuery.invoice_payload,X)},shippingQuery($){let w=r1.filterQuery("shipping_query"),X=GX($);return(G)=>w(G)&&EX(G,G.shippingQuery.invoice_payload,X)}};class m${constructor($,w,X){this.update=$,this.api=w,this.me=X}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,X,G,E,J,W;return(J=(E=(G=(X=(w=($=this.message)!==null&&$!==void 0?$:this.editedMessage)!==null&&w!==void 0?w:this.channelPost)!==null&&X!==void 0?X:this.editedChannelPost)!==null&&G!==void 0?G:this.businessMessage)!==null&&E!==void 0?E:this.editedBusinessMessage)!==null&&J!==void 0?J:(W=this.callbackQuery)===null||W===void 0?void 0:W.message}get chat(){var $,w,X,G,E,J,W,Y,A;return(A=(Y=(W=(J=(E=(G=(X=(w=($=this.msg)!==null&&$!==void 0?$:this.deletedBusinessMessages)!==null&&w!==void 0?w:this.messageReaction)!==null&&X!==void 0?X:this.messageReactionCount)!==null&&G!==void 0?G:this.myChatMember)!==null&&E!==void 0?E:this.chatMember)!==null&&J!==void 0?J:this.chatJoinRequest)!==null&&W!==void 0?W:this.chatBoost)!==null&&Y!==void 0?Y:this.removedChatBoost)===null||A===void 0?void 0:A.chat}get senderChat(){var $;return($=this.msg)===null||$===void 0?void 0:$.sender_chat}get from(){var $,w,X,G,E,J,W,Y,A,D,U,N,H,L,F,M,z;return(W=(J=(w=($=this.businessConnection)!==null&&$!==void 0?$:this.messageReaction)!==null&&w!==void 0?w:(E=(G=(X=this.chatBoost)===null||X===void 0?void 0:X.boost)!==null&&G!==void 0?G:this.removedChatBoost)===null||E===void 0?void 0:E.source)===null||J===void 0?void 0:J.user)!==null&&W!==void 0?W:(z=(M=(F=(L=(H=(N=(U=(D=(A=(Y=this.callbackQuery)!==null&&Y!==void 0?Y:this.msg)!==null&&A!==void 0?A:this.inlineQuery)!==null&&D!==void 0?D:this.chosenInlineResult)!==null&&U!==void 0?U:this.shippingQuery)!==null&&N!==void 0?N:this.preCheckoutQuery)!==null&&H!==void 0?H:this.myChatMember)!==null&&L!==void 0?L:this.chatMember)!==null&&F!==void 0?F:this.chatJoinRequest)!==null&&M!==void 0?M:this.purchasedPaidMedia)===null||z===void 0?void 0:z.from}get msgId(){var $,w,X,G,E;return(G=(w=($=this.msg)===null||$===void 0?void 0:$.message_id)!==null&&w!==void 0?w:(X=this.messageReaction)===null||X===void 0?void 0:X.message_id)!==null&&G!==void 0?G:(E=this.messageReactionCount)===null||E===void 0?void 0:E.message_id}get chatId(){var $,w,X;return(w=($=this.chat)===null||$===void 0?void 0:$.id)!==null&&w!==void 0?w:(X=this.businessConnection)===null||X===void 0?void 0:X.user_chat_id}get inlineMessageId(){var $,w,X;return(w=($=this.callbackQuery)===null||$===void 0?void 0:$.inline_message_id)!==null&&w!==void 0?w:(X=this.chosenInlineResult)===null||X===void 0?void 0:X.inline_message_id}get businessConnectionId(){var $,w,X,G,E;return(G=(w=($=this.msg)===null||$===void 0?void 0:$.business_connection_id)!==null&&w!==void 0?w:(X=this.businessConnection)===null||X===void 0?void 0:X.id)!==null&&G!==void 0?G:(E=this.deletedBusinessMessages)===null||E===void 0?void 0:E.business_connection_id}entities($){var w,X;let G=this.msg;if(G===void 0)return[];let E=(w=G.text)!==null&&w!==void 0?w:G.caption;if(E===void 0)return[];let J=(X=G.entities)!==null&&X!==void 0?X:G.caption_entities;if(J===void 0)return[];if($!==void 0){let W=new Set(m4($));J=J.filter((Y)=>W.has(Y.type))}return J.map((W)=>({...W,text:E.substring(W.offset,W.offset+W.length)}))}reactions(){let $=[],w=[],X=[],G=[],E=[],J=[],W=[],Y=[],A=!1,D=!1,U=this.messageReaction;if(U!==void 0){let{old_reaction:N,new_reaction:H}=U;for(let L of H)if(L.type==="emoji")$.push(L.emoji);else if(L.type==="custom_emoji")E.push(L.custom_emoji_id);else if(L.type==="paid")A=D=!0;for(let L of N)if(L.type==="emoji")G.push(L.emoji);else if(L.type==="custom_emoji")Y.push(L.custom_emoji_id);else if(L.type==="paid")D=!1;w.push(...$),J.push(...E);for(let L=0;L<G.length;L++){let F=w.length;if(F===0)break;let M=G[L];for(let z=0;z<F;z++)if(M===w[z]){X.push(M),G.splice(L,1),w.splice(z,1),L--;break}}for(let L=0;L<Y.length;L++){let F=J.length;if(F===0)break;let M=Y[L];for(let z=0;z<F;z++)if(M===J[z]){W.push(M),Y.splice(L,1),J.splice(z,1),L--;break}}}return{emoji:$,emojiAdded:w,emojiKept:X,emojiRemoved:G,customEmoji:E,customEmojiAdded:J,customEmojiKept:W,customEmojiRemoved:Y,paid:A,paidAdded:D}}has($){return m$.has.filterQuery($)(this)}hasText($){return m$.has.text($)(this)}hasCommand($){return m$.has.command($)(this)}hasReaction($){return m$.has.reaction($)(this)}hasChatType($){return m$.has.chatType($)(this)}hasCallbackQuery($){return m$.has.callbackQuery($)(this)}hasGameQuery($){return m$.has.gameQuery($)(this)}hasInlineQuery($){return m$.has.inlineQuery($)(this)}hasChosenInlineResult($){return m$.has.chosenInlineResult($)(this)}hasPreCheckoutQuery($){return m$.has.preCheckoutQuery($)(this)}hasShippingQuery($){return m$.has.shippingQuery($)(this)}reply($,w,X){var G;let E=this.msg;return this.api.sendMessage(V(this.chatId,"sendMessage"),$,{business_connection_id:this.businessConnectionId,...(E===null||E===void 0?void 0:E.is_topic_message)?{message_thread_id:E.message_thread_id}:{},direct_messages_topic_id:(G=E===null||E===void 0?void 0:E.direct_messages_topic)===null||G===void 0?void 0:G.topic_id,...w},X)}replyWithDraft($,w,X){let G=this.msg;return this.api.sendMessageDraft(V(this.chatId,"sendMessageDraft"),this.update.update_id,$,{...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G===null||G===void 0?void 0:G.message_thread_id}:{},...w},X)}forwardMessage($,w,X){var G;let E=this.msg;return this.api.forwardMessage($,V(this.chatId,"forwardMessage"),V(this.msgId,"forwardMessage"),{direct_messages_topic_id:(G=E===null||E===void 0?void 0:E.direct_messages_topic)===null||G===void 0?void 0:G.topic_id,...w},X)}forwardMessages($,w,X,G){var E;let J=this.msg;return this.api.forwardMessages($,V(this.chatId,"forwardMessages"),w,{direct_messages_topic_id:(E=J===null||J===void 0?void 0:J.direct_messages_topic)===null||E===void 0?void 0:E.topic_id,...X},G)}copyMessage($,w,X){var G;let E=this.msg;return this.api.copyMessage($,V(this.chatId,"copyMessage"),V(this.msgId,"copyMessage"),{direct_messages_topic_id:(G=E===null||E===void 0?void 0:E.direct_messages_topic)===null||G===void 0?void 0:G.topic_id,...w},X)}copyMessages($,w,X,G){var E;let J=this.msg;return this.api.copyMessages($,V(this.chatId,"copyMessages"),w,{direct_messages_topic_id:(E=J===null||J===void 0?void 0:J.direct_messages_topic)===null||E===void 0?void 0:E.topic_id,...X},G)}replyWithPhoto($,w,X){var G;let E=this.msg;return this.api.sendPhoto(V(this.chatId,"sendPhoto"),$,{business_connection_id:this.businessConnectionId,...(E===null||E===void 0?void 0:E.is_topic_message)?{message_thread_id:E.message_thread_id}:{},direct_messages_topic_id:(G=E===null||E===void 0?void 0:E.direct_messages_topic)===null||G===void 0?void 0:G.topic_id,...w},X)}replyWithAudio($,w,X){var G;let E=this.msg;return this.api.sendAudio(V(this.chatId,"sendAudio"),$,{business_connection_id:this.businessConnectionId,...(E===null||E===void 0?void 0:E.is_topic_message)?{message_thread_id:E.message_thread_id}:{},direct_messages_topic_id:(G=E===null||E===void 0?void 0:E.direct_messages_topic)===null||G===void 0?void 0:G.topic_id,...w},X)}replyWithDocument($,w,X){var G;let E=this.msg;return this.api.sendDocument(V(this.chatId,"sendDocument"),$,{business_connection_id:this.businessConnectionId,...(E===null||E===void 0?void 0:E.is_topic_message)?{message_thread_id:E.message_thread_id}:{},direct_messages_topic_id:(G=E===null||E===void 0?void 0:E.direct_messages_topic)===null||G===void 0?void 0:G.topic_id,...w},X)}replyWithVideo($,w,X){var G;let E=this.msg;return this.api.sendVideo(V(this.chatId,"sendVideo"),$,{business_connection_id:this.businessConnectionId,...(E===null||E===void 0?void 0:E.is_topic_message)?{message_thread_id:E.message_thread_id}:{},direct_messages_topic_id:(G=E===null||E===void 0?void 0:E.direct_messages_topic)===null||G===void 0?void 0:G.topic_id,...w},X)}replyWithAnimation($,w,X){var G;let E=this.msg;return this.api.sendAnimation(V(this.chatId,"sendAnimation"),$,{business_connection_id:this.businessConnectionId,...(E===null||E===void 0?void 0:E.is_topic_message)?{message_thread_id:E.message_thread_id}:{},direct_messages_topic_id:(G=E===null||E===void 0?void 0:E.direct_messages_topic)===null||G===void 0?void 0:G.topic_id,...w},X)}replyWithVoice($,w,X){var G;let E=this.msg;return this.api.sendVoice(V(this.chatId,"sendVoice"),$,{business_connection_id:this.businessConnectionId,...(E===null||E===void 0?void 0:E.is_topic_message)?{message_thread_id:E.message_thread_id}:{},direct_messages_topic_id:(G=E===null||E===void 0?void 0:E.direct_messages_topic)===null||G===void 0?void 0:G.topic_id,...w},X)}replyWithVideoNote($,w,X){var G;let E=this.msg;return this.api.sendVideoNote(V(this.chatId,"sendVideoNote"),$,{business_connection_id:this.businessConnectionId,...(E===null||E===void 0?void 0:E.is_topic_message)?{message_thread_id:E.message_thread_id}:{},direct_messages_topic_id:(G=E===null||E===void 0?void 0:E.direct_messages_topic)===null||G===void 0?void 0:G.topic_id,...w},X)}replyWithMediaGroup($,w,X){var G;let E=this.msg;return this.api.sendMediaGroup(V(this.chatId,"sendMediaGroup"),$,{business_connection_id:this.businessConnectionId,...(E===null||E===void 0?void 0:E.is_topic_message)?{message_thread_id:E.message_thread_id}:{},direct_messages_topic_id:(G=E===null||E===void 0?void 0:E.direct_messages_topic)===null||G===void 0?void 0:G.topic_id,...w},X)}replyWithLocation($,w,X,G){var E;let J=this.msg;return this.api.sendLocation(V(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:(E=J===null||J===void 0?void 0:J.direct_messages_topic)===null||E===void 0?void 0:E.topic_id,...X},G)}editMessageLiveLocation($,w,X,G){let E=this.inlineMessageId;return E!==void 0?this.api.editMessageLiveLocationInline(E,$,w,{business_connection_id:this.businessConnectionId,...X},G):this.api.editMessageLiveLocation(V(this.chatId,"editMessageLiveLocation"),V(this.msgId,"editMessageLiveLocation"),$,w,{business_connection_id:this.businessConnectionId,...X},G)}stopMessageLiveLocation($,w){let X=this.inlineMessageId;return X!==void 0?this.api.stopMessageLiveLocationInline(X,{business_connection_id:this.businessConnectionId,...$},w):this.api.stopMessageLiveLocation(V(this.chatId,"stopMessageLiveLocation"),V(this.msgId,"stopMessageLiveLocation"),{business_connection_id:this.businessConnectionId,...$},w)}sendPaidMedia($,w,X,G){var E,J;let W=this.msg;return this.api.sendPaidMedia(V(this.chatId,"sendPaidMedia"),$,w,{business_connection_id:this.businessConnectionId,...(W===null||W===void 0?void 0:W.is_topic_message)?{message_thread_id:W.message_thread_id}:{},direct_messages_topic_id:(J=(E=this.msg)===null||E===void 0?void 0:E.direct_messages_topic)===null||J===void 0?void 0:J.topic_id,...X},G)}replyWithVenue($,w,X,G,E,J){var W;let Y=this.msg;return this.api.sendVenue(V(this.chatId,"sendVenue"),$,w,X,G,{business_connection_id:this.businessConnectionId,...(Y===null||Y===void 0?void 0:Y.is_topic_message)?{message_thread_id:Y.message_thread_id}:{},direct_messages_topic_id:(W=Y===null||Y===void 0?void 0:Y.direct_messages_topic)===null||W===void 0?void 0:W.topic_id,...E},J)}replyWithContact($,w,X,G){var E;let J=this.msg;return this.api.sendContact(V(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:(E=J===null||J===void 0?void 0:J.direct_messages_topic)===null||E===void 0?void 0:E.topic_id,...X},G)}replyWithPoll($,w,X,G){let E=this.msg;return this.api.sendPoll(V(this.chatId,"sendPoll"),$,w,{business_connection_id:this.businessConnectionId,...(E===null||E===void 0?void 0:E.is_topic_message)?{message_thread_id:E.message_thread_id}:{},...X},G)}replyWithChecklist($,w,X){return this.api.sendChecklist(V(this.businessConnectionId,"sendChecklist"),V(this.chatId,"sendChecklist"),$,w,X)}editMessageChecklist($,w,X){var G,E,J,W;let Y=V(this.msg,"editMessageChecklist"),A=(W=(E=(G=Y.checklist_tasks_done)===null||G===void 0?void 0:G.checklist_message)!==null&&E!==void 0?E:(J=Y.checklist_tasks_added)===null||J===void 0?void 0:J.checklist_message)!==null&&W!==void 0?W:Y;return this.api.editMessageChecklist(V(this.businessConnectionId,"editMessageChecklist"),V(A.chat.id,"editMessageChecklist"),V(A.message_id,"editMessageChecklist"),$,w,X)}replyWithDice($,w,X){var G;let E=this.msg;return this.api.sendDice(V(this.chatId,"sendDice"),$,{business_connection_id:this.businessConnectionId,...(E===null||E===void 0?void 0:E.is_topic_message)?{message_thread_id:E.message_thread_id}:{},direct_messages_topic_id:(G=E===null||E===void 0?void 0:E.direct_messages_topic)===null||G===void 0?void 0:G.topic_id,...w},X)}replyWithChatAction($,w,X){let G=this.msg;return this.api.sendChatAction(V(this.chatId,"sendChatAction"),$,{business_connection_id:this.businessConnectionId,message_thread_id:G===null||G===void 0?void 0:G.message_thread_id,...w},X)}react($,w,X){return this.api.setMessageReaction(V(this.chatId,"setMessageReaction"),V(this.msgId,"setMessageReaction"),typeof $==="string"?[{type:"emoji",emoji:$}]:(Array.isArray($)?$:[$]).map((G)=>typeof G==="string"?{type:"emoji",emoji:G}:G),w,X)}getUserProfilePhotos($,w){return this.api.getUserProfilePhotos(V(this.from,"getUserProfilePhotos").id,$,w)}getUserProfileAudios($,w){return this.api.getUserProfileAudios(V(this.from,"getUserProfileAudios").id,$,w)}setUserEmojiStatus($,w){return this.api.setUserEmojiStatus(V(this.from,"setUserEmojiStatus").id,$,w)}getUserChatBoosts($,w){return this.api.getUserChatBoosts($!==null&&$!==void 0?$:V(this.chatId,"getUserChatBoosts"),V(this.from,"getUserChatBoosts").id,w)}getUserGifts($,w){return this.api.getUserGifts(V(this.from,"getUserGifts").id,$,w)}getChatGifts($,w){return this.api.getChatGifts(V(this.chatId,"getChatGifts"),$,w)}getBusinessConnection($){return this.api.getBusinessConnection(V(this.businessConnectionId,"getBusinessConnection"),$)}getFile($){var w,X,G,E,J,W;let Y=V(this.msg,"getFile"),A=Y.photo!==void 0?Y.photo[Y.photo.length-1]:(W=(J=(E=(G=(X=(w=Y.animation)!==null&&w!==void 0?w:Y.audio)!==null&&X!==void 0?X:Y.document)!==null&&G!==void 0?G:Y.video)!==null&&E!==void 0?E:Y.video_note)!==null&&J!==void 0?J:Y.voice)!==null&&W!==void 0?W:Y.sticker;return this.api.getFile(V(A,"getFile").file_id,$)}kickAuthor(...$){return this.banAuthor(...$)}banAuthor($,w){return this.api.banChatMember(V(this.chatId,"banAuthor"),V(this.from,"banAuthor").id,$,w)}kickChatMember(...$){return this.banChatMember(...$)}banChatMember($,w,X){return this.api.banChatMember(V(this.chatId,"banChatMember"),$,w,X)}unbanChatMember($,w,X){return this.api.unbanChatMember(V(this.chatId,"unbanChatMember"),$,w,X)}restrictAuthor($,w,X){return this.api.restrictChatMember(V(this.chatId,"restrictAuthor"),V(this.from,"restrictAuthor").id,$,w,X)}restrictChatMember($,w,X,G){return this.api.restrictChatMember(V(this.chatId,"restrictChatMember"),$,w,X,G)}promoteAuthor($,w){return this.api.promoteChatMember(V(this.chatId,"promoteAuthor"),V(this.from,"promoteAuthor").id,$,w)}promoteChatMember($,w,X){return this.api.promoteChatMember(V(this.chatId,"promoteChatMember"),$,w,X)}setChatAdministratorAuthorCustomTitle($,w){return this.api.setChatAdministratorCustomTitle(V(this.chatId,"setChatAdministratorAuthorCustomTitle"),V(this.from,"setChatAdministratorAuthorCustomTitle").id,$,w)}setChatAdministratorCustomTitle($,w,X){return this.api.setChatAdministratorCustomTitle(V(this.chatId,"setChatAdministratorCustomTitle"),$,w,X)}setAuthorTag($,w){return this.api.setChatMemberTag(V(this.chatId,"setChatMemberTag"),V(this.from,"setChatMemberTag").id,$,w)}setChatMemberTag($,w,X){return this.api.setChatMemberTag(V(this.chatId,"setChatMemberTag"),$,w,X)}banChatSenderChat($,w){return this.api.banChatSenderChat(V(this.chatId,"banChatSenderChat"),$,w)}unbanChatSenderChat($,w){return this.api.unbanChatSenderChat(V(this.chatId,"unbanChatSenderChat"),$,w)}setChatPermissions($,w,X){return this.api.setChatPermissions(V(this.chatId,"setChatPermissions"),$,w,X)}exportChatInviteLink($){return this.api.exportChatInviteLink(V(this.chatId,"exportChatInviteLink"),$)}createChatInviteLink($,w){return this.api.createChatInviteLink(V(this.chatId,"createChatInviteLink"),$,w)}editChatInviteLink($,w,X){return this.api.editChatInviteLink(V(this.chatId,"editChatInviteLink"),$,w,X)}createChatSubscriptionInviteLink($,w,X,G){return this.api.createChatSubscriptionInviteLink(V(this.chatId,"createChatSubscriptionInviteLink"),$,w,X,G)}editChatSubscriptionInviteLink($,w,X){return this.api.editChatSubscriptionInviteLink(V(this.chatId,"editChatSubscriptionInviteLink"),$,w,X)}revokeChatInviteLink($,w){return this.api.revokeChatInviteLink(V(this.chatId,"editChatInviteLink"),$,w)}approveChatJoinRequest($,w){return this.api.approveChatJoinRequest(V(this.chatId,"approveChatJoinRequest"),$,w)}declineChatJoinRequest($,w){return this.api.declineChatJoinRequest(V(this.chatId,"declineChatJoinRequest"),$,w)}approveSuggestedPost($,w){return this.api.approveSuggestedPost(V(this.chatId,"approveSuggestedPost"),V(this.msgId,"approveSuggestedPost"),$,w)}declineSuggestedPost($,w){return this.api.declineSuggestedPost(V(this.chatId,"declineSuggestedPost"),V(this.msgId,"declineSuggestedPost"),$,w)}setChatPhoto($,w){return this.api.setChatPhoto(V(this.chatId,"setChatPhoto"),$,w)}deleteChatPhoto($){return this.api.deleteChatPhoto(V(this.chatId,"deleteChatPhoto"),$)}setChatTitle($,w){return this.api.setChatTitle(V(this.chatId,"setChatTitle"),$,w)}setChatDescription($,w){return this.api.setChatDescription(V(this.chatId,"setChatDescription"),$,w)}pinChatMessage($,w,X){return this.api.pinChatMessage(V(this.chatId,"pinChatMessage"),$,{business_connection_id:this.businessConnectionId,...w},X)}unpinChatMessage($,w,X){return this.api.unpinChatMessage(V(this.chatId,"unpinChatMessage"),$,{business_connection_id:this.businessConnectionId,...w},X)}unpinAllChatMessages($){return this.api.unpinAllChatMessages(V(this.chatId,"unpinAllChatMessages"),$)}leaveChat($){return this.api.leaveChat(V(this.chatId,"leaveChat"),$)}getChat($){return this.api.getChat(V(this.chatId,"getChat"),$)}getChatAdministrators($){return this.api.getChatAdministrators(V(this.chatId,"getChatAdministrators"),$)}getChatMembersCount(...$){return this.getChatMemberCount(...$)}getChatMemberCount($){return this.api.getChatMemberCount(V(this.chatId,"getChatMemberCount"),$)}getAuthor($){return this.api.getChatMember(V(this.chatId,"getAuthor"),V(this.from,"getAuthor").id,$)}getChatMember($,w){return this.api.getChatMember(V(this.chatId,"getChatMember"),$,w)}setChatStickerSet($,w){return this.api.setChatStickerSet(V(this.chatId,"setChatStickerSet"),$,w)}deleteChatStickerSet($){return this.api.deleteChatStickerSet(V(this.chatId,"deleteChatStickerSet"),$)}createForumTopic($,w,X){return this.api.createForumTopic(V(this.chatId,"createForumTopic"),$,w,X)}editForumTopic($,w){let X=V(this.msg,"editForumTopic"),G=V(X.message_thread_id,"editForumTopic");return this.api.editForumTopic(X.chat.id,G,$,w)}closeForumTopic($){let w=V(this.msg,"closeForumTopic"),X=V(w.message_thread_id,"closeForumTopic");return this.api.closeForumTopic(w.chat.id,X,$)}reopenForumTopic($){let w=V(this.msg,"reopenForumTopic"),X=V(w.message_thread_id,"reopenForumTopic");return this.api.reopenForumTopic(w.chat.id,X,$)}deleteForumTopic($){let w=V(this.msg,"deleteForumTopic"),X=V(w.message_thread_id,"deleteForumTopic");return this.api.deleteForumTopic(w.chat.id,X,$)}unpinAllForumTopicMessages($){let w=V(this.msg,"unpinAllForumTopicMessages"),X=V(w.message_thread_id,"unpinAllForumTopicMessages");return this.api.unpinAllForumTopicMessages(w.chat.id,X,$)}editGeneralForumTopic($,w){return this.api.editGeneralForumTopic(V(this.chatId,"editGeneralForumTopic"),$,w)}closeGeneralForumTopic($){return this.api.closeGeneralForumTopic(V(this.chatId,"closeGeneralForumTopic"),$)}reopenGeneralForumTopic($){return this.api.reopenGeneralForumTopic(V(this.chatId,"reopenGeneralForumTopic"),$)}hideGeneralForumTopic($){return this.api.hideGeneralForumTopic(V(this.chatId,"hideGeneralForumTopic"),$)}unhideGeneralForumTopic($){return this.api.unhideGeneralForumTopic(V(this.chatId,"unhideGeneralForumTopic"),$)}unpinAllGeneralForumTopicMessages($){return this.api.unpinAllGeneralForumTopicMessages(V(this.chatId,"unpinAllGeneralForumTopicMessages"),$)}answerCallbackQuery($,w){return this.api.answerCallbackQuery(V(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,X){var G,E,J,W,Y;let A=this.inlineMessageId;return A!==void 0?this.api.editMessageTextInline(A,$,{business_connection_id:this.businessConnectionId,...w},X):this.api.editMessageText(V(this.chatId,"editMessageText"),V((W=(E=(G=this.msg)===null||G===void 0?void 0:G.message_id)!==null&&E!==void 0?E:(J=this.messageReaction)===null||J===void 0?void 0:J.message_id)!==null&&W!==void 0?W:(Y=this.messageReactionCount)===null||Y===void 0?void 0:Y.message_id,"editMessageText"),$,{business_connection_id:this.businessConnectionId,...w},X)}editMessageCaption($,w){var X,G,E,J,W;let Y=this.inlineMessageId;return Y!==void 0?this.api.editMessageCaptionInline(Y,{business_connection_id:this.businessConnectionId,...$},w):this.api.editMessageCaption(V(this.chatId,"editMessageCaption"),V((J=(G=(X=this.msg)===null||X===void 0?void 0:X.message_id)!==null&&G!==void 0?G:(E=this.messageReaction)===null||E===void 0?void 0:E.message_id)!==null&&J!==void 0?J:(W=this.messageReactionCount)===null||W===void 0?void 0:W.message_id,"editMessageCaption"),{business_connection_id:this.businessConnectionId,...$},w)}editMessageMedia($,w,X){var G,E,J,W,Y;let A=this.inlineMessageId;return A!==void 0?this.api.editMessageMediaInline(A,$,{business_connection_id:this.businessConnectionId,...w},X):this.api.editMessageMedia(V(this.chatId,"editMessageMedia"),V((W=(E=(G=this.msg)===null||G===void 0?void 0:G.message_id)!==null&&E!==void 0?E:(J=this.messageReaction)===null||J===void 0?void 0:J.message_id)!==null&&W!==void 0?W:(Y=this.messageReactionCount)===null||Y===void 0?void 0:Y.message_id,"editMessageMedia"),$,{business_connection_id:this.businessConnectionId,...w},X)}editMessageReplyMarkup($,w){var X,G,E,J,W;let Y=this.inlineMessageId;return Y!==void 0?this.api.editMessageReplyMarkupInline(Y,{business_connection_id:this.businessConnectionId,...$},w):this.api.editMessageReplyMarkup(V(this.chatId,"editMessageReplyMarkup"),V((J=(G=(X=this.msg)===null||X===void 0?void 0:X.message_id)!==null&&G!==void 0?G:(E=this.messageReaction)===null||E===void 0?void 0:E.message_id)!==null&&J!==void 0?J:(W=this.messageReactionCount)===null||W===void 0?void 0:W.message_id,"editMessageReplyMarkup"),{business_connection_id:this.businessConnectionId,...$},w)}stopPoll($,w){var X,G,E,J,W;return this.api.stopPoll(V(this.chatId,"stopPoll"),V((J=(G=(X=this.msg)===null||X===void 0?void 0:X.message_id)!==null&&G!==void 0?G:(E=this.messageReaction)===null||E===void 0?void 0:E.message_id)!==null&&J!==void 0?J:(W=this.messageReactionCount)===null||W===void 0?void 0:W.message_id,"stopPoll"),{business_connection_id:this.businessConnectionId,...$},w)}deleteMessage($){var w,X,G,E,J;return this.api.deleteMessage(V(this.chatId,"deleteMessage"),V((E=(X=(w=this.msg)===null||w===void 0?void 0:w.message_id)!==null&&X!==void 0?X:(G=this.messageReaction)===null||G===void 0?void 0:G.message_id)!==null&&E!==void 0?E:(J=this.messageReactionCount)===null||J===void 0?void 0:J.message_id,"deleteMessage"),$)}deleteMessages($,w){return this.api.deleteMessages(V(this.chatId,"deleteMessages"),$,w)}deleteBusinessMessages($,w){return this.api.deleteBusinessMessages(V(this.businessConnectionId,"deleteBusinessMessages"),$,w)}setBusinessAccountName($,w,X){return this.api.setBusinessAccountName(V(this.businessConnectionId,"setBusinessAccountName"),$,w,X)}setBusinessAccountUsername($,w){return this.api.setBusinessAccountUsername(V(this.businessConnectionId,"setBusinessAccountUsername"),$,w)}setBusinessAccountBio($,w){return this.api.setBusinessAccountBio(V(this.businessConnectionId,"setBusinessAccountBio"),$,w)}setBusinessAccountProfilePhoto($,w,X){return this.api.setBusinessAccountProfilePhoto(V(this.businessConnectionId,"setBusinessAccountProfilePhoto"),$,w,X)}removeBusinessAccountProfilePhoto($,w){return this.api.removeBusinessAccountProfilePhoto(V(this.businessConnectionId,"removeBusinessAccountProfilePhoto"),$,w)}setBusinessAccountGiftSettings($,w,X){return this.api.setBusinessAccountGiftSettings(V(this.businessConnectionId,"setBusinessAccountGiftSettings"),$,w,X)}getBusinessAccountStarBalance($){return this.api.getBusinessAccountStarBalance(V(this.businessConnectionId,"getBusinessAccountStarBalance"),$)}transferBusinessAccountStars($,w){return this.api.transferBusinessAccountStars(V(this.businessConnectionId,"transferBusinessAccountStars"),$,w)}getBusinessAccountGifts($,w){return this.api.getBusinessAccountGifts(V(this.businessConnectionId,"getBusinessAccountGifts"),$,w)}convertGiftToStars($,w){return this.api.convertGiftToStars(V(this.businessConnectionId,"convertGiftToStars"),$,w)}upgradeGift($,w,X){return this.api.upgradeGift(V(this.businessConnectionId,"upgradeGift"),$,w,X)}transferGift($,w,X,G){return this.api.transferGift(V(this.businessConnectionId,"transferGift"),$,w,X,G)}postStory($,w,X,G){return this.api.postStory(V(this.businessConnectionId,"postStory"),$,w,X,G)}repostStory($,w,X){var G;let E=V((G=this.msg)===null||G===void 0?void 0:G.story,"repostStory");return this.api.repostStory(V(this.businessConnectionId,"repostStory"),E.chat.id,E.id,$,w,X)}editStory($,w,X,G){return this.api.editStory(V(this.businessConnectionId,"editStory"),$,w,X,G)}deleteStory($,w){return this.api.deleteStory(V(this.businessConnectionId,"deleteStory"),$,w)}replyWithSticker($,w,X){var G;let E=this.msg;return this.api.sendSticker(V(this.chatId,"sendSticker"),$,{business_connection_id:this.businessConnectionId,...(E===null||E===void 0?void 0:E.is_topic_message)?{message_thread_id:E.message_thread_id}:{},direct_messages_topic_id:(G=E===null||E===void 0?void 0:E.direct_messages_topic)===null||G===void 0?void 0:G.topic_id,...w},X)}getCustomEmojiStickers($){var w,X;return this.api.getCustomEmojiStickers(((X=(w=this.msg)===null||w===void 0?void 0:w.entities)!==null&&X!==void 0?X:[]).filter((G)=>G.type==="custom_emoji").map((G)=>G.custom_emoji_id),$)}replyWithGift($,w,X){return this.api.sendGift(V(this.from,"sendGift").id,$,w,X)}giftPremiumSubscription($,w,X,G){return this.api.giftPremiumSubscription(V(this.from,"giftPremiumSubscription").id,$,w,X,G)}replyWithGiftToChannel($,w,X){return this.api.sendGiftToChannel(V(this.chat,"sendGift").id,$,w,X)}answerInlineQuery($,w,X){return this.api.answerInlineQuery(V(this.inlineQuery,"answerInlineQuery").id,$,w,X)}savePreparedInlineMessage($,w,X){return this.api.savePreparedInlineMessage(V(this.from,"savePreparedInlineMessage").id,$,w,X)}replyWithInvoice($,w,X,G,E,J,W){var Y;let A=this.msg;return this.api.sendInvoice(V(this.chatId,"sendInvoice"),$,w,X,G,E,{...(A===null||A===void 0?void 0:A.is_topic_message)?{message_thread_id:A.message_thread_id}:{},direct_messages_topic_id:(Y=A===null||A===void 0?void 0:A.direct_messages_topic)===null||Y===void 0?void 0:Y.topic_id,...J},W)}answerShippingQuery($,w,X){return this.api.answerShippingQuery(V(this.shippingQuery,"answerShippingQuery").id,$,w,X)}answerPreCheckoutQuery($,w,X){return this.api.answerPreCheckoutQuery(V(this.preCheckoutQuery,"answerPreCheckoutQuery").id,$,typeof w==="string"?{error_message:w}:w,X)}refundStarPayment($){var w;return this.api.refundStarPayment(V(this.from,"refundStarPayment").id,V((w=this.msg)===null||w===void 0?void 0:w.successful_payment,"refundStarPayment").telegram_payment_charge_id,$)}editUserStarSubscription($,w,X){return this.api.editUserStarSubscription(V(this.from,"editUserStarSubscription").id,$,w,X)}verifyUser($,w){return this.api.verifyUser(V(this.from,"verifyUser").id,$,w)}verifyChat($,w){return this.api.verifyChat(V(this.chatId,"verifyChat"),$,w)}removeUserVerification($){return this.api.removeUserVerification(V(this.from,"removeUserVerification").id,$)}removeChatVerification($){return this.api.removeChatVerification(V(this.chatId,"removeChatVerification"),$)}readBusinessMessage($){return this.api.readBusinessMessage(V(this.businessConnectionId,"readBusinessMessage"),V(this.chatId,"readBusinessMessage"),V(this.msgId,"readBusinessMessage"),$)}setPassportDataErrors($,w){return this.api.setPassportDataErrors(V(this.from,"setPassportDataErrors").id,$,w)}replyWithGame($,w,X){let G=this.msg;return this.api.sendGame(V(this.chatId,"sendGame"),$,{business_connection_id:this.businessConnectionId,...(G===null||G===void 0?void 0:G.is_topic_message)?{message_thread_id:G.message_thread_id}:{},...w},X)}}tN.Context=m$;m$.has=r1;function V($,w){if($===void 0)throw Error(`Missing information for API call to ${w}`);return $}function GX($){return m4($).map((w)=>typeof w==="string"?(X)=>X===w?w:null:(X)=>X.match(w))}function EX($,w,X){for(let G of X){let E=G(w);if(E)return $.match=E,!0}return!1}function m4($){return Array.isArray($)?$:[$]}});var g9=b((aN)=>{Object.defineProperty(aN,"__esModule",{value:!0});aN.Composer=aN.BotError=void 0;aN.run=sN;var P1=n4();class y9 extends Error{constructor($,w){super(Iq($));if(this.error=$,this.ctx=w,this.name="BotError",$ instanceof Error)this.stack=$.stack}}aN.BotError=y9;function Iq($){let w;if($ instanceof Error)w=`${$.name} in middleware: ${$.message}`;else{let X=typeof $;switch(w=`Non-error value of type ${X} thrown in middleware`,X){case"bigint":case"boolean":case"number":case"symbol":w+=`: ${$}`;break;case"string":w+=`: ${String($).substring(0,50)}`;break;default:w+="!";break}}return w}function I6($){return typeof $==="function"?$:(w,X)=>$.middleware()(w,X)}function lN($,w){return async(X,G)=>{let E=!1;await $(X,async()=>{if(E)throw Error("`next` already called before!");else E=!0;await w(X,G)})}}function x9($,w){return w()}var jq=()=>Promise.resolve();async function sN($,w){await $(w,jq)}class JX{constructor(...$){this.handler=$.length===0?x9:$.map(I6).reduce(lN)}middleware(){return this.handler}use(...$){let w=new JX(...$);return this.handler=lN(this.handler,I6(w)),w}on($,...w){return this.filter(P1.Context.has.filterQuery($),...w)}hears($,...w){return this.filter(P1.Context.has.text($),...w)}command($,...w){return this.filter(P1.Context.has.command($),...w)}reaction($,...w){return this.filter(P1.Context.has.reaction($),...w)}chatType($,...w){return this.filter(P1.Context.has.chatType($),...w)}callbackQuery($,...w){return this.filter(P1.Context.has.callbackQuery($),...w)}gameQuery($,...w){return this.filter(P1.Context.has.gameQuery($),...w)}inlineQuery($,...w){return this.filter(P1.Context.has.inlineQuery($),...w)}chosenInlineResult($,...w){return this.filter(P1.Context.has.chosenInlineResult($),...w)}preCheckoutQuery($,...w){return this.filter(P1.Context.has.preCheckoutQuery($),...w)}shippingQuery($,...w){return this.filter(P1.Context.has.shippingQuery($),...w)}filter($,...w){let X=new JX(...w);return this.branch($,X,x9),X}drop($,...w){return this.filter(async(X)=>!await $(X),...w)}fork(...$){let w=new JX(...$),X=I6(w);return this.use((G,E)=>Promise.all([E(),sN(X,G)])),w}lazy($){return this.use(async(w,X)=>{let G=await $(w),E=Array.isArray(G)?G:[G];await I6(new JX(...E))(w,X)})}route($,w,X=x9){return this.lazy(async(G)=>{var E;let J=await $(G);return(E=J===void 0||!w[J]?X:w[J])!==null&&E!==void 0?E:[]})}branch($,w,X){return this.lazy(async(G)=>await $(G)?w:X)}errorBoundary($,...w){let X=new JX(...w),G=I6(X);return this.use(async(E,J)=>{let W=!1,Y=()=>(W=!0,Promise.resolve());try{await G(E,Y)}catch(A){W=!1,await $(new y9(A,E),Y)}if(W)await J()}),X}}aN.Composer=JX});var wH=b((va,$H)=>{var sX=1000,aX=sX*60,eX=aX*60,WX=eX*24,Sq=WX*7,Zq=WX*365.25;$H.exports=function($,w){w=w||{};var X=typeof $;if(X==="string"&&$.length>0)return bq($);else if(X==="number"&&isFinite($))return w.long?Cq($):kq($);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify($))};function bq($){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 X=parseFloat(w[1]),G=(w[2]||"ms").toLowerCase();switch(G){case"years":case"year":case"yrs":case"yr":case"y":return X*Zq;case"weeks":case"week":case"w":return X*Sq;case"days":case"day":case"d":return X*WX;case"hours":case"hour":case"hrs":case"hr":case"h":return X*eX;case"minutes":case"minute":case"mins":case"min":case"m":return X*aX;case"seconds":case"second":case"secs":case"sec":case"s":return X*sX;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return X;default:return}}function kq($){var w=Math.abs($);if(w>=WX)return Math.round($/WX)+"d";if(w>=eX)return Math.round($/eX)+"h";if(w>=aX)return Math.round($/aX)+"m";if(w>=sX)return Math.round($/sX)+"s";return $+"ms"}function Cq($){var w=Math.abs($);if(w>=WX)return p4($,w,WX,"day");if(w>=eX)return p4($,w,eX,"hour");if(w>=aX)return p4($,w,aX,"minute");if(w>=sX)return p4($,w,sX,"second");return $+" ms"}function p4($,w,X,G){var E=w>=X*1.5;return Math.round($/X)+" "+G+(E?"s":"")}});var h9=b((_a,XH)=>{function vq($){X.debug=X,X.default=X,X.coerce=A,X.disable=W,X.enable=E,X.enabled=Y,X.humanize=wH(),X.destroy=D,Object.keys($).forEach((U)=>{X[U]=$[U]}),X.names=[],X.skips=[],X.formatters={};function w(U){let N=0;for(let H=0;H<U.length;H++)N=(N<<5)-N+U.charCodeAt(H),N|=0;return X.colors[Math.abs(N)%X.colors.length]}X.selectColor=w;function X(U){let N,H=null,L,F;function M(...z){if(!M.enabled)return;let Q=M,R=Number(new Date),T=R-(N||R);if(Q.diff=T,Q.prev=N,Q.curr=R,N=R,z[0]=X.coerce(z[0]),typeof z[0]!=="string")z.unshift("%O");let v=0;z[0]=z[0].replace(/%([a-zA-Z%])/g,(k,m)=>{if(k==="%%")return"%";v++;let F0=X.formatters[m];if(typeof F0==="function"){let b0=z[v];k=F0.call(Q,b0),z.splice(v,1),v--}return k}),X.formatArgs.call(Q,z),(Q.log||X.log).apply(Q,z)}if(M.namespace=U,M.useColors=X.useColors(),M.color=X.selectColor(U),M.extend=G,M.destroy=X.destroy,Object.defineProperty(M,"enabled",{enumerable:!0,configurable:!1,get:()=>{if(H!==null)return H;if(L!==X.namespaces)L=X.namespaces,F=X.enabled(U);return F},set:(z)=>{H=z}}),typeof X.init==="function")X.init(M);return M}function G(U,N){let H=X(this.namespace+(typeof N>"u"?":":N)+U);return H.log=this.log,H}function E(U){X.save(U),X.namespaces=U,X.names=[],X.skips=[];let N=(typeof U==="string"?U:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let H of N)if(H[0]==="-")X.skips.push(H.slice(1));else X.names.push(H)}function J(U,N){let H=0,L=0,F=-1,M=0;while(H<U.length)if(L<N.length&&(N[L]===U[H]||N[L]==="*"))if(N[L]==="*")F=L,M=H,L++;else H++,L++;else if(F!==-1)L=F+1,M++,H=M;else return!1;while(L<N.length&&N[L]==="*")L++;return L===N.length}function W(){let U=[...X.names,...X.skips.map((N)=>"-"+N)].join(",");return X.enable(""),U}function Y(U){for(let N of X.skips)if(J(U,N))return!1;for(let N of X.names)if(J(U,N))return!0;return!1}function A(U){if(U instanceof Error)return U.stack||U.message;return U}function D(){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 X.enable(X.load()),X}XH.exports=vq});var EH=b((GH,r4)=>{GH.formatArgs=fq;GH.save=xq;GH.load=yq;GH.useColors=_q;GH.storage=gq();GH.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`.")}})();GH.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 _q(){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 fq($){if($[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+$[0]+(this.useColors?"%c ":" ")+"+"+r4.exports.humanize(this.diff),!this.useColors)return;let w="color: "+this.color;$.splice(1,0,w,"color: inherit");let X=0,G=0;$[0].replace(/%[a-zA-Z%]/g,(E)=>{if(E==="%%")return;if(X++,E==="%c")G=X}),$.splice(G,0,w)}GH.log=console.debug||console.log||(()=>{});function xq($){try{if($)GH.storage.setItem("debug",$);else GH.storage.removeItem("debug")}catch(w){}}function yq(){let $;try{$=GH.storage.getItem("debug")||GH.storage.getItem("DEBUG")}catch(w){}if(!$&&typeof process<"u"&&"env"in process)$=process.env.DEBUG;return $}function gq(){try{return localStorage}catch($){}}r4.exports=h9()(GH);var{formatters:hq}=r4.exports;hq.j=function($){try{return JSON.stringify($)}catch(w){return"[UnexpectedJSONParseError]: "+w.message}}});var WH={};e1(WH,{default:()=>aq,createSupportsColor:()=>u9});import c9 from"process";import oq from"os";import JH from"tty";function W1($,w=globalThis.Deno?globalThis.Deno.args:c9.argv){let X=$.startsWith("-")?"":$.length===1?"-":"--",G=w.indexOf(X+$),E=w.indexOf("--");return G!==-1&&(E===-1||G<E)}function tq(){if(!("FORCE_COLOR"in x0))return;if(x0.FORCE_COLOR==="true")return 1;if(x0.FORCE_COLOR==="false")return 0;if(x0.FORCE_COLOR.length===0)return 1;let $=Math.min(Number.parseInt(x0.FORCE_COLOR,10),3);if(![0,1,2,3].includes($))return;return $}function dq($){if($===0)return!1;return{level:$,hasBasic:!0,has256:$>=2,has16m:$>=3}}function lq($,{streamIsTTY:w,sniffFlags:X=!0}={}){let G=tq();if(G!==void 0)i4=G;let E=X?i4:G;if(E===0)return 0;if(X){if(W1("color=16m")||W1("color=full")||W1("color=truecolor"))return 3;if(W1("color=256"))return 2}if("TF_BUILD"in x0&&"AGENT_NAME"in x0)return 1;if($&&!w&&E===void 0)return 0;let J=E||0;if(x0.TERM==="dumb")return J;if(c9.platform==="win32"){let W=oq.release().split(".");if(Number(W[0])>=10&&Number(W[2])>=10586)return Number(W[2])>=14931?3:2;return 1}if("CI"in x0){if(["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some((W)=>(W in x0)))return 3;if(["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some((W)=>(W in x0))||x0.CI_NAME==="codeship")return 1;return J}if("TEAMCITY_VERSION"in x0)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(x0.TEAMCITY_VERSION)?1:0;if(x0.COLORTERM==="truecolor")return 3;if(x0.TERM==="xterm-kitty")return 3;if(x0.TERM==="xterm-ghostty")return 3;if(x0.TERM==="wezterm")return 3;if("TERM_PROGRAM"in x0){let W=Number.parseInt((x0.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(x0.TERM_PROGRAM){case"iTerm.app":return W>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(x0.TERM))return 2;if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(x0.TERM))return 1;if("COLORTERM"in x0)return 1;return J}function u9($,w={}){let X=lq($,{streamIsTTY:$&&$.isTTY,...w});return dq(X)}var x0,i4,sq,aq;var YH=B(()=>{({env:x0}=c9);if(W1("no-color")||W1("no-colors")||W1("color=false")||W1("color=never"))i4=0;else if(W1("color")||W1("colors")||W1("color=true")||W1("color=always"))i4=1;sq={stdout:u9({isTTY:JH.isatty(1)}),stderr:u9({isTTY:JH.isatty(2)})},aq=sq});var OH=b((DH,t4)=>{var eq=B$("tty"),o4=B$("util");DH.init=WS;DH.log=GS;DH.formatArgs=wS;DH.save=ES;DH.load=JS;DH.useColors=$S;DH.destroy=o4.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");DH.colors=[6,2,3,4,5,1];try{let $=(YH(),HD(WH));if($&&($.stderr||$).level>=2)DH.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($){}DH.inspectOpts=Object.keys(process.env).filter(($)=>{return/^debug_/i.test($)}).reduce(($,w)=>{let X=w.substring(6).toLowerCase().replace(/_([a-z])/g,(E,J)=>{return J.toUpperCase()}),G=process.env[w];if(/^(yes|on|true|enabled)$/i.test(G))G=!0;else if(/^(no|off|false|disabled)$/i.test(G))G=!1;else if(G==="null")G=null;else G=Number(G);return $[X]=G,$},{});function $S(){return"colors"in DH.inspectOpts?Boolean(DH.inspectOpts.colors):eq.isatty(process.stderr.fd)}function wS($){let{namespace:w,useColors:X}=this;if(X){let G=this.color,E="\x1B[3"+(G<8?G:"8;5;"+G),J=` ${E};1m${w} \x1B[0m`;$[0]=J+$[0].split(`
|
|
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:$});GX(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;pJ(this.proc.stdin);let $=setTimeout(()=>this.proc?.kill(),j2);try{await this.proc.exited}finally{clearTimeout($)}this.proc=null,this.done=!0,this.resolveNext?.(),this.resolveNext=null}}function R2(){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 iJ({...w,runtimeSessionId:$})},async stop(){}}}async function _8($,w){let E=new iJ($);return await E.start($,w),E}var $e,j2=8000;var dJ=R(()=>{X1();p$();tJ();$e=Z0("agent-runtime:codex");JX("codex",R2)});function B2(){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 v8(){return Bun.which("claude")??null}function Q2($){return/auth|api.key|invalid.key|401|unauthorized/i.test($)}function TY($){if(!$)return"";if(typeof $==="string")return $;return $.map((w)=>w.text??w.thinking??"").join("")}class f8{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:B2()}),this.proc.stdout)XX(this.proc.stdout,(E)=>{try{this.handleStdoutLine(JSON.parse(E))}catch{}}).then(()=>this.handleEof());if(this.proc.stderr)XX(this.proc.stderr,(E)=>{if(this.stderrRing.push(E),this.stderrRing.length>T2)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:TY($.content),isError:$.is_error??!1}});return}if($.type==="control_request"||$.type==="permission_request"){let w=$.id??i(),E=$.name??TY($.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(Q2(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"};GX(this.proc?.stdin,new TextEncoder().encode(`${JSON.stringify(X)}
|
|
371
|
+
`))}async send($){let w={type:"user",message:{role:"user",content:$}};GX(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;pJ(this.proc.stdin);let $=setTimeout(()=>this.proc?.kill(),z2);try{await this.proc.exited}finally{clearTimeout($)}this.proc=null,this.done=!0,this.resolveNext?.(),this.resolveNext=null}}function I2(){return{name:"claude",async preflight(){let $=v8();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=v8();if(!w)throw Error("claude CLI not found on PATH");let E=new f8($,w);return await E.start($),E},async resumeSession($,w){let E=v8();if(!E)throw Error("claude CLI not found on PATH");let X=new f8({...w,runtimeSessionId:$},E);return await X.start({...w,runtimeSessionId:$}),X},async stop(){}}}var Je,z2=8000,T2=200;var BY=R(()=>{X1();p$();tJ();Je=Z0("agent-runtime:claude");JX("claude",I2)});var QY={};Ww(QY,{startCodexSession:()=>_8,registerBackend:()=>JX,listRegisteredBackends:()=>RY,createBackend:()=>oJ});var lJ=R(()=>{dJ();tJ();BY();dJ()});async function IY($){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 x8($,w){await x().update(X$).set({mode:w,updated_at:new Date}).where(V(X$.id,$))}async function KY($,w){await x().update(X$).set({working_dir:w,updated_at:new Date}).where(V(X$.id,$))}async function AX($){await x().insert(S8).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 y8($){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 DX($){return x().query.gateway_sessions.findMany({where:V(x$.chat_id,$),orderBy:[x0(x$.updated_at)],limit:20})}async function ZG($,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 VY($){let w=x(),E=i();return await w.insert(EX).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(EX.id,E)})}async function g8($){let w=x();if($.length===26)return w.query.bridge_permissions.findFirst({where:V(EX.id,$)});return(await w.query.bridge_permissions.findMany({limit:20,orderBy:[x0(EX.created_at)]})).find((X)=>X.id.endsWith($))}async function CG($){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 PY($,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 qY($,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 u8($=8){return(await x().query.tasks.findMany({limit:$,orderBy:[x0(r.updated_at)]})).filter((X)=>!["done","cancelled"].includes(X.status))}async function SY($,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 sJ($){return x().query.jobs.findFirst({where:V(I0.name,$)})}async function h8($=10){return x().query.jobs.findMany({limit:$,orderBy:[x0(I0.updated_at)]})}async function kY(){return x().query.bridge_chats.findMany({where:S0(V(X$.authorized,!0),KJ(X$.platform,["telegram","slack"])),orderBy:[x0(X$.updated_at)]})}async function bY($,w){await x().update(x$).set({task_id:w,updated_at:new Date}).where(V(x$.id,$))}var _G=R(()=>{X1();y$();d$();i$()});async function ZY($,w,E,X){let G=fG.get($.session.id);if(!G||!G.alive())G=await V2($,w),fG.set($.session.id,G);else if($.session.backend==="codex")await G.send(w);else await G.send(w);return await P2($,G,E,X)}async function V2($,w){let E=$.session.backend,X=$.session.runtime_session_id??void 0;if(E==="codex"){let{startCodexSession:A}=await Promise.resolve().then(() => (dJ(),zY));return await A({cwd:$.session.cwd,model:$.session.model??void 0,runtimeSessionId:X},w)}let G=oJ(E);if(X)try{return await G.resumeSession(X,{cwd:$.session.cwd,model:$.session.model??void 0,runtimeSessionId:X})}catch(A){vG.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 P2($,w,E,X){let G="",J,A=q2($.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 VY({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
|
+
<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 q2($,w){let E=!1,X=null;function G(){if(X)clearTimeout(X);if(E)return;X=setTimeout(async()=>{vG.warn("Idle timeout \u2014 closing agent session",{sessionId:$}),await w.close().catch(()=>{}),fG.delete($),await a1($,{status:"error",last_error:"Idle timeout",last_activity_at:new Date})},K2)}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 CY($){let w=fG.get($);if(w)fG.delete($),await w.close().catch(()=>{})}async function _Y(){let{listRegisteredBackends:$,createBackend:w}=await Promise.resolve().then(() => (lJ(),QY));for(let E of $())try{let G=await w(E).preflight();if(!G.ok)vG.warn(`Agent backend preflight failed: ${E}`,{error:G.error});else vG.info(`Agent backend ready: ${E}`)}catch(X){vG.warn(`Agent backend preflight error: ${E}`,{err:X})}}var vG,K2=600000,fG;var vY=R(()=>{p$();lJ();_G();vG=Z0("gateway:runner"),fG=new Map});class c8{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 n8($){return $.replace(S2,(w)=>`${"*".repeat(w.length-4)}${w.slice(-4)}`)}var S2;var fY=R(()=>{S2=/\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 uY($){if($.endsWith("codex"))return"codex";if($.endsWith("cursor"))return"cursor";return"claude"}function xY($){if($==="running")return"\u26A1";if($==="error")return"\u274C";if($==="stopped")return"\u26D4";return"\uD83D\uDCA4"}function yY($){if($==="critical")return"\uD83D\uDD34";if($==="high")return"\uD83D\uDFE0";if($==="normal")return"\uD83D\uDFE1";return"\u26AA"}function gY($){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 k2($){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 hY($){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:k2($.currentMode??"direct")};if(X==="/status"){let J=await u8(5),A=await DX($.chatKey),D=await h8(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} ${xY(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 x8($.chatKey,J),{text:`Mode updated to ${J}`,mode:J}}if(X==="/cwd"){if(!G)return{text:"Usage: /cwd <absolute-path>"};await KY($.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 x8($.chatKey,J),{text:`Agent mode set to ${J}`,mode:J}}if(X==="/tasks"){let J=await u8();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(`${gY(D.status)} ${yY(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 CG(G);if(!J)return{text:`Task not found: ${G}`};let A=[`<b>${J.title}</b>`,`ID: <code>${J.id}</code>`,`Status: ${gY(J.status)} ${J.status}`,`Priority: ${yY(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 g8(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 CG(J);if(!W)return{text:`No task or permission found for ${J}`};return await PY(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 g8(J);if(N)return{text:`Permission ${N.id.slice(-6)} denial queued \u2014 use the button or wait for agent context.`};let W=await CG(J);if(!W)return{text:`No task or permission found for ${J}`};return await qY(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 CG(J);if(!D)return{text:`Task not found: ${J}`};let W=(await DX($.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 bY(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 h8();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 sJ(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 SY(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 DX($.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}${xY(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=uY($.currentMode??"agent:claude"),N=await y8({chatKey:$.chatKey,backend:D,cwd:$.currentWorkingDir??void 0,mode:$.currentMode??`agent:${D}`,title:`Session ${i().slice(-6)}`});return await ZG($.chatKey,N.id),{text:`Created and activated ${D} session [${N.id.slice(-6)}]`}}if(J==="list"){let D=await DX($.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 DX($.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 ZG($.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 ZG($.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 cY($){let w=await jw($.chatKey),E=uY($.mode);if(w&&w.backend===E&&w.status!=="stopped")return w;let X=await y8({chatKey:$.chatKey,backend:E,cwd:$.cwd??void 0,mode:$.mode,title:`Session ${i().slice(-6)}`});return await ZG($.chatKey,X.id),X}var nY=R(()=>{X1();nw();_G()});class m8{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 aJ{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
|
+
\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(`
|
|
358
388
|
`).join(`
|
|
359
|
-
`+J),$.push(
|
|
360
|
-
`)}function
|
|
361
|
-
`).map((w)=>w.trim()).join(" ")};
|
|
362
|
-
`);let
|
|
389
|
+
`+J),$.push(G+"m+"+WA.exports.humanize(this.diff)+"\x1B[0m")}else $[0]=CS()+w+" "+$[0]}function CS(){if(VH.inspectOpts.hideDate)return"";return new Date().toISOString()+" "}function _S(...$){return process.stderr.write(NA.formatWithOptions(VH.inspectOpts,...$)+`
|
|
390
|
+
`)}function vS($){if($)process.env.DEBUG=$;else delete process.env.DEBUG}function fS(){return process.env.DEBUG}function xS($){$.inspectOpts={};let w=Object.keys(VH.inspectOpts);for(let E=0;E<w.length;E++)$.inspectOpts[w[E]]=VH.inspectOpts[w[E]]}WA.exports=e8()(VH);var{formatters:KH}=WA.exports;KH.o=function($){return this.inspectOpts.colors=this.useColors,NA.inspect($,this.inspectOpts).split(`
|
|
391
|
+
`).map((w)=>w.trim()).join(" ")};KH.O=function($){return this.inspectOpts.colors=this.useColors,NA.inspect($,this.inspectOpts)}});var SH=Z((te,EN)=>{if(typeof process>"u"||process.type==="renderer"||!1||process.__nwjs)EN.exports=TH();else EN.exports=qH()});var mw=Z((XN)=>{Object.defineProperty(XN,"__esModule",{value:!0});XN.defaultAdapter=XN.itrToStream=XN.debug=void 0;XN.baseFetchConfig=sS;var rS=V$("http"),pS=V$("https"),oS=V$("stream"),tS=SH();Object.defineProperty(XN,"debug",{enumerable:!0,get:function(){return tS.debug}});var iS=($)=>oS.Readable.from($,{objectMode:!1});XN.itrToStream=iS;var dS=new Map,lS=new Map;function kH($,w,E){let X=$.get(w);if(X===void 0)X=E(),$.set(w,X);return X}function sS($){if($.startsWith("https:"))return{compress:!0,agent:kH(lS,$,()=>new pS.Agent({keepAlive:!0}))};else if($.startsWith("http:"))return{agent:kH(dS,$,()=>new rS.Agent({keepAlive:!0}))};else return{}}XN.defaultAdapter="express"});var OA=Z((CH)=>{Object.defineProperty(CH,"__esModule",{value:!0});CH.HttpError=CH.GrammyError=void 0;CH.toGrammyError=wk;CH.toHttpError=Xk;var $k=mw(),ZH=(0,$k.debug)("grammy:warn");class GN 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:{}}}CH.GrammyError=GN;function wk($,w,E){switch($.error_code){case 401:ZH("Error 401 means that your bot token is wrong, talk to https://t.me/BotFather to check it.");break;case 409:ZH("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 GN(`Call to '${w}' failed!`,$,w,E)}class JN extends Error{constructor($,w){super($);this.error=w,this.name="HttpError"}}CH.HttpError=JN;function Ek($){return typeof $==="object"&&$!==null&&"status"in $&&"statusText"in $}function Xk($,w,E){let X=`Network request for '${$}' failed!`;if(Ek(E))X+=` (${E.status}: ${E.statusText})`;if(w&&E instanceof Error)X+=` ${E.message}`;return new JN(X,E)}});var Dk={};var xH=Z((Mw)=>{var Nk=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]}),Wk=Mw&&Mw.__exportStar||function($,w){for(var E in $)if(E!=="default"&&!Object.prototype.hasOwnProperty.call(w,E))Nk(w,$,E)};Object.defineProperty(Mw,"__esModule",{value:!0});Mw.InputFile=void 0;var vH=V$("fs"),Ok=V$("node-fetch"),UA=V$("path"),Uk=mw(),Yk=(0,Uk.debug)("grammy:warn");Wk(kO(Dk),Mw);class AN{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:")))Yk(`InputFile received the local file path '${$}' that looks like a URL. Is this a mistake?`)}guessFilename($){if(typeof $==="string")return(0,UA.basename)($);if("url"in $)return(0,UA.basename)($.url);if(!($ instanceof URL))return;if($.pathname!=="/"){let w=(0,UA.basename)($.pathname);if(w)return w}return(0,UA.basename)($.hostname)}async toRaw(){if(this.consumed)throw Error("Cannot reuse InputFile data source!");let $=this.fileData;if(typeof $==="string")return(0,vH.createReadStream)($);if($ instanceof URL)return $.protocol==="file"?(0,vH.createReadStream)($.pathname):fH($);if("url"in $)return fH($.url);if($ instanceof Uint8Array)return $;if(typeof $==="function")return new AN(await $()).toRaw();return this.consumed=!0,$}toJSON(){throw Error("InputFile instances must be sent via grammY")}}Mw.InputFile=AN;async function*fH($){let{body:w}=await(0,Ok.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 DN=Z((RE)=>{var Hk=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]}),Lk=RE&&RE.__exportStar||function($,w){for(var E in $)if(E!=="default"&&!Object.prototype.hasOwnProperty.call(w,E))Hk(w,$,E)};Object.defineProperty(RE,"__esModule",{value:!0});Lk(xH(),RE)});var hH=Z((uH)=>{Object.defineProperty(uH,"__esModule",{value:!0});uH.requiresFormDataUpload=NN;uH.createJsonPayload=jk;uH.createFormDataPayload=Rk;var Fk=mw(),YA=DN();function NN($){return $ instanceof YA.InputFile||typeof $==="object"&&$!==null&&Object.values($).some((w)=>Array.isArray(w)?w.some(NN):w instanceof YA.InputFile||NN(w))}function yH($){return JSON.stringify($,(w,E)=>E!==null&&E!==void 0?E:void 0)}function jk($){return{method:"POST",headers:{"content-type":"application/json",connection:"keep-alive"},body:yH($)}}async function*Mk($,w){try{yield*$}catch(E){w(E)}}function Rk($,w){let E=zk(),X=Tk($,E),G=Mk(X,w),J=(0,Fk.itrToStream)(G);return{method:"POST",headers:{"content-type":`multipart/form-data; boundary=${E}`,connection:"keep-alive"},body:J}}function zk(){return"----------"+gH(32)}function gH($=16){return Array.from(Array($)).map(()=>Math.random().toString(36)[2]||0).join("")}var gG=new TextEncoder;async function*Tk($,w){let E=WN($);yield gG.encode(`--${w}\r
|
|
392
|
+
`);let X=gG.encode(`\r
|
|
363
393
|
--${w}\r
|
|
364
|
-
`),
|
|
394
|
+
`),G=!0;for(let[J,A]of Object.entries($)){if(A==null)continue;if(!G)yield X;yield Bk(J,A instanceof YA.InputFile?A.toJSON():typeof A==="object"?yH(A):A),G=!1}for(let{id:J,origin:A,file:D}of E){if(!G)yield X;yield*Qk(J,A,D),G=!1}yield gG.encode(`\r
|
|
365
395
|
--${w}--\r
|
|
366
|
-
`)}function
|
|
396
|
+
`)}function WN($){if(typeof $!=="object"||$===null)return[];return Object.entries($).flatMap(([w,E])=>{if(Array.isArray(E))return E.flatMap((X)=>WN(X));else if(E instanceof YA.InputFile){let X=gH();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 WN(E)})}function Bk($,w){return gG.encode(`content-disposition:form-data;name="${$}"\r
|
|
367
397
|
\r
|
|
368
|
-
${w}`)}async function*
|
|
398
|
+
${w}`)}async function*Qk($,w,E){let X=E.filename||`${w}.${Ik(w)}`;if(X.includes("\r")||X.includes(`
|
|
369
399
|
`))throw Error(`File paths cannot contain carriage-return (\\r) or newline (\\n) characters! Filename for property '${w}' was:
|
|
370
400
|
"""
|
|
371
|
-
${
|
|
372
|
-
"""`);yield
|
|
401
|
+
${X}
|
|
402
|
+
"""`);yield gG.encode(`content-disposition:form-data;name="${$}";filename=${X}\r
|
|
373
403
|
content-type:application/octet-stream\r
|
|
374
404
|
\r
|
|
375
|
-
`);let
|
|
405
|
+
`);let G=await E.toRaw();if(G instanceof Uint8Array)yield G;else yield*G}function Ik($){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 ON=Z((HA)=>{Object.defineProperty(HA,"__esModule",{value:!0});HA.fetch=HA.AbortController=void 0;var qk=V$("abort-controller");Object.defineProperty(HA,"AbortController",{enumerable:!0,get:function(){return qk.AbortController}});var Sk=V$("node-fetch");Object.defineProperty(HA,"fetch",{enumerable:!0,get:function(){return Sk.default}})});var oH=Z((pH)=>{Object.defineProperty(pH,"__esModule",{value:!0});pH.createRawApi=Ck;var nH=mw(),cH=OA(),LA=hH(),bk=(0,nH.debug)("grammy:core");function Zk($,w){return(E,X,G)=>w($,E,X,G)}class mH{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(bk(`Calling ${L}`),j!==void 0)gk(L,M,j);let z=this.options,B=(0,LA.requiresFormDataUpload)(M);if(this.webhookReplyEnvelope.send!==void 0&&!this.hasUsedWebhookReply&&!B&&z.canUseWebhookReply(L)){this.hasUsedWebhookReply=!0;let K0=(0,LA.createJsonPayload)({...M,method:L});return await this.webhookReplyEnvelope.send(K0.body),{ok:!0,result:!0}}let Q=yk(j),k=fk(Q,z.timeoutSeconds,L),v=xk(Q),C=z.buildUrl(z.apiRoot,this.token,L,z.environment),n=B?(0,LA.createFormDataPayload)(M,(K0)=>v.catch(K0)):(0,LA.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,cH.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:rH.fetch;if(this.options={apiRoot:W,environment:O,buildUrl:(J=w.buildUrl)!==null&&J!==void 0?J:_k,timeoutSeconds:(A=w.timeoutSeconds)!==null&&A!==void 0?A:500,baseFetchConfig:{...(0,nH.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(Zk,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,cH.toGrammyError)(X,$,w)}}function Ck($,w,E){let X=new mH($,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)},...vk},J=new Proxy({},G),A=X.installedTransformers,D={raw:J,installedTransformers:A,use:(...N)=>{return X.use(...N),D}};return D}var _k=($,w,E,X)=>{return`${$}/bot${w}/${X==="test"?"test/":""}${E}`},vk={set(){return!1},defineProperty(){return!1},deleteProperty(){return!1},ownKeys(){return[]}};function fk($,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 xk($){let w=(X)=>{throw X};return{promise:new Promise((X,G)=>{w=(J)=>{G(J),$.abort()}}),catch:w}}function yk($){let w=new rH.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 gk($,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.
|
|
376
406
|
|
|
377
|
-
If you want to prevent such mistakes in the future, consider using TypeScript. https://www.typescriptlang.org/`)}var SH=l9()});var s9=b((CH)=>{Object.defineProperty(CH,"__esModule",{value:!0});CH.Api=void 0;var UZ=bH();class kH{constructor($,w,X){this.token=$,this.options=w;let{raw:G,use:E,installedTransformers:J}=(0,UZ.createRawApi)($,w,X);this.raw=G,this.config={use:E,installedTransformers:()=>J.slice()}}getUpdates($,w){return this.raw.getUpdates({...$},w)}setWebhook($,w,X){return this.raw.setWebhook({url:$,...w},X)}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,X,G){return this.raw.sendMessage({chat_id:$,text:w,...X},G)}sendMessageDraft($,w,X,G,E){return this.raw.sendMessageDraft({chat_id:$,draft_id:w,text:X,...G},E)}forwardMessage($,w,X,G,E){return this.raw.forwardMessage({chat_id:$,from_chat_id:w,message_id:X,...G},E)}forwardMessages($,w,X,G,E){return this.raw.forwardMessages({chat_id:$,from_chat_id:w,message_ids:X,...G},E)}copyMessage($,w,X,G,E){return this.raw.copyMessage({chat_id:$,from_chat_id:w,message_id:X,...G},E)}copyMessages($,w,X,G,E){return this.raw.copyMessages({chat_id:$,from_chat_id:w,message_ids:X,...G},E)}sendPhoto($,w,X,G){return this.raw.sendPhoto({chat_id:$,photo:w,...X},G)}sendAudio($,w,X,G){return this.raw.sendAudio({chat_id:$,audio:w,...X},G)}sendDocument($,w,X,G){return this.raw.sendDocument({chat_id:$,document:w,...X},G)}sendVideo($,w,X,G){return this.raw.sendVideo({chat_id:$,video:w,...X},G)}sendAnimation($,w,X,G){return this.raw.sendAnimation({chat_id:$,animation:w,...X},G)}sendVoice($,w,X,G){return this.raw.sendVoice({chat_id:$,voice:w,...X},G)}sendVideoNote($,w,X,G){return this.raw.sendVideoNote({chat_id:$,video_note:w,...X},G)}sendMediaGroup($,w,X,G){return this.raw.sendMediaGroup({chat_id:$,media:w,...X},G)}sendLocation($,w,X,G,E){return this.raw.sendLocation({chat_id:$,latitude:w,longitude:X,...G},E)}editMessageLiveLocation($,w,X,G,E,J){return this.raw.editMessageLiveLocation({chat_id:$,message_id:w,latitude:X,longitude:G,...E},J)}editMessageLiveLocationInline($,w,X,G,E){return this.raw.editMessageLiveLocation({inline_message_id:$,latitude:w,longitude:X,...G},E)}stopMessageLiveLocation($,w,X,G){return this.raw.stopMessageLiveLocation({chat_id:$,message_id:w,...X},G)}stopMessageLiveLocationInline($,w,X){return this.raw.stopMessageLiveLocation({inline_message_id:$,...w},X)}sendPaidMedia($,w,X,G,E){return this.raw.sendPaidMedia({chat_id:$,star_count:w,media:X,...G},E)}sendVenue($,w,X,G,E,J,W){return this.raw.sendVenue({chat_id:$,latitude:w,longitude:X,title:G,address:E,...J},W)}sendContact($,w,X,G,E){return this.raw.sendContact({chat_id:$,phone_number:w,first_name:X,...G},E)}sendPoll($,w,X,G,E){let J=X.map((W)=>typeof W==="string"?{text:W}:W);return this.raw.sendPoll({chat_id:$,question:w,options:J,...G},E)}sendChecklist($,w,X,G,E){return this.raw.sendChecklist({business_connection_id:$,chat_id:w,checklist:X,...G},E)}editMessageChecklist($,w,X,G,E,J){return this.raw.editMessageChecklist({business_connection_id:$,chat_id:w,message_id:X,checklist:G,...E},J)}sendDice($,w,X,G){return this.raw.sendDice({chat_id:$,emoji:w,...X},G)}setMessageReaction($,w,X,G,E){return this.raw.setMessageReaction({chat_id:$,message_id:w,reaction:X,...G},E)}sendChatAction($,w,X,G){return this.raw.sendChatAction({chat_id:$,action:w,...X},G)}getUserProfilePhotos($,w,X){return this.raw.getUserProfilePhotos({user_id:$,...w},X)}getUserProfileAudios($,w,X){return this.raw.getUserProfileAudios({user_id:$,...w},X)}setUserEmojiStatus($,w,X){return this.raw.setUserEmojiStatus({user_id:$,...w},X)}getUserChatBoosts($,w,X){return this.raw.getUserChatBoosts({chat_id:$,user_id:w},X)}getUserGifts($,w,X){return this.raw.getUserGifts({user_id:$,...w},X)}getChatGifts($,w,X){return this.raw.getChatGifts({chat_id:$,...w},X)}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,X,G){return this.raw.banChatMember({chat_id:$,user_id:w,...X},G)}unbanChatMember($,w,X,G){return this.raw.unbanChatMember({chat_id:$,user_id:w,...X},G)}restrictChatMember($,w,X,G,E){return this.raw.restrictChatMember({chat_id:$,user_id:w,permissions:X,...G},E)}promoteChatMember($,w,X,G){return this.raw.promoteChatMember({chat_id:$,user_id:w,...X},G)}setChatAdministratorCustomTitle($,w,X,G){return this.raw.setChatAdministratorCustomTitle({chat_id:$,user_id:w,custom_title:X},G)}setChatMemberTag($,w,X,G){return this.raw.setChatMemberTag({chat_id:$,user_id:w,tag:X},G)}banChatSenderChat($,w,X){return this.raw.banChatSenderChat({chat_id:$,sender_chat_id:w},X)}unbanChatSenderChat($,w,X){return this.raw.unbanChatSenderChat({chat_id:$,sender_chat_id:w},X)}setChatPermissions($,w,X,G){return this.raw.setChatPermissions({chat_id:$,permissions:w,...X},G)}exportChatInviteLink($,w){return this.raw.exportChatInviteLink({chat_id:$},w)}createChatInviteLink($,w,X){return this.raw.createChatInviteLink({chat_id:$,...w},X)}editChatInviteLink($,w,X,G){return this.raw.editChatInviteLink({chat_id:$,invite_link:w,...X},G)}createChatSubscriptionInviteLink($,w,X,G,E){return this.raw.createChatSubscriptionInviteLink({chat_id:$,subscription_period:w,subscription_price:X,...G},E)}editChatSubscriptionInviteLink($,w,X,G){return this.raw.editChatSubscriptionInviteLink({chat_id:$,invite_link:w,...X},G)}revokeChatInviteLink($,w,X){return this.raw.revokeChatInviteLink({chat_id:$,invite_link:w},X)}approveChatJoinRequest($,w,X){return this.raw.approveChatJoinRequest({chat_id:$,user_id:w},X)}declineChatJoinRequest($,w,X){return this.raw.declineChatJoinRequest({chat_id:$,user_id:w},X)}approveSuggestedPost($,w,X,G){return this.raw.approveSuggestedPost({chat_id:$,message_id:w,...X},G)}declineSuggestedPost($,w,X,G){return this.raw.declineSuggestedPost({chat_id:$,message_id:w,...X},G)}setChatPhoto($,w,X){return this.raw.setChatPhoto({chat_id:$,photo:w},X)}deleteChatPhoto($,w){return this.raw.deleteChatPhoto({chat_id:$},w)}setChatTitle($,w,X){return this.raw.setChatTitle({chat_id:$,title:w},X)}setChatDescription($,w,X){return this.raw.setChatDescription({chat_id:$,description:w},X)}pinChatMessage($,w,X,G){return this.raw.pinChatMessage({chat_id:$,message_id:w,...X},G)}unpinChatMessage($,w,X,G){return this.raw.unpinChatMessage({chat_id:$,message_id:w,...X},G)}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,X){return this.raw.getChatMember({chat_id:$,user_id:w},X)}setChatStickerSet($,w,X){return this.raw.setChatStickerSet({chat_id:$,sticker_set_name:w},X)}deleteChatStickerSet($,w){return this.raw.deleteChatStickerSet({chat_id:$},w)}getForumTopicIconStickers($){return this.raw.getForumTopicIconStickers($)}createForumTopic($,w,X,G){return this.raw.createForumTopic({chat_id:$,name:w,...X},G)}editForumTopic($,w,X,G){return this.raw.editForumTopic({chat_id:$,message_thread_id:w,...X},G)}closeForumTopic($,w,X){return this.raw.closeForumTopic({chat_id:$,message_thread_id:w},X)}reopenForumTopic($,w,X){return this.raw.reopenForumTopic({chat_id:$,message_thread_id:w},X)}deleteForumTopic($,w,X){return this.raw.deleteForumTopic({chat_id:$,message_thread_id:w},X)}unpinAllForumTopicMessages($,w,X){return this.raw.unpinAllForumTopicMessages({chat_id:$,message_thread_id:w},X)}editGeneralForumTopic($,w,X){return this.raw.editGeneralForumTopic({chat_id:$,name:w},X)}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,X){return this.raw.answerCallbackQuery({callback_query_id:$,...w},X)}setMyName($,w,X){return this.raw.setMyName({name:$,...w},X)}getMyName($,w){return this.raw.getMyName($!==null&&$!==void 0?$:{},w)}setMyCommands($,w,X){return this.raw.setMyCommands({commands:$,...w},X)}deleteMyCommands($,w){return this.raw.deleteMyCommands({...$},w)}getMyCommands($,w){return this.raw.getMyCommands({...$},w)}setMyDescription($,w,X){return this.raw.setMyDescription({description:$,...w},X)}getMyDescription($,w){return this.raw.getMyDescription({...$},w)}setMyShortDescription($,w,X){return this.raw.setMyShortDescription({short_description:$,...w},X)}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,X,G,E){return this.raw.editMessageText({chat_id:$,message_id:w,text:X,...G},E)}editMessageTextInline($,w,X,G){return this.raw.editMessageText({inline_message_id:$,text:w,...X},G)}editMessageCaption($,w,X,G){return this.raw.editMessageCaption({chat_id:$,message_id:w,...X},G)}editMessageCaptionInline($,w,X){return this.raw.editMessageCaption({inline_message_id:$,...w},X)}editMessageMedia($,w,X,G,E){return this.raw.editMessageMedia({chat_id:$,message_id:w,media:X,...G},E)}editMessageMediaInline($,w,X,G){return this.raw.editMessageMedia({inline_message_id:$,media:w,...X},G)}editMessageReplyMarkup($,w,X,G){return this.raw.editMessageReplyMarkup({chat_id:$,message_id:w,...X},G)}editMessageReplyMarkupInline($,w,X){return this.raw.editMessageReplyMarkup({inline_message_id:$,...w},X)}stopPoll($,w,X,G){return this.raw.stopPoll({chat_id:$,message_id:w,...X},G)}deleteMessage($,w,X){return this.raw.deleteMessage({chat_id:$,message_id:w},X)}deleteMessages($,w,X){return this.raw.deleteMessages({chat_id:$,message_ids:w},X)}deleteBusinessMessages($,w,X){return this.raw.deleteBusinessMessages({business_connection_id:$,message_ids:w},X)}setBusinessAccountName($,w,X,G){return this.raw.setBusinessAccountName({business_connection_id:$,first_name:w,...X},G)}setBusinessAccountUsername($,w,X){return this.raw.setBusinessAccountUsername({business_connection_id:$,username:w},X)}setBusinessAccountBio($,w,X){return this.raw.setBusinessAccountBio({business_connection_id:$,bio:w},X)}setBusinessAccountProfilePhoto($,w,X,G){return this.raw.setBusinessAccountProfilePhoto({business_connection_id:$,photo:w,...X},G)}removeBusinessAccountProfilePhoto($,w,X){return this.raw.removeBusinessAccountProfilePhoto({business_connection_id:$,...w},X)}setBusinessAccountGiftSettings($,w,X,G){return this.raw.setBusinessAccountGiftSettings({business_connection_id:$,show_gift_button:w,accepted_gift_types:X},G)}getBusinessAccountStarBalance($,w){return this.raw.getBusinessAccountStarBalance({business_connection_id:$},w)}transferBusinessAccountStars($,w,X){return this.raw.transferBusinessAccountStars({business_connection_id:$,star_count:w},X)}getBusinessAccountGifts($,w,X){return this.raw.getBusinessAccountGifts({business_connection_id:$,...w},X)}convertGiftToStars($,w,X){return this.raw.convertGiftToStars({business_connection_id:$,owned_gift_id:w},X)}upgradeGift($,w,X,G){return this.raw.upgradeGift({business_connection_id:$,owned_gift_id:w,...X},G)}transferGift($,w,X,G,E){return this.raw.transferGift({business_connection_id:$,owned_gift_id:w,new_owner_chat_id:X,star_count:G},E)}postStory($,w,X,G,E){return this.raw.postStory({business_connection_id:$,content:w,active_period:X,...G},E)}repostStory($,w,X,G,E,J){return this.raw.repostStory({business_connection_id:$,from_chat_id:w,from_story_id:X,active_period:G,...E},J)}editStory($,w,X,G,E){return this.raw.editStory({business_connection_id:$,story_id:w,content:X,...G},E)}deleteStory($,w,X){return this.raw.deleteStory({business_connection_id:$,story_id:w},X)}sendSticker($,w,X,G){return this.raw.sendSticker({chat_id:$,sticker:w,...X},G)}getStickerSet($,w){return this.raw.getStickerSet({name:$},w)}getCustomEmojiStickers($,w){return this.raw.getCustomEmojiStickers({custom_emoji_ids:$},w)}uploadStickerFile($,w,X,G){return this.raw.uploadStickerFile({user_id:$,sticker_format:w,sticker:X},G)}createNewStickerSet($,w,X,G,E,J){return this.raw.createNewStickerSet({user_id:$,name:w,title:X,stickers:G,...E},J)}addStickerToSet($,w,X,G){return this.raw.addStickerToSet({user_id:$,name:w,sticker:X},G)}setStickerPositionInSet($,w,X){return this.raw.setStickerPositionInSet({sticker:$,position:w},X)}deleteStickerFromSet($,w){return this.raw.deleteStickerFromSet({sticker:$},w)}replaceStickerInSet($,w,X,G,E){return this.raw.replaceStickerInSet({user_id:$,name:w,old_sticker:X,sticker:G},E)}setStickerEmojiList($,w,X){return this.raw.setStickerEmojiList({sticker:$,emoji_list:w},X)}setStickerKeywords($,w,X){return this.raw.setStickerKeywords({sticker:$,keywords:w},X)}setStickerMaskPosition($,w,X){return this.raw.setStickerMaskPosition({sticker:$,mask_position:w},X)}setStickerSetTitle($,w,X){return this.raw.setStickerSetTitle({name:$,title:w},X)}deleteStickerSet($,w){return this.raw.deleteStickerSet({name:$},w)}setStickerSetThumbnail($,w,X,G,E){return this.raw.setStickerSetThumbnail({name:$,user_id:w,thumbnail:X,format:G},E)}setCustomEmojiStickerSetThumbnail($,w,X){return this.raw.setCustomEmojiStickerSetThumbnail({name:$,custom_emoji_id:w},X)}getAvailableGifts($){return this.raw.getAvailableGifts($)}sendGift($,w,X,G){return this.raw.sendGift({user_id:$,gift_id:w,...X},G)}giftPremiumSubscription($,w,X,G,E){return this.raw.giftPremiumSubscription({user_id:$,month_count:w,star_count:X,...G},E)}sendGiftToChannel($,w,X,G){return this.raw.sendGift({chat_id:$,gift_id:w,...X},G)}answerInlineQuery($,w,X,G){return this.raw.answerInlineQuery({inline_query_id:$,results:w,...X},G)}answerWebAppQuery($,w,X){return this.raw.answerWebAppQuery({web_app_query_id:$,result:w},X)}savePreparedInlineMessage($,w,X,G){return this.raw.savePreparedInlineMessage({user_id:$,result:w,...X},G)}sendInvoice($,w,X,G,E,J,W,Y){return this.raw.sendInvoice({chat_id:$,title:w,description:X,payload:G,currency:E,prices:J,...W},Y)}createInvoiceLink($,w,X,G,E,J,W,Y){return this.raw.createInvoiceLink({title:$,description:w,payload:X,provider_token:G,currency:E,prices:J,...W},Y)}answerShippingQuery($,w,X,G){return this.raw.answerShippingQuery({shipping_query_id:$,ok:w,...X},G)}answerPreCheckoutQuery($,w,X,G){return this.raw.answerPreCheckoutQuery({pre_checkout_query_id:$,ok:w,...X},G)}getStarTransactions($,w){return this.raw.getStarTransactions({...$},w)}refundStarPayment($,w,X){return this.raw.refundStarPayment({user_id:$,telegram_payment_charge_id:w},X)}editUserStarSubscription($,w,X,G){return this.raw.editUserStarSubscription({user_id:$,telegram_payment_charge_id:w,is_canceled:X},G)}verifyUser($,w,X){return this.raw.verifyUser({user_id:$,...w},X)}verifyChat($,w,X){return this.raw.verifyChat({chat_id:$,...w},X)}removeUserVerification($,w){return this.raw.removeUserVerification({user_id:$},w)}removeChatVerification($,w){return this.raw.removeChatVerification({chat_id:$},w)}readBusinessMessage($,w,X,G){return this.raw.readBusinessMessage({business_connection_id:$,chat_id:w,message_id:X},G)}setPassportDataErrors($,w,X){return this.raw.setPassportDataErrors({user_id:$,errors:w},X)}sendGame($,w,X,G){return this.raw.sendGame({chat_id:$,game_short_name:w,...X},G)}setGameScore($,w,X,G,E,J){return this.raw.setGameScore({chat_id:$,message_id:w,user_id:X,score:G,...E},J)}setGameScoreInline($,w,X,G,E){return this.raw.setGameScore({inline_message_id:$,user_id:w,score:X,...G},E)}getGameHighScores($,w,X,G){return this.raw.getGameHighScores({chat_id:$,message_id:w,user_id:X},G)}getGameHighScoresInline($,w,X){return this.raw.getGameHighScores({inline_message_id:$,user_id:w},X)}}CH.Api=kH});var XW=b((wW)=>{Object.defineProperty(wW,"__esModule",{value:!0});wW.Bot=wW.BotError=wW.DEFAULT_UPDATE_TYPES=void 0;var q6=g9();Object.defineProperty(wW,"BotError",{enumerable:!0,get:function(){return q6.BotError}});var OZ=n4(),_H=s9(),a9=d4(),fH=c4(),$W=kw(),i1=(0,$W.debug)("grammy:bot"),NZ=(0,$W.debug)("grammy:warn"),$G=(0,$W.debug)("grammy:error");wW.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 yH extends q6.Composer{constructor($,w){var X;super();if(this.token=$,this.pollingRunning=!1,this.lastTriedUpdateId=0,this.observedUpdateTypes=new Set,this.errorHandler=async(G)=>{var E,J;if(console.error("Error in middleware while handling update",(J=(E=G.ctx)===null||E===void 0?void 0:E.update)===null||J===void 0?void 0:J.update_id,G.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 G},!$)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=(X=w===null||w===void 0?void 0:w.ContextConstructor)!==null&&X!==void 0?X:OZ.Context,this.api=new _H.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[X]of(0,fH.parse)($).flatMap(fH.preprocess))this.observedUpdateTypes.add(X);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()){i1("Initializing bot"),(w=this.mePromise)!==null&&w!==void 0||(this.mePromise=xH(()=>this.api.getMe($),$));let X;try{X=await this.mePromise}finally{this.mePromise=void 0}if(this.me===void 0)this.me=X;else i1("Bot info was set by now, will not overwrite")}i1(`I am ${this.me.username}!`)}async handleUpdates($){for(let w of $){this.lastTriedUpdateId=w.update_id;try{await this.handleUpdate(w)}catch(X){if(X instanceof q6.BotError)await this.errorHandler(X);else throw console.error("FATAL: grammY unable to handle:",X),X}}}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.");i1(`Processing update ${$.update_id}`);let X=new _H.Api(this.token,this.clientConfig,w),G=this.api.config.installedTransformers();if(G.length>0)X.config.use(...G);let E=new this.ContextConstructor($,X,this.me);try{await(0,q6.run)(this.middleware(),E)}catch(J){throw $G(`Error in middleware for update ${$.update_id}`),new q6.BotError(J,E)}}async start($){var w,X,G;let E=[];if(!this.isInited())E.push(this.init((w=this.pollingAbortController)===null||w===void 0?void 0:w.signal));if(this.pollingRunning){await Promise.all(E),i1("Simple long polling already running!");return}this.pollingRunning=!0,this.pollingAbortController=new FZ.AbortController;try{E.push(xH(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)},(X=this.pollingAbortController)===null||X===void 0?void 0:X.signal)),await Promise.all(E),await((G=$===null||$===void 0?void 0:$.onStart)===null||G===void 0?void 0:G.call($,this.botInfo))}catch(J){throw this.pollingRunning=!1,this.pollingAbortController=void 0,J}if(!this.pollingRunning)return;HZ(this.observedUpdateTypes,$===null||$===void 0?void 0:$.allowed_updates),this.use=LZ,i1("Starting simple long polling"),await this.loop($),i1("Middleware is done running")}async stop(){var $;if(this.pollingRunning){i1("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 i1("Bot is not running!")}isRunning(){return this.pollingRunning}catch($){this.errorHandler=$}async loop($){var w,X;let G=$===null||$===void 0?void 0:$.limit,E=(w=$===null||$===void 0?void 0:$.timeout)!==null&&w!==void 0?w:30,J=(X=$===null||$===void 0?void 0:$.allowed_updates)!==null&&X!==void 0?X:[];try{while(this.pollingRunning){let W=await this.fetchUpdates({limit:G,timeout:E,allowed_updates:J});if(W===void 0)break;await this.handleUpdates(W),J=void 0}}finally{this.pollingRunning=!1}}async fetchUpdates({limit:$,timeout:w,allowed_updates:X}){var G;let E=this.lastTriedUpdateId+1,J=void 0;do try{J=await this.api.getUpdates({offset:E,limit:$,timeout:w,allowed_updates:X},(G=this.pollingAbortController)===null||G===void 0?void 0:G.signal)}catch(W){await this.handlePollingError(W)}while(J===void 0&&this.pollingRunning);return J}async handlePollingError($){var w;if(!this.pollingRunning){i1("Pending getUpdates request cancelled");return}let X=3;if($ instanceof a9.GrammyError){if($G($.message),$.error_code===401||$.error_code===409)throw $;else if($.error_code===429)$G("Bot API server is closing."),X=(w=$.parameters.retry_after)!==null&&w!==void 0?w:X}else $G($);$G(`Call to getUpdates failed, retrying in ${X} seconds ...`),await e9(X)}}wW.Bot=yH;async function xH($,w){let G=50;async function E(W){let Y=!1,A="rethrow";if(W instanceof a9.HttpError)Y=!0,A="retry";else if(W instanceof a9.GrammyError){if(W.error_code>=500)Y=!0,A="retry";else if(W.error_code===429){let D=W.parameters.retry_after;if(typeof D==="number")await e9(D,w),G=50;else Y=!0;A="retry"}}if(Y){if(G!==50)await e9(G,w);G=Math.min(1200000,2*G)}return A}let J={ok:!1};while(!J.ok)try{J={ok:!0,value:await $()}}catch(W){switch($G(W),await E(W)){case"retry":continue;case"rethrow":throw W}}return J.value}async function e9($,w){let X,G;function E(){if(G===null||G===void 0||G(Error("Aborted delay")),X!==void 0)clearTimeout(X)}try{await new Promise((J,W)=>{if(G=W,w===null||w===void 0?void 0:w.aborted){E();return}w===null||w===void 0||w.addEventListener("abort",E),X=setTimeout(J,1000*$)})}finally{w===null||w===void 0||w.removeEventListener("abort",E)}}function HZ($,w=wW.DEFAULT_UPDATE_TYPES){let X=Array.from($).filter((G)=>!w.includes(G));if(X.length>0)NZ(`You registered listeners for the following update types, but you did not specify them in \`allowed_updates\` so they may not be received: ${X.map((G)=>`'${G}'`).join(", ")}`)}function LZ(){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 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
|
|
378
408
|
|
|
379
|
-
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 FZ=l9()});var mH=b((cH)=>{Object.defineProperty(cH,"__esModule",{value:!0});cH.API_CONSTANTS=void 0;var uH=XW(),MZ=[...uH.DEFAULT_UPDATE_TYPES,"chat_member","message_reaction","message_reaction_count"],zZ={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};cH.API_CONSTANTS={DEFAULT_UPDATE_TYPES:uH.DEFAULT_UPDATE_TYPES,ALL_UPDATE_TYPES:MZ,ALL_CHAT_PERMISSIONS:zZ};Object.freeze(cH.API_CONSTANTS)});var rH=b((nH)=>{Object.defineProperty(nH,"__esModule",{value:!0});nH.InlineQueryResultBuilder=void 0;function E$($){return{...$,...EW($)}}function EW($){return{text(w,X={}){let G={message_text:w,...X};return{...$,input_message_content:G}},location(w,X,G={}){let E={latitude:w,longitude:X,...G};return{...$,input_message_content:E}},venue(w,X,G,E,J){let W={title:w,latitude:X,longitude:G,address:E,...J};return{...$,input_message_content:W}},contact(w,X,G={}){let E={first_name:w,phone_number:X,...G};return{...$,input_message_content:E}},invoice(w,X,G,E,J,W,Y={}){let A={title:w,description:X,payload:G,provider_token:E,currency:J,prices:W,...Y};return{...$,input_message_content:A}}}}nH.InlineQueryResultBuilder={article($,w,X={}){return EW({type:"article",id:$,title:w,...X})},audio($,w,X,G={}){return E$({type:"audio",id:$,title:w,audio_url:typeof X==="string"?X:X.href,...G})},audioCached($,w,X={}){return E$({type:"audio",id:$,audio_file_id:w,...X})},contact($,w,X,G={}){return E$({type:"contact",id:$,phone_number:w,first_name:X,...G})},documentPdf($,w,X,G={}){return E$({type:"document",mime_type:"application/pdf",id:$,title:w,document_url:typeof X==="string"?X:X.href,...G})},documentZip($,w,X,G={}){return E$({type:"document",mime_type:"application/zip",id:$,title:w,document_url:typeof X==="string"?X:X.href,...G})},documentCached($,w,X,G={}){return E$({type:"document",id:$,title:w,document_file_id:X,...G})},game($,w,X={}){return{type:"game",id:$,game_short_name:w,...X}},gif($,w,X,G={}){return E$({type:"gif",id:$,gif_url:typeof w==="string"?w:w.href,thumbnail_url:typeof X==="string"?X:X.href,...G})},gifCached($,w,X={}){return E$({type:"gif",id:$,gif_file_id:w,...X})},location($,w,X,G,E={}){return E$({type:"location",id:$,title:w,latitude:X,longitude:G,...E})},mpeg4gif($,w,X,G={}){return E$({type:"mpeg4_gif",id:$,mpeg4_url:typeof w==="string"?w:w.href,thumbnail_url:typeof X==="string"?X:X.href,...G})},mpeg4gifCached($,w,X={}){return E$({type:"mpeg4_gif",id:$,mpeg4_file_id:w,...X})},photo($,w,X={}){let G=typeof w==="string"?w:w.href;return E$({type:"photo",id:$,photo_url:G,thumbnail_url:G,...X})},photoCached($,w,X={}){return E$({type:"photo",id:$,photo_file_id:w,...X})},stickerCached($,w,X={}){return E$({type:"sticker",id:$,sticker_file_id:w,...X})},venue($,w,X,G,E,J={}){return E$({type:"venue",id:$,title:w,latitude:X,longitude:G,address:E,...J})},videoHtml($,w,X,G,E={}){return EW({type:"video",mime_type:"text/html",id:$,title:w,video_url:typeof X==="string"?X:X.href,thumbnail_url:typeof G==="string"?G:G.href,...E})},videoMp4($,w,X,G,E={}){return E$({type:"video",mime_type:"video/mp4",id:$,title:w,video_url:typeof X==="string"?X:X.href,thumbnail_url:typeof G==="string"?G:G.href,...E})},videoCached($,w,X,G={}){return E$({type:"video",id:$,title:w,video_file_id:X,...G})},voice($,w,X,G={}){return E$({type:"voice",id:$,title:w,voice_url:typeof X==="string"?X:X.href,...G})},voiceCached($,w,X,G={}){return E$({type:"voice",id:$,title:w,voice_file_id:X,...G})}}});var tH=b((iH)=>{Object.defineProperty(iH,"__esModule",{value:!0});iH.InputMediaBuilder=void 0;iH.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 eH=b((sH)=>{Object.defineProperty(sH,"__esModule",{value:!0});sH.InlineKeyboard=sH.Keyboard=void 0;class n${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(n$.text($,w))}static text($,w){return typeof w==="string"?{text:$,style:w}:{text:$,...w}}requestUsers($,w,X={}){return this.add(n$.requestUsers($,w,X))}static requestUsers($,w,X={}){return typeof $==="string"?{text:$,request_users:{request_id:w,...X}}:{...$,request_users:{request_id:w,...X}}}requestChat($,w,X={chat_is_channel:!1}){return this.add(n$.requestChat($,w,X))}static requestChat($,w,X={chat_is_channel:!1}){let G={request_id:w,...X};return typeof $==="string"?{text:$,request_chat:G}:{...$,request_chat:G}}requestContact($){return this.add(n$.requestContact($))}static requestContact($){return typeof $==="string"?{text:$,request_contact:!0}:{...$,request_contact:!0}}requestLocation($){return this.add(n$.requestLocation($))}static requestLocation($){return typeof $==="string"?{text:$,request_location:!0}:{...$,request_location:!0}}requestPoll($,w){return this.add(n$.requestPoll($,w))}static requestPoll($,w){let X={type:w};return typeof $==="string"?{text:$,request_poll:X}:{...$,request_poll:X}}webApp($,w){return this.add(n$.webApp($,w))}static webApp($,w){let X={url:w};return typeof $==="string"?{text:$,web_app:X}:{...$,web_app:X}}style($){let w=this.keyboard.length;if(w===0)throw Error("Need to add a button before applying a style!");let X=this.keyboard[w-1],G=X.length;if(G===0)throw Error("Need to add a button before applying a style!");let E=X[G-1];if(typeof E==="string")E={text:E},X[G-1]=E;return E.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 X=this.keyboard[w-1],G=X.length;if(G===0)throw Error("Need to add a button before adding an icon!");let E=X[G-1];if(typeof E==="string")E={text:E},X[G-1]=E;return E.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=dH($);return this.clone(w)}toFlowed($,w={}){let X=this.keyboard,G=lH(X,$,w);return this.clone(G)}clone($=this.keyboard){let w=new n$($.map((X)=>X.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 X=n$.from(w);this.keyboard.push(...X.keyboard.map((G)=>G.slice()))}return this}build(){return this.keyboard}static from($){if($ instanceof n$)return $.clone();function w(X){return typeof X==="string"?n$.text(X):X}return new n$($.map((X)=>X.map(w)))}}sH.Keyboard=n$;class D${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(D$.url($,w))}static url($,w){return typeof $==="string"?{text:$,url:w}:{...$,url:w}}text($,w=typeof $==="string"?$:$.text){return this.add(D$.text($,w))}static text($,w=typeof $==="string"?$:$.text){return typeof $==="string"?{text:$,callback_data:w}:{...$,callback_data:w}}webApp($,w){return this.add(D$.webApp($,w))}static webApp($,w){let X=typeof w==="string"?{url:w}:w;return typeof $==="string"?{text:$,web_app:X}:{...$,web_app:X}}login($,w){return this.add(D$.login($,w))}static login($,w){let X=typeof w==="string"?{url:w}:w;return typeof $==="string"?{text:$,login_url:X}:{...$,login_url:X}}switchInline($,w=""){return this.add(D$.switchInline($,w))}static switchInline($,w=""){return typeof $==="string"?{text:$,switch_inline_query:w}:{...$,switch_inline_query:w}}switchInlineCurrent($,w=""){return this.add(D$.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(D$.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(D$.copyText($,w))}static copyText($,w){let X=typeof w==="string"?{text:w}:w;return typeof $==="string"?{text:$,copy_text:X}:{...$,copy_text:X}}game($){return this.add(D$.game($))}static game($){let w={};return typeof $==="string"?{text:$,callback_game:w}:{...$,callback_game:w}}pay($){return this.add(D$.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 X=this.inline_keyboard[w-1],G=X.length;if(G===0)throw Error("Need to add a button before applying a style!");return X[G-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 X=this.inline_keyboard[w-1],G=X.length;if(G===0)throw Error("Need to add a button before adding an icon!");return X[G-1].icon_custom_emoji_id=$,this}toTransposed(){let $=this.inline_keyboard,w=dH($);return new D$(w)}toFlowed($,w={}){let X=this.inline_keyboard,G=lH(X,$,w);return new D$(G)}clone(){return new D$(this.inline_keyboard.map(($)=>$.slice()))}append(...$){for(let w of $){let X=D$.from(w);this.inline_keyboard.push(...X.inline_keyboard.map((G)=>G.slice()))}return this}static from($){if($ instanceof D$)return $.clone();return new D$($.map((w)=>w.slice()))}}sH.InlineKeyboard=D$;function dH($){var w;let X=[];for(let G=0;G<$.length;G++){let E=$[G];for(let J=0;J<E.length;J++){let W=E[J];((w=X[J])!==null&&w!==void 0?w:X[J]=[]).push(W)}}return X}function lH($,w,{fillLastRow:X=!1}){var G;let E=w;if(X)E=$.map((Y)=>Y.length).reduce((Y,A)=>Y+A,0)%w;let J=[];for(let W of $)for(let Y of W){let A=Math.max(0,J.length-1),D=A===0?E:w,U=(G=J[A])!==null&&G!==void 0?G:J[A]=[];if(U.length===D)U=[],J.push(U);U.push(Y)}return J}});var JL=b((GL)=>{Object.defineProperty(GL,"__esModule",{value:!0});GL.MemorySessionStorage=void 0;GL.session=VZ;GL.lazySession=IZ;GL.enhanceStorage=PZ;var BZ=kw(),KZ=(0,BZ.debug)("grammy:session");function VZ($={}){return $.type==="multi"?TZ($):RZ($)}function RZ($){let{initial:w,storage:X,getSessionKey:G,custom:E}=JW($);return async(J,W)=>{let Y=new $J(X,J,"session",w),A=await G(J);await Y.init(A,{custom:E,lazy:!1}),await W(),await Y.finish()}}function TZ($){let w=Object.keys($).filter((G)=>G!=="type"),X=Object.fromEntries(w.map((G)=>[G,JW($[G])]));return async(G,E)=>{G.session={};let J=await Promise.all(w.map(async(W)=>{let{initial:Y,storage:A,getSessionKey:D,custom:U}=X[W],N=new $J(A,G.session,W,Y),H=await D(G);return await N.init(H,{custom:U,lazy:!1}),N}));if(await E(),G.session==null)J.forEach((W)=>W.delete());await Promise.all(J.map((W)=>W.finish()))}}function IZ($={}){if($.type!==void 0&&$.type!=="single")throw Error("Cannot use lazy multi sessions!");let{initial:w,storage:X,getSessionKey:G,custom:E}=JW($);return async(J,W)=>{let Y=new $J(X,J,"session",w),A=await G(J);await Y.init(A,{custom:E,lazy:!0}),await W(),await Y.finish()}}class $J{constructor($,w,X,G){this.storage=$,this.obj=w,this.prop=X,this.initial=G,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 X=wL("access",w);throw Error(X)}if(this.read=!0,!w.lazy||this.wrote)return this.value;return this.load(),this.fetching?this.promise:this.value},set:(X)=>{if($===void 0){let G=wL("assign",w);throw Error(G)}this.wrote=!0,this.fetching=!1,this.value=X}})}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 JW($={}){let{prefix:w="",getSessionKey:X=$L,initial:G,storage:E}=$;if(E==null)KZ("Storing session data in memory, all data will be lost when the bot restarts."),E=new WW;return{initial:G,storage:E,getSessionKey:async(W)=>{let Y=await X(W);return Y===void 0?void 0:w+Y},custom:X!==$L}}function $L($){var w;return(w=$.chatId)===null||w===void 0?void 0:w.toString()}function wL($,w){let{lazy:X=!1,custom:G}=w;return`Cannot ${$} ${X?"lazy ":""}session data because ${G?"the custom `getSessionKey` function returned undefined for this update":"this update does not belong to a chat, so the session key is undefined"}!`}function jZ($){return $===void 0||typeof $==="object"&&$!==null&&"__d"in $}function PZ($){let{storage:w,millisecondsToLive:X,migrations:G}=$;if(w=qZ(w),X!==void 0)w=SZ(w,X);if(G!==void 0)w=ZZ(w,G);return bZ(w)}function qZ($){return{read:async(w)=>{let X=await $.read(w);return jZ(X)?X:{__d:X}},write:(w,X)=>$.write(w,X),delete:(w)=>$.delete(w)}}function SZ($,w){let X={read:async(G)=>{let E=await $.read(G);if(E===void 0)return;if(E.e===void 0)return await X.write(G,E),E;if(E.e<Date.now()){await X.delete(G);return}return E},write:async(G,E)=>{E.e=XL(E,w).expires,await $.write(G,E)},delete:(G)=>$.delete(G)};return X}function ZZ($,w){let X=Object.keys(w).map((D)=>parseInt(D)).sort((D,U)=>D-U),G=X.length;if(G===0)throw Error("No migrations given!");let E=X[0],J=G-1,W=X[J],Y=new Map;X.forEach((D,U)=>Y.set(D,U));function A(D){let U=J;while(D<=X[U])U--;return U}return{read:async(D)=>{var U;let N=await $.read(D);if(N===void 0)return N;let{__d:H,v:L=E-1}=N,F=1+((U=Y.get(L))!==null&&U!==void 0?U:A(L));for(;F<G;F++)H=w[X[F]](H);return{...N,v:W,__d:H}},write:(D,U)=>$.write(D,{v:W,...U}),delete:(D)=>$.delete(D)}}function bZ($){return{read:(w)=>Promise.resolve($.read(w)).then((X)=>X===null||X===void 0?void 0:X.__d),write:(w,X)=>$.write(w,{__d:X}),delete:(w)=>$.delete(w)}}class WW{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($,XL(w,this.timeToLive))}delete($){this.storage.delete($)}}GL.MemorySessionStorage=WW;function XL($,w){if(w!==void 0&&w<1/0){let X=Date.now();return{session:$,expires:X+w}}else return{session:$}}});var DL=b((YL)=>{Object.defineProperty(YL,"__esModule",{value:!0});YL.adapters=void 0;var H$="X-Telegram-Bot-Api-Secret-Token",wJ=H$.toLowerCase(),Aw="secret token is wrong",wG=()=>new Response(null,{status:200}),XG=($)=>new Response($,{status:200,headers:{"Content-Type":"application/json"}}),GG=()=>new Response('"unauthorized"',{status:401,statusText:Aw}),_Z=($,w,X)=>({get update(){var G;return JSON.parse((G=$.body)!==null&&G!==void 0?G:"{}")},header:$.headers[H$],end:()=>X(null,{statusCode:200}),respond:(G)=>X(null,{statusCode:200,headers:{"Content-Type":"application/json"},body:G}),unauthorized:()=>X(null,{statusCode:401})}),fZ=($,w)=>{let X;return{get update(){var G;return JSON.parse((G=$.body)!==null&&G!==void 0?G:"{}")},header:$.headers[H$],end:()=>X({statusCode:200}),respond:(G)=>X({statusCode:200,headers:{"Content-Type":"application/json"},body:G}),unauthorized:()=>X({statusCode:401}),handlerReturn:new Promise((G)=>X=G)}},xZ=($,w)=>{var X,G;return{get update(){return w.body},header:(G=(X=$.res)===null||X===void 0?void 0:X.headers)===null||G===void 0?void 0:G[H$],end:()=>$.res={status:200,body:""},respond:(E)=>{var J,W,Y,A;(W=(J=$.res)===null||J===void 0?void 0:J.set)===null||W===void 0||W.call(J,"Content-Type","application/json"),(A=(Y=$.res)===null||Y===void 0?void 0:Y.send)===null||A===void 0||A.call(Y,E)},unauthorized:()=>{var E,J;(J=(E=$.res)===null||E===void 0?void 0:E.send)===null||J===void 0||J.call(E,401,Aw)}}},yZ=($)=>{let w;return{get update(){return $.json()},header:$.headers.get(H$)||void 0,end:()=>w({status:204}),respond:(X)=>w({jsonBody:X}),unauthorized:()=>w({status:401,body:Aw}),handlerReturn:new Promise((X)=>w=X)}},gZ=($)=>{let w;return{get update(){return $.json()},header:$.headers.get(H$)||void 0,end:()=>{w(wG())},respond:(X)=>{w(XG(X))},unauthorized:()=>{w(GG())},handlerReturn:new Promise((X)=>w=X)}},hZ=($)=>{let w;return $.respondWith(new Promise((X)=>{w=X})),{get update(){return $.request.json()},header:$.request.headers.get(H$)||void 0,end:()=>{w(wG())},respond:(X)=>{w(XG(X))},unauthorized:()=>{w(GG())}}},uZ=($)=>{let w;return{get update(){return $.json()},header:$.headers.get(H$)||void 0,end:()=>{w(wG())},respond:(X)=>{w(XG(X))},unauthorized:()=>{w(GG())},handlerReturn:new Promise((X)=>w=X)}},cZ=($,w)=>({get update(){return $.body},header:$.header(H$),end:()=>w.end(),respond:(X)=>{w.set("Content-Type","application/json"),w.send(X)},unauthorized:()=>{w.status(401).send(Aw)}}),mZ=($,w)=>({get update(){return $.body},header:$.headers[wJ],end:()=>w.send(""),respond:(X)=>w.headers({"Content-Type":"application/json"}).send(X),unauthorized:()=>w.code(401).send(Aw)}),nZ=($)=>{let w;return{get update(){return $.req.json()},header:$.req.header(H$),end:()=>{w($.body(""))},respond:(X)=>{w($.json(X))},unauthorized:()=>{$.status(401),w($.body(""))},handlerReturn:new Promise((X)=>w=X)}},WL=($,w)=>{let X=$.headers[wJ];return{get update(){return new Promise((G,E)=>{let J=[];$.on("data",(W)=>J.push(W)).once("end",()=>{let W=Buffer.concat(J).toString("utf-8");try{G(JSON.parse(W))}catch(Y){E(Y)}}).once("error",E)})},header:Array.isArray(X)?X[0]:X,end:()=>w.end(),respond:(G)=>w.writeHead(200,{"Content-Type":"application/json"}).end(G),unauthorized:()=>w.writeHead(401).end(Aw)}},pZ=($)=>({get update(){return $.request.body},header:$.get(H$)||void 0,end:()=>{$.body=""},respond:(w)=>{$.set("Content-Type","application/json"),$.response.body=w},unauthorized:()=>{$.status=401}}),rZ=($,w)=>({get update(){return $.body},header:$.headers[wJ],end:()=>w.end(),respond:(X)=>w.status(200).json(X),unauthorized:()=>w.status(401).send(Aw)}),iZ=($)=>({get update(){return $.body},header:$.headers.get(H$)||void 0,end:()=>$.response.sendStatus(200),respond:(w)=>$.response.status(200).send(w),unauthorized:()=>$.response.status(401).send(Aw)}),oZ=($)=>({get update(){return $.request.body.json()},header:$.request.headers.get(H$)||void 0,end:()=>{$.response.status=200},respond:(w)=>{$.response.type="json",$.response.body=w},unauthorized:()=>{$.response.status=401}}),tZ=($)=>({get update(){return $.request.json()},header:$.request.headers.get(H$)||void 0,end:()=>$.respondWith(wG()),respond:(w)=>$.respondWith(XG(w)),unauthorized:()=>$.respondWith(GG())}),dZ=($)=>{let w;return{get update(){return $.json()},header:$.headers.get(H$)||void 0,end:()=>{if(w)w(wG())},respond:(X)=>{if(w)w(XG(X))},unauthorized:()=>{if(w)w(GG())},handlerReturn:new Promise((X)=>w=X)}},lZ=({request:$})=>{let w;return{get update(){return $.json()},header:$.headers.get(H$)||void 0,end:()=>{if(w)w(wG())},respond:(X)=>{if(w)w(XG(X))},unauthorized:()=>{if(w)w(GG())},handlerReturn:new Promise((X)=>w=X)}},sZ=($,w)=>{var X;return{get update(){return $.json()},header:(X=$.headers.get(H$))!==null&&X!==void 0?X:void 0,end:()=>w.end(null),respond:(G)=>w.send(200,G),unauthorized:()=>w.send(401,Aw)}},aZ=($)=>{let w;return{get update(){return $.body},header:$.headers[wJ],end(){w("")},respond(X){$.set.headers["content-type"]="application/json",w(X)},unauthorized(){$.set.status=401,w("")},handlerReturn:new Promise((X)=>w=X)}};YL.adapters={"aws-lambda":_Z,"aws-lambda-async":fZ,azure:xZ,"azure-v4":yZ,bun:gZ,cloudflare:hZ,"cloudflare-mod":uZ,elysia:aZ,express:cZ,fastify:mZ,hono:nZ,http:WL,https:WL,koa:pZ,"next-js":rZ,nhttp:iZ,oak:oZ,serveHttp:tZ,"std/http":dZ,sveltekit:lZ,worktop:sZ}});var HL=b((NL)=>{Object.defineProperty(NL,"__esModule",{value:!0});NL.webhookCallback=Gb;var OL=kw(),eZ=DL(),UL=(0,OL.debug)("grammy:error"),$b=($,w,X,G=()=>w('"unauthorized"'))=>({update:Promise.resolve($),respond:w,header:X,unauthorized:G}),wb={...eZ.adapters,callback:$b};function Xb($,w){if(w===void 0)return!0;if($===void 0)return!1;let X=new TextEncoder,G=X.encode($),E=X.encode(w);if(G.length!==E.length)return!1;let J=0;for(let W=0;W<E.length;W++){let Y=W<G.length?G[W]:0,A=E[W];J|=Y^A}return J===0}function Gb($,w=OL.defaultAdapter,X,G,E){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:W=1e4,secretToken:Y}=typeof X==="object"?X:{onTimeout:X,timeoutMilliseconds:G,secretToken:E},A=!1,D=typeof w==="string"?wb[w]:w;return async(...U)=>{var N;let H=D(...U);if(!A)await $.init(),A=!0;if(!Xb(H.header,Y))return await H.unauthorized(),H.handlerReturn;let L=!1,F={async send(M){L=!0,await H.respond(M)}};if(await Eb($.handleUpdate(await H.update,F),typeof J==="function"?()=>J(...U):J,W),!L)(N=H.end)===null||N===void 0||N.call(H);return H.handlerReturn}}function Eb($,w,X){if(X===1/0)return $;return new Promise((G,E)=>{let J=setTimeout(()=>{if(UL(`Request timed out after ${X} ms`),w==="throw")E(Error(`Request timed out after ${X} ms`));else{if(typeof w==="function")w();G()}let W=Date.now();$.finally(()=>{let Y=Date.now()-W;UL(`Request completed ${Y} ms after timeout!`)})},X);$.then(G).catch(E).finally(()=>clearTimeout(J))})}});var ML=b((R0)=>{var Wb=R0&&R0.__createBinding||(Object.create?function($,w,X,G){if(G===void 0)G=X;var E=Object.getOwnPropertyDescriptor(w,X);if(!E||("get"in E?!w.__esModule:E.writable||E.configurable))E={enumerable:!0,get:function(){return w[X]}};Object.defineProperty($,G,E)}:function($,w,X,G){if(G===void 0)G=X;$[G]=w[X]}),EG=R0&&R0.__exportStar||function($,w){for(var X in $)if(X!=="default"&&!Object.prototype.hasOwnProperty.call(w,X))Wb(w,$,X)};Object.defineProperty(R0,"__esModule",{value:!0});R0.HttpError=R0.GrammyError=R0.Api=R0.matchFilter=R0.Composer=R0.Context=R0.InputFile=R0.BotError=R0.Bot=void 0;var LL=XW();Object.defineProperty(R0,"Bot",{enumerable:!0,get:function(){return LL.Bot}});Object.defineProperty(R0,"BotError",{enumerable:!0,get:function(){return LL.BotError}});var Yb=o9();Object.defineProperty(R0,"InputFile",{enumerable:!0,get:function(){return Yb.InputFile}});var Ab=n4();Object.defineProperty(R0,"Context",{enumerable:!0,get:function(){return Ab.Context}});EG(mH(),R0);EG(rH(),R0);EG(tH(),R0);EG(eH(),R0);EG(JL(),R0);EG(HL(),R0);var Db=g9();Object.defineProperty(R0,"Composer",{enumerable:!0,get:function(){return Db.Composer}});var Ub=c4();Object.defineProperty(R0,"matchFilter",{enumerable:!0,get:function(){return Ub.matchFilter}});var Ob=s9();Object.defineProperty(R0,"Api",{enumerable:!0,get:function(){return Ob.Api}});var FL=d4();Object.defineProperty(R0,"GrammyError",{enumerable:!0,get:function(){return FL.GrammyError}});Object.defineProperty(R0,"HttpError",{enumerable:!0,get:function(){return FL.HttpError}})});function AW($){let w=new JG.InlineKeyboard;for(let X of $){for(let G of X)w.text(G.label,G.value);w.row()}return w}function Hb($){let w=Q0(),X=w.gateway.telegram.token;if(!X)throw Error("Telegram token is not configured.");let G=new JG.Bot(X),E=new Map,J=null;function W(H){let L=w.gateway.telegram.authorized_users.map(String);return L.length>0&&L.includes(String(H))}function Y(H){let L=Date.now();if(E.has(H))return!0;E.set(H,L);for(let[F,M]of E)if(L-M>Nb)E.delete(F);return!1}function A(H){if(!H)return!1;return H.getTime()<$}async function D(H){let L=await G.api.getFile(H),F=await fetch(`https://api.telegram.org/file/bot${X}/${L.file_path}`);return new Uint8Array(await F.arrayBuffer())}async function U(H){if(J)await J(H)}function N(H,L,F){let M=H.from;return{platform:"telegram",chatId:String(H.chat?.id??H.callbackQuery?.message?.chat.id??""),userId:String(M.id),username:M.username,displayName:[M.first_name,M.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"];G.command(L,async(F)=>{if(!F.from||!W(F.from.id))return;let M=String(F.message?.message_id??"");if(M&&Y(`cmd:${M}`))return;if(A(F.message?.date?new Date(F.message.date*1000):void 0))return;let z=F.message?.text?.split(" ")[0]?.replace(/^\//,"").split("@")[0]??"help",Q=F.message?.text?.split(" ").slice(1).join(" ")??"",R=Q?`/${z} ${Q}`:`/${z}`;await U(N(F,R))}),G.on("message",async(F)=>{if(!F.from||!W(F.from.id))return;let M=String(F.message?.message_id??"");if(M&&Y(`msg:${M}`))return;if(A(F.message?.date?new Date(F.message.date*1000):void 0))return;let z=[];if(F.message?.voice)try{z.push({kind:"audio",data:await D(F.message.voice.file_id),mimeType:F.message.voice.mime_type??"audio/ogg",format:"ogg",duration:F.message.voice.duration})}catch(R){YW.warn("Failed to download voice message",{err:R})}if(F.message?.audio)try{z.push({kind:"audio",data:await D(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(R){YW.warn("Failed to download audio message",{err:R})}let Q=F.message?.text??F.message?.caption??"";if(!Q&&z.length===0)return;await U(N(F,Q,z.length>0?z:void 0))}),G.on("callback_query:data",async(F)=>{if(!F.from||!W(F.from.id)||!F.callbackQuery)return;let M=F.callbackQuery.id;if(Y(`cb:${M}`)){await F.answerCallbackQuery();return}let z=String(F.callbackQuery.message?.chat.id??F.chat?.id??""),Q=`${z}:${F.callbackQuery.message?.message_id}`;await U({platform:"telegram",chatId:z,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:Q}),await F.answerCallbackQuery()}),YW.info("Starting Telegram gateway adapter"),G.start({allowed_updates:["message","callback_query"]})},async stop(){G.stop()},async send(H,L,F){let M={};if(F?.parseMode==="html")M.parse_mode="HTML";if(F?.buttons?.length)M.reply_markup=AW(F.buttons);let z=L.slice(0,4096),Q=await G.api.sendMessage(H,z,M);return`${Q.chat.id}:${Q.message_id}`},async updateMessage(H,L,F,M){let[,z]=L.split(":");if(!z)return;let Q={};if(M?.parseMode==="html")Q.parse_mode="HTML";if(M?.buttons?.length)Q.reply_markup=AW(M.buttons);try{await G.api.editMessageText(H,Number(z),F.slice(0,4096),Q)}catch(R){if(!String(R instanceof Error?R.message:"").includes("message is not modified"))throw R}},async sendWithButtons(H,L,F,M){let z={reply_markup:AW(F)};if(M?.parseMode==="html")z.parse_mode="HTML";let Q=await G.api.sendMessage(H,L.slice(0,4096),z);return`${Q.chat.id}:${Q.message_id}`},async downloadAudio(H){return D(H)},async sendAudio(H,L,F,M){let z=F==="ogg"||F==="oga"?"ogg":"mp3",Q=new JG.InputFile(L,`audio.${z}`),R=M?{caption:M}:{};if(z==="ogg")await G.api.sendVoice(H,Q,R);else await G.api.sendAudio(H,Q,R)},async showTyping(H){try{await G.api.sendChatAction(H,"typing")}catch{}},async registerCommands(H){await G.api.setMyCommands(H.map((L)=>({command:L.command,description:L.description})))}}}var JG,YW,Nb=60000;var zL=B(()=>{d$();f$();Z4();JG=pE(ML(),1),YW=P0("gateway:telegram");S4("telegram",($)=>Hb($))});import{existsSync as Lb}from"fs";class QL{adapters=new Map;sessionLock=new b9;permissionManager=new Z9;startTime=Date.now();adapterStatus=new Map;pendingSessionApprove=new Set;rateLimiter=new q9;async start(){let $=Q0(),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 E of w)try{let J=wN(E,this.startTime);this.adapters.set(J.platform,J),await this.safeStart(J)}catch(J){let W=S9(String(J));DX.error(`Failed to create ${E} adapter`,W),this.adapterStatus.set(E,{error:W})}for(let[,E]of this.adapters)if("registerCommands"in E)try{await E.registerCommands(Fb)}catch(J){DX.warn("Failed to register bot commands",{platform:E.platform,err:J})}await zN();let X=Q0();for(let E of["telegram","slack"]){let J=X.gateway[E];if(J.enabled&&J.authorized_users.length===0)DX.warn(`${E}: authorized_users is empty \u2014 all users will be denied. Add user IDs to config.`)}let G=[...this.adapters.keys()].join(", ");DX.info(`Gateway started with adapters: ${G||"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)}),DX.error(`Failed to start ${$.platform} adapter`,S9(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=Q0(),X=w.gateway[$.platform],G=X.authorized_users.map(String),E=await YN({platform:$.platform,chatId:$.chatId,username:$.username,displayName:$.displayName,authorized:G.length>0&&G.includes($.userId),mode:X.mode,threadId:$.threadId});if(!E.authorized)return;if(!this.rateLimiter.allow(E.id)){await this.sendText($,"\u23F8 Slow down \u2014 too many messages. Try again in a minute.");return}let J=$.text.trim(),W=$.attachments?.find((D)=>D.kind==="audio");if(J){if(J=this.normalizeCallbackText(J),J.startsWith("__perm_resolved:")){let U=J.split(":")[2],N=U==="approved"?"\u2705 Permission approved.":U==="session"?"\u2705 Permission approved for this session.":"\u274C Permission denied.";if(await this.sendText($,N),U==="session"){let H=await Ww(E.id);if(H)await p1(H.id,{auto_approve:!0})}return}}if(!J&&W&&w.speech.enabled)try{let D=await CN({audio:W.data,format:W.format});await this.handleIncoming({...$,text:D,fromVoice:!0,attachments:[]});return}catch(D){await this.sendText($,`Voice transcription failed: ${D instanceof Error?D.message:String(D)}`);return}if(!J){await this.sendText($,"Send text or a voice message.");return}await dX({chatKey:E.id,direction:"in",role:"user",text:J,platformMessageId:$.platformMessageId,threadId:$.threadId,metadata:$.fromVoice?{from_voice:!0}:void 0});let Y=await IN({chatKey:E.id,rawText:J,currentMode:E.mode,currentWorkingDir:E.working_dir});if(Y){if(Y.mode)E.mode=Y.mode;let D=Y.html??Y.text??"",U=Y.text??D,N=Y.html?"html":void 0,H=this.adapters.get($.platform);if(H&&Y.buttons?.length&&"sendWithButtons"in H)await H.sendWithButtons($.chatId,D,Y.buttons,{threadId:$.threadId,parseMode:N});else if(H)await H.send($.chatId,D,{threadId:$.threadId,parseMode:N});if($.fromVoice&&U)await this.trySendVoiceReply($,U);await dX({chatKey:E.id,direction:"out",role:"system",text:U,threadId:$.threadId});return}if(E.mode.startsWith("job:")){let D=E.mode.slice(4),U=await x4(D),N=U?`Triggered ${U.name} \u2192 ${await $1({jobId:U.id,triggerBy:"bridge-msg",envOverrides:{MSG:J}})}`:`Job not found: ${D}`;if(await this.sendText($,N),$.fromVoice)await this.trySendVoiceReply($,N);await dX({chatKey:E.id,direction:"out",role:"system",text:N,threadId:$.threadId});return}if(E.mode==="direct"){await this.sendText($,"Direct mode active. Use /help for commands, or /agent claude to start an agent session."),await dX({chatKey:E.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 A=await jN({chatKey:E.id,mode:E.mode,cwd:E.working_dir});if(!this.sessionLock.tryAcquire(A.id)){await this.sendText($,`\u23F3 ${A.backend} is still processing \u2014 please wait.`);return}try{await this.runAgentTurnWithPreview($,E,A,J)}finally{this.sessionLock.release(A.id)}}async runAgentTurnWithPreview($,w,X,G){if(!X.cwd||!Lb(X.cwd)){await this.sendText($,"Set a working directory first: /cwd <absolute-path>");return}let E=this.adapters.get($.platform);if(!E)return;if("showTyping"in E)await E.showTyping($.chatId).catch(()=>{});let J=await E.send($.chatId,`${X.backend} is thinking\u2026`,{threadId:$.threadId}),W=null;if(J&&y4.supports(E))W=new y4(E),await W.init(X.id,$.chatId,J,`${X.backend} is thinking\u2026`);await p1(X.id,{status:"running",last_activity_at:new Date});try{let Y=await FN({chatKey:w.id,chatId:$.chatId,platform:$.platform,adapter:E,permissionManager:this.permissionManager,session:{id:X.id,backend:X.backend,cwd:X.cwd,model:X.model,runtime_session_id:X.runtime_session_id,auto_approve:X.auto_approve,task_id:X.task_id},threadId:$.threadId},G,J,W);if(await p1(X.id,{status:"idle",runtime_session_id:Y.runtimeSessionId,last_activity_at:new Date,last_error:null}),W&&J)await W.finalize(X.id,Y.output);else if(J&&"updateMessage"in E)await E.updateMessage($.chatId,J,Y.output,{threadId:$.threadId}).catch(()=>E.send($.chatId,Y.output,{threadId:$.threadId}));else await E.send($.chatId,Y.output,{threadId:$.threadId});if(await dX({chatKey:w.id,direction:"out",role:"assistant",text:Y.output,gatewaySessionId:X.id,threadId:$.threadId,platformMessageId:J}),$.fromVoice)await this.trySendVoiceReply($,Y.output)}catch(Y){W?.cleanup(X.id);let A=`Agent error: ${Y instanceof Error?Y.message:String(Y)}`;await p1(X.id,{status:"error",last_error:A,last_activity_at:new Date});let D=A.slice(0,1000);if(J&&"updateMessage"in E)await E.updateMessage($.chatId,J,D,{threadId:$.threadId}).catch(()=>E.send($.chatId,D,{threadId:$.threadId}));else await E.send($.chatId,D,{threadId:$.threadId}).catch(()=>{});if(Y instanceof Error&&/auth|api.key|401/i.test(Y.message))await MN(X.id)}}async sendText($,w){let X=this.adapters.get($.platform);if(!X)return;await X.send($.chatId,w,{threadId:$.threadId})}async trySendVoiceReply($,w){if(!Q0().tts.enabled)return;let G=this.adapters.get($.platform);if(!G||!("sendAudio"in G))return;try{let E=await vN(w);await G.sendAudio($.chatId,E.audio,E.format,"Voice reply")}catch(E){DX.warn("TTS failed",{err:E})}}async notifyTaskReview($){let w=await HN(),X=`\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 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>
|
|
380
410
|
|
|
381
411
|
<b>${$.title}</b>
|
|
382
|
-
${$.summary.slice(0,400)}`,
|
|
383
|
-
`)}var
|
|
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 IN(){if(ww)return;ww=new vL,await ww.start()}async function KN(){if(!ww)return;await ww.stop(),ww=null}function MA(){return ww}async function VN($,w,E,X){await ww?.sendToChat($,w,E,X)}function PN(){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,pb,ww=null;var fL=R(()=>{C$();p$();nw();rJ();vY();fY();lJ();nY();mY();lY();_L();_G();zE=Z0("gateway"),pb=[{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 qN=R(()=>{fL();_G()});var hN,TX=($,w)=>{let E=new String($);return E.isEscaped=!0,E.callbacks=w,E},tZ,j3=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];VA(J,D),E=D[0]}}return TX(E,w)},VA=($,w)=>{let E=$.search(tZ);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)},M3=($)=>{let w=$.callbacks;if(!w?.length)return $;let E=[$],X={};return w.forEach((G)=>G({phase:hN.Stringify,buffer:E,context:X})),E[0]},cN=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)=>cN(N,w,!1,X,G))).then(()=>G[0]));if(E)return TX(await A,J);else return A};var nN=R(()=>{hN={Stringify:1,BeforeStream:2,Stream:3},tZ=/[&<>'"]/});var mN=($,...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")VA(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 VA(N.toString(),E)}}return E[0]+=$.at(-1),E.length===1?"callbacks"in E?TX(M3(TX(E[0],E.callbacks))):TX(E[0]):j3(E,E.callbacks)};var R3=R(()=>{nN()});var J0,z3,iZ=($)=>{return Object.entries($).map(([w,E])=>{let X=w;if(!z3[X]||E===void 0)return"";switch(z3[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(",")},dZ=({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`]}},lZ=($)=>{let w=dZ({version:$?.version});if(delete $.version,$.manuallySwaggerUIHtml)return $.manuallySwaggerUIHtml(w);let E=iZ($);return`
|
|
384
414
|
<div>
|
|
385
415
|
<div id="swagger-ui"></div>
|
|
386
|
-
${w.css.map((
|
|
387
|
-
${w.js.map((
|
|
416
|
+
${w.css.map((X)=>mN`<link rel="stylesheet" href="${X}" />`)}
|
|
417
|
+
${w.js.map((X)=>mN`<script src="${X}" crossorigin="anonymous"><\/script>`)}
|
|
388
418
|
<script>
|
|
389
419
|
window.onload = () => {
|
|
390
420
|
window.ui = SwaggerUIBundle({
|
|
391
|
-
dom_id: '#swagger-ui',${
|
|
421
|
+
dom_id: '#swagger-ui',${E},
|
|
392
422
|
})
|
|
393
423
|
}
|
|
394
424
|
</script>
|
|
395
425
|
</div>
|
|
396
|
-
`},
|
|
426
|
+
`},T3=($)=>async(w)=>{let E=$?.title??"SwaggerUI";return w.html(`
|
|
397
427
|
<!doctype html>
|
|
398
428
|
<html lang="en">
|
|
399
429
|
<head>
|
|
400
430
|
<meta charset="utf-8" />
|
|
401
431
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
402
432
|
<meta name="description" content="SwaggerUI" />
|
|
403
|
-
<title>${
|
|
433
|
+
<title>${E}</title>
|
|
404
434
|
</head>
|
|
405
435
|
<body>
|
|
406
|
-
${
|
|
436
|
+
${lZ($)}
|
|
407
437
|
</body>
|
|
408
438
|
</html>
|
|
409
|
-
`)};var J3=B(()=>{X3();X0={STRING_ARRAY:"string_array",STRING:"string",JSON_STRING:"json_string",RAW:"raw"},G3={configUrl:X0.STRING,deepLinking:X0.RAW,presets:X0.STRING_ARRAY,plugins:X0.STRING_ARRAY,spec:X0.JSON_STRING,url:X0.STRING,urls:X0.JSON_STRING,layout:X0.STRING,docExpansion:X0.STRING,maxDisplayedTags:X0.RAW,operationsSorter:X0.RAW,requestInterceptor:X0.RAW,responseInterceptor:X0.RAW,persistAuthorization:X0.RAW,defaultModelsExpandDepth:X0.RAW,defaultModelExpandDepth:X0.RAW,defaultModelRendering:X0.STRING,displayRequestDuration:X0.RAW,filter:X0.RAW,showExtensions:X0.RAW,showCommonExtensions:X0.RAW,queryConfigEnabled:X0.RAW,displayOperationId:X0.RAW,tagsSorter:X0.RAW,onComplete:X0.RAW,syntaxHighlight:X0.JSON_STRING,tryItOutEnabled:X0.RAW,requestSnippetsEnabled:X0.RAW,requestSnippets:X0.JSON_STRING,oauth2RedirectUrl:X0.STRING,showMutabledRequest:X0.RAW,request:X0.JSON_STRING,supportedSubmitMethods:X0.JSON_STRING,validatorUrl:X0.STRING,withCredentials:X0.RAW,modelPropertyMacro:X0.RAW,parameterMacro:X0.RAW}});function f6($,w){var X={};for(var G in $)if(Object.prototype.hasOwnProperty.call($,G)&&w.indexOf(G)<0)X[G]=$[G];if($!=null&&typeof Object.getOwnPropertySymbols==="function"){for(var E=0,G=Object.getOwnPropertySymbols($);E<G.length;E++)if(w.indexOf(G[E])<0&&Object.prototype.propertyIsEnumerable.call($,G[E]))X[G[E]]=$[G[E]]}return X}function J0($,w){var X;return((X=$===null||$===void 0?void 0:$._def)===null||X===void 0?void 0:X.typeName)===w}function Vk($){return"_def"in $}function v6($,w){let X=$.ZodType.prototype[w];$.ZodType.prototype[w]=function(...G){let E=X.apply(this,G);return E._def.openapi=this._def.openapi,E}}function Y3($){if(typeof $.ZodType.prototype.openapi<"u")return;$.ZodType.prototype.openapi=function(E,J){var W,Y,A,D,U,N;let H=typeof E==="string"?J:E,L=H!==null&&H!==void 0?H:{},{param:F}=L,M=f6(L,["param"]),z=Object.assign(Object.assign({},(W=this._def.openapi)===null||W===void 0?void 0:W._internal),typeof E==="string"?{refId:E}:void 0),Q=Object.assign(Object.assign(Object.assign({},(Y=this._def.openapi)===null||Y===void 0?void 0:Y.metadata),M),((D=(A=this._def.openapi)===null||A===void 0?void 0:A.metadata)===null||D===void 0?void 0:D.param)||F?{param:Object.assign(Object.assign({},(N=(U=this._def.openapi)===null||U===void 0?void 0:U.metadata)===null||N===void 0?void 0:N.param),F)}:void 0),R=new this.constructor(Object.assign(Object.assign({},this._def),{openapi:Object.assign(Object.assign({},Object.keys(z).length>0?{_internal:z}:void 0),Object.keys(Q).length>0?{metadata:Q}:void 0)}));if(J0(this,"ZodObject")){let T=this.extend;R.extend=function(...v){var f,k,m,F0,b0,f0,c0;let K0=T.apply(this,v);return K0._def.openapi={_internal:{extendedFrom:((k=(f=this._def.openapi)===null||f===void 0?void 0:f._internal)===null||k===void 0?void 0:k.refId)?{refId:(F0=(m=this._def.openapi)===null||m===void 0?void 0:m._internal)===null||F0===void 0?void 0:F0.refId,schema:this}:(f0=(b0=this._def.openapi)===null||b0===void 0?void 0:b0._internal)===null||f0===void 0?void 0:f0.extendedFrom},metadata:(c0=K0._def.openapi)===null||c0===void 0?void 0:c0.metadata},K0}}return R},v6($,"optional"),v6($,"nullable"),v6($,"default"),v6($,"transform"),v6($,"refine");let w=$.ZodObject.prototype.deepPartial;$.ZodObject.prototype.deepPartial=function(){let E=this._def.shape(),J=w.apply(this),W=J._def.shape();return Object.entries(W).forEach(([Y,A])=>{var D,U;A._def.openapi=(U=(D=E[Y])===null||D===void 0?void 0:D._def)===null||U===void 0?void 0:U.openapi}),J._def.openapi=void 0,J};let X=$.ZodObject.prototype.pick;$.ZodObject.prototype.pick=function(...E){let J=X.apply(this,E);return J._def.openapi=void 0,J};let G=$.ZodObject.prototype.omit;$.ZodObject.prototype.omit=function(...E){let J=G.apply(this,E);return J._def.openapi=void 0,J}}function OJ($,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 X=Object.keys($);return Object.keys(w).every((G)=>X.indexOf(G)!==-1)&&X.every((G)=>OJ($[G],w[G]))}class A3{constructor(){this.buckets=new Map}put($){let w=this.hashCodeOf($),X=this.buckets.get(w);if(!X){this.buckets.set(w,[$]);return}if(!X.some((E)=>OJ(E,$)))X.push($)}contains($){let w=this.hashCodeOf($),X=this.buckets.get(w);if(!X)return!1;return X.some((G)=>OJ(G,$))}values(){return[...this.buckets.values()].flat()}stats(){let $=0,w=0,X=0;for(let E of this.buckets.values())if($+=1,w+=E.length,E.length>1)X+=1;let G=$/w;return{totalBuckets:$,collisions:X,totalValues:w,hashEffectiveness:G}}hashCodeOf($){let w=0;if(Array.isArray($)){for(let X=0;X<$.length;X++)w^=this.hashCodeOf($[X])*X;return w}if(typeof $==="string"){for(let X=0;X<$.length;X++)w^=$.charCodeAt(X)*X;return w}if(typeof $==="number")return $;if(typeof $==="object")for(let[X,G]of Object.entries($))w^=this.hashCodeOf(X)+this.hashCodeOf(G!==null&&G!==void 0?G:"");return w}}function x6($){return $===void 0}function y6($,w){let X={};return Object.entries($).forEach(([G,E])=>{X[G]=w(E)}),X}function Rk($,w){let X={};return Object.entries($).forEach(([G,E])=>{if(!w.some((J)=>J===G))X[G]=E}),X}function OG($,w){let X={};return Object.entries($).forEach(([G,E])=>{if(!w(E,G))X[G]=E}),X}function W3($){return $.filter((w)=>!x6(w))}function Tk($){let w=new A3;return $.forEach((X)=>w.put(X)),[...w.values()]}function D3($){return typeof $==="string"}class kW{constructor($){this.parents=$,this._definitions=[]}get definitions(){var $,w;return[...(w=($=this.parents)===null||$===void 0?void 0:$.flatMap((G)=>G.definitions))!==null&&w!==void 0?w:[],...this._definitions]}register($,w){let X=this.schemaWithRefId($,w);return this._definitions.push({type:"schema",schema:X}),X}registerParameter($,w){var X,G,E;let J=this.schemaWithRefId($,w),W=(X=J._def.openapi)===null||X===void 0?void 0:X.metadata,Y=J.openapi(Object.assign(Object.assign({},W),{param:Object.assign(Object.assign({},W===null||W===void 0?void 0:W.param),{name:(E=(G=W===null||W===void 0?void 0:W.param)===null||G===void 0?void 0:G.name)!==null&&E!==void 0?E:$})}));return this._definitions.push({type:"parameter",schema:Y}),Y}registerPath($){this._definitions.push({type:"route",route:$})}registerWebhook($){this._definitions.push({type:"webhook",webhook:$})}registerComponent($,w,X){return this._definitions.push({type:"component",componentType:$,name:w,component:X}),{name:w,ref:{$ref:`#/components/${$}/${w}`}}}schemaWithRefId($,w){return w.openapi($)}}class h6{constructor($){this.message=$}}function _6($,w){try{return $()}catch(X){if(X instanceof g6)throw new g6(Object.assign(Object.assign({},X.data),w));throw X}}class C0{static getMetadata($){var w;let X=this.unwrapChained($),G=$._def.openapi?$._def.openapi:X._def.openapi,E=(w=$.description)!==null&&w!==void 0?w:X.description;return{_internal:G===null||G===void 0?void 0:G._internal,metadata:Object.assign({description:E},G===null||G===void 0?void 0:G.metadata)}}static getInternalMetadata($){let w=this.unwrapChained($),X=$._def.openapi?$._def.openapi:w._def.openapi;return X===null||X===void 0?void 0:X._internal}static getParamMetadata($){var w,X;let G=this.unwrapChained($),E=$._def.openapi?$._def.openapi:G._def.openapi,J=(w=$.description)!==null&&w!==void 0?w:G.description;return{_internal:E===null||E===void 0?void 0:E._internal,metadata:Object.assign(Object.assign({},E===null||E===void 0?void 0:E.metadata),{param:Object.assign({description:J},(X=E===null||E===void 0?void 0:E.metadata)===null||X===void 0?void 0:X.param)})}}static buildSchemaMetadata($){return OG(Rk($,["param"]),x6)}static buildParameterMetadata($){return OG($,x6)}static applySchemaMetadata($,w){return OG(Object.assign(Object.assign({},$),this.buildSchemaMetadata(w)),x6)}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&&J0($,w))return $;if(J0($,"ZodOptional")||J0($,"ZodNullable")||J0($,"ZodBranded"))return this.unwrapUntil($.unwrap(),w);if(J0($,"ZodDefault")||J0($,"ZodReadonly"))return this.unwrapUntil($._def.innerType,w);if(J0($,"ZodEffects"))return this.unwrapUntil($._def.schema,w);if(J0($,"ZodPipeline"))return this.unwrapUntil($._def.in,w);return w?void 0:$}static isOptionalSchema($){return $.isOptional()}}class O3{transform($,w,X){var G,E;let J=$._def.type;return Object.assign(Object.assign({},w("array")),{items:X(J),minItems:(G=$._def.minLength)===null||G===void 0?void 0:G.value,maxItems:(E=$._def.maxLength)===null||E===void 0?void 0:E.value})}}class N3{transform($){return Object.assign(Object.assign({},$("string")),{pattern:"^d+$"})}}class H3{transform($,w,X,G,E){let J=[...$.options.values()],W=J.map(G);if(w)return{oneOf:X(W,w)};return{oneOf:W,discriminator:this.mapDiscriminator(J,$.discriminator,E)}}mapDiscriminator($,w,X){if($.some((E)=>C0.getRefId(E)===void 0))return;let G={};return $.forEach((E)=>{var J;let W=C0.getRefId(E),Y=(J=E.shape)===null||J===void 0?void 0:J[w];if(J0(Y,"ZodEnum")||J0(Y,"ZodNativeEnum")){Object.values(Y.enum).filter(D3).forEach((U)=>{G[U]=X(W)});return}let A=Y===null||Y===void 0?void 0:Y._def.value;if(typeof A!=="string")throw Error(`Discriminator ${w} could not be found in one of the values of a discriminated union`);G[A]=X(W)}),{propertyName:w,mapping:G}}}class L3{transform($,w){return Object.assign(Object.assign({},w("string")),{enum:$._def.values})}}class F3{transform($,w,X,G){let J={allOf:this.flattenIntersectionTypes($).map(G)};if(w)return{anyOf:X([J],w)};return J}flattenIntersectionTypes($){if(!J0($,"ZodIntersection"))return[$];let w=this.flattenIntersectionTypes($._def.left),X=this.flattenIntersectionTypes($._def.right);return[...w,...X]}}class M3{transform($,w){return Object.assign(Object.assign({},w(typeof $._def.value)),{enum:[$._def.value]})}}function Ik($){let X=Object.keys($).filter((J)=>typeof $[$[J]]!=="number").map((J)=>$[J]),G=X.filter((J)=>typeof J==="number").length,E=G===0?"string":G===X.length?"numeric":"mixed";return{values:X,type:E}}class z3{transform($,w){let{type:X,values:G}=Ik($._def.values);if(X==="mixed")throw new h6("Enum has mixed string and number values, please specify the OpenAPI type manually");return Object.assign(Object.assign({},w(X==="numeric"?"integer":"string")),{enum:G})}}class Q3{transform($,w,X){return Object.assign(Object.assign({},w($.isInt?"integer":"number")),X($._def.checks))}}class B3{transform($,w,X,G){var E;let J=(E=C0.getInternalMetadata($))===null||E===void 0?void 0:E.extendedFrom,W=this.requiredKeysOf($),Y=y6($._def.shape(),G);if(!J)return Object.assign(Object.assign(Object.assign(Object.assign({},X("object")),{properties:Y,default:w}),W.length>0?{required:W}:{}),this.generateAdditionalProperties($,G));let A=J.schema;G(A);let D=this.requiredKeysOf(A),U=y6(A===null||A===void 0?void 0:A._def.shape(),G),N=Object.fromEntries(Object.entries(Y).filter(([F,M])=>{return!bW(U[F],M)})),H=W.filter((F)=>!D.includes(F)),L=Object.assign(Object.assign(Object.assign(Object.assign({},X("object")),{default:w,properties:N}),H.length>0?{required:H}:{}),this.generateAdditionalProperties($,G));return{allOf:[{$ref:`#/components/schemas/${J.refId}`},L]}}generateAdditionalProperties($,w){let X=$._def.unknownKeys,G=$._def.catchall;if(J0(G,"ZodNever")){if(X==="strict")return{additionalProperties:!1};return{}}return{additionalProperties:w(G)}}requiredKeysOf($){return Object.entries($._def.shape()).filter(([w,X])=>!C0.isOptionalSchema(X)).map(([w,X])=>w)}}class K3{transform($,w,X){let G=$._def.valueType,E=$._def.keyType,J=X(G);if(J0(E,"ZodEnum")||J0(E,"ZodNativeEnum")){let Y=Object.values(E.enum).filter(D3).reduce((A,D)=>Object.assign(Object.assign({},A),{[D]:J}),{});return Object.assign(Object.assign({},w("object")),{properties:Y})}return Object.assign(Object.assign({},w("object")),{additionalProperties:J})}}class V3{transform($,w){var X,G,E;let J=this.getZodStringCheck($,"regex"),W=(X=this.getZodStringCheck($,"length"))===null||X===void 0?void 0:X.value,Y=Number.isFinite($.minLength)?(G=$.minLength)!==null&&G!==void 0?G:void 0:void 0,A=Number.isFinite($.maxLength)?(E=$.maxLength)!==null&&E!==void 0?E:void 0:void 0;return Object.assign(Object.assign({},w("string")),{minLength:W!==null&&W!==void 0?W:Y,maxLength:W!==null&&W!==void 0?W:A,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((X)=>{return X.kind===w})}}class R3{constructor($){this.versionSpecifics=$}transform($,w,X){let{items:G}=$._def,E=G.map(X);return Object.assign(Object.assign({},w("array")),this.versionSpecifics.mapTupleItems(E))}}class T3{transform($,w,X){let E=this.flattenUnionTypes($).map((J)=>{let W=this.unwrapNullable(J);return X(W)});return{anyOf:w(E)}}flattenUnionTypes($){if(!J0($,"ZodUnion"))return[$];return $._def.options.flatMap((X)=>this.flattenUnionTypes(X))}unwrapNullable($){if(J0($,"ZodNullable"))return this.unwrapNullable($.unwrap());return $}}class I3{constructor($){this.versionSpecifics=$,this.objectTransformer=new B3,this.stringTransformer=new V3,this.numberTransformer=new Q3,this.bigIntTransformer=new N3,this.literalTransformer=new M3,this.enumTransformer=new L3,this.nativeEnumTransformer=new z3,this.arrayTransformer=new O3,this.unionTransformer=new T3,this.discriminatedUnionTransformer=new H3,this.intersectionTransformer=new F3,this.recordTransformer=new K3,this.tupleTransformer=new R3($)}transform($,w,X,G,E){if(J0($,"ZodNull"))return this.versionSpecifics.nullType;if(J0($,"ZodUnknown")||J0($,"ZodAny"))return this.versionSpecifics.mapNullableType(void 0,w);if(J0($,"ZodObject"))return this.objectTransformer.transform($,E,(W)=>this.versionSpecifics.mapNullableType(W,w),X);let J=this.transformSchemaWithoutDefault($,w,X,G);return Object.assign(Object.assign({},J),{default:E})}transformSchemaWithoutDefault($,w,X,G){if(J0($,"ZodUnknown")||J0($,"ZodAny"))return this.versionSpecifics.mapNullableType(void 0,w);if(J0($,"ZodString"))return this.stringTransformer.transform($,(J)=>this.versionSpecifics.mapNullableType(J,w));if(J0($,"ZodNumber"))return this.numberTransformer.transform($,(J)=>this.versionSpecifics.mapNullableType(J,w),(J)=>this.versionSpecifics.getNumberChecks(J));if(J0($,"ZodBigInt"))return this.bigIntTransformer.transform((J)=>this.versionSpecifics.mapNullableType(J,w));if(J0($,"ZodBoolean"))return this.versionSpecifics.mapNullableType("boolean",w);if(J0($,"ZodLiteral"))return this.literalTransformer.transform($,(J)=>this.versionSpecifics.mapNullableType(J,w));if(J0($,"ZodEnum"))return this.enumTransformer.transform($,(J)=>this.versionSpecifics.mapNullableType(J,w));if(J0($,"ZodNativeEnum"))return this.nativeEnumTransformer.transform($,(J)=>this.versionSpecifics.mapNullableType(J,w));if(J0($,"ZodArray"))return this.arrayTransformer.transform($,(J)=>this.versionSpecifics.mapNullableType(J,w),X);if(J0($,"ZodTuple"))return this.tupleTransformer.transform($,(J)=>this.versionSpecifics.mapNullableType(J,w),X);if(J0($,"ZodUnion"))return this.unionTransformer.transform($,(J)=>this.versionSpecifics.mapNullableOfArray(J,w),X);if(J0($,"ZodDiscriminatedUnion"))return this.discriminatedUnionTransformer.transform($,w,(J)=>this.versionSpecifics.mapNullableOfArray(J,w),X,G);if(J0($,"ZodIntersection"))return this.intersectionTransformer.transform($,w,(J)=>this.versionSpecifics.mapNullableOfArray(J,w),X);if(J0($,"ZodRecord"))return this.recordTransformer.transform($,(J)=>this.versionSpecifics.mapNullableType(J,w),X);if(J0($,"ZodDate"))return this.versionSpecifics.mapNullableType("string",w);let E=C0.getRefId($);throw new U3({currentSchema:$._def,schemaName:E})}}class CW{constructor($,w){this.definitions=$,this.versionSpecifics=w,this.schemaRefs={},this.paramRefs={},this.pathRefs={},this.rawComponents=[],this.openApiTransformer=new I3(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 X={};return this.rawComponents.forEach(({componentType:G,name:E,component:J})=>{var W;(W=X[G])!==null&&W!==void 0||(X[G]={}),X[G][E]=J}),Object.assign(Object.assign({},X),{schemas:Object.assign(Object.assign({},($=X.schemas)!==null&&$!==void 0?$:{}),this.schemaRefs),parameters:Object.assign(Object.assign({},(w=X.parameters)!==null&&w!==void 0?w:{}),this.paramRefs)})}sortDefinitions(){let $=["schema","parameter","component","route"];this.definitions.sort((w,X)=>{if(!("type"in w)){if(!("type"in X))return 0;return-1}if(!("type"in X))return 1;let G=$.findIndex((J)=>J===w.type),E=$.findIndex((J)=>J===X.type);return G-E})}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=C0.getRefId($),X=this.generateParameter($);if(w)this.paramRefs[w]=X;return X}getParameterRef($,w){var X,G,E,J,W;let Y=(X=$===null||$===void 0?void 0:$.metadata)===null||X===void 0?void 0:X.param,A=((G=$===null||$===void 0?void 0:$._internal)===null||G===void 0?void 0:G.refId)?this.paramRefs[(E=$._internal)===null||E===void 0?void 0:E.refId]:void 0;if(!((J=$===null||$===void 0?void 0:$._internal)===null||J===void 0?void 0:J.refId)||!A)return;if(Y&&A.in!==Y.in||(w===null||w===void 0?void 0:w.in)&&A.in!==w.in)throw new UG(`Conflicting location for parameter ${A.name}`,{key:"in",values:W3([A.in,w===null||w===void 0?void 0:w.in,Y===null||Y===void 0?void 0:Y.in])});if(Y&&A.name!==Y.name||(w===null||w===void 0?void 0:w.name)&&A.name!==(w===null||w===void 0?void 0:w.name))throw new UG("Conflicting names for parameter",{key:"name",values:W3([A.name,w===null||w===void 0?void 0:w.name,Y===null||Y===void 0?void 0:Y.name])});return{$ref:`#/components/parameters/${(W=$._internal)===null||W===void 0?void 0:W.refId}`}}generateInlineParameters($,w){var X;let G=C0.getMetadata($),E=(X=G===null||G===void 0?void 0:G.metadata)===null||X===void 0?void 0:X.param,J=this.getParameterRef(G,{in:w});if(J)return[J];if(J0($,"ZodObject")){let W=$._def.shape();return Object.entries(W).map(([A,D])=>{var U,N;let H=C0.getMetadata(D),L=this.getParameterRef(H,{in:w,name:A});if(L)return L;let F=(U=H===null||H===void 0?void 0:H.metadata)===null||U===void 0?void 0:U.param;if((F===null||F===void 0?void 0:F.name)&&F.name!==A)throw new UG("Conflicting names for parameter",{key:"name",values:[A,F.name]});if((F===null||F===void 0?void 0:F.in)&&F.in!==w)throw new UG(`Conflicting location for parameter ${(N=F.name)!==null&&N!==void 0?N:A}`,{key:"in",values:[w,F.in]});return this.generateParameter(D.openapi({param:{name:A,in:w}}))})}if((E===null||E===void 0?void 0:E.in)&&E.in!==w)throw new UG(`Conflicting location for parameter ${E.name}`,{key:"in",values:[w,E.in]});return[this.generateParameter($.openapi({param:{in:w}}))]}generateSimpleParameter($){var w;let X=C0.getParamMetadata($),G=(w=X===null||X===void 0?void 0:X.metadata)===null||w===void 0?void 0:w.param,E=!C0.isOptionalSchema($)&&!$.isNullable(),J=this.generateSchemaWithRef($);return Object.assign({schema:J,required:E},G?C0.buildParameterMetadata(G):{})}generateParameter($){var w;let X=C0.getMetadata($),G=(w=X===null||X===void 0?void 0:X.metadata)===null||w===void 0?void 0:w.param,E=G===null||G===void 0?void 0:G.name,J=G===null||G===void 0?void 0:G.in;if(!E)throw new g6({missingField:"name"});if(!J)throw new g6({missingField:"in",paramName:E});let W=this.generateSimpleParameter($);return Object.assign(Object.assign({},W),{in:J,name:E})}generateSchemaWithMetadata($){var w;let X=C0.unwrapChained($),G=C0.getMetadata($),E=C0.getDefaultValue($),J=((w=G===null||G===void 0?void 0:G.metadata)===null||w===void 0?void 0:w.type)?{type:G===null||G===void 0?void 0:G.metadata.type}:this.toOpenAPISchema(X,$.isNullable(),E);return(G===null||G===void 0?void 0:G.metadata)?C0.applySchemaMetadata(J,G.metadata):OG(J,x6)}constructReferencedOpenAPISchema($){var w;let X=C0.getMetadata($),G=C0.unwrapChained($),E=C0.getDefaultValue($),J=$.isNullable();if((w=X===null||X===void 0?void 0:X.metadata)===null||w===void 0?void 0:w.type)return this.versionSpecifics.mapNullableType(X.metadata.type,J);return this.toOpenAPISchema(G,J,E)}generateSimpleSchema($){var w;let X=C0.getMetadata($),G=C0.getRefId($);if(!G||!this.schemaRefs[G])return this.generateSchemaWithMetadata($);let E=this.schemaRefs[G],J={$ref:this.generateSchemaRef(G)},W=OG(C0.buildSchemaMetadata((w=X===null||X===void 0?void 0:X.metadata)!==null&&w!==void 0?w:{}),(D,U)=>D===void 0||bW(D,E[U]));if(W.type)return{allOf:[J,W]};let Y=OG(this.constructReferencedOpenAPISchema($),(D,U)=>D===void 0||bW(D,E[U])),A=C0.applySchemaMetadata(Y,W);if(Object.keys(A).length>0)return{allOf:[J,A]};return J}generateSchemaWithRef($){let w=C0.getRefId($),X=this.generateSimpleSchema($);if(w&&this.schemaRefs[w]===void 0)return this.schemaRefs[w]=X,{$ref:this.generateSchemaRef(w)};return X}generateSchemaRef($){return`#/components/schemas/${$}`}getRequestBody($){if(!$)return;let{content:w}=$,X=f6($,["content"]),G=this.getBodyContent(w);return Object.assign(Object.assign({},X),{content:G})}getParameters($){if(!$)return[];let{headers:w}=$,X=this.cleanParameter($.query),G=this.cleanParameter($.params),E=this.cleanParameter($.cookies),J=_6(()=>X?this.generateInlineParameters(X,"query"):[],{location:"query"}),W=_6(()=>G?this.generateInlineParameters(G,"path"):[],{location:"path"}),Y=_6(()=>E?this.generateInlineParameters(E,"cookie"):[],{location:"cookie"}),A=_6(()=>{if(Array.isArray(w))return w.flatMap((U)=>this.generateInlineParameters(U,"header"));let D=this.cleanParameter(w);return D?this.generateInlineParameters(D,"header"):[]},{location:"header"});return[...W,...J,...A,...Y]}cleanParameter($){if(!$)return;return J0($,"ZodEffects")?this.cleanParameter($._def.schema):$}generatePath($){let{method:w,path:X,request:G,responses:E}=$,J=f6($,["method","path","request","responses"]),W=y6(E,(U)=>{return this.getResponse(U)}),Y=_6(()=>this.getParameters(G),{route:`${w} ${X}`}),A=this.getRequestBody(G===null||G===void 0?void 0:G.body);return{[w]:Object.assign(Object.assign(Object.assign(Object.assign({},J),Y.length>0?{parameters:[...J.parameters||[],...Y]}:{}),A?{requestBody:A}:{}),{responses:W})}}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:X}=$,G=f6($,["content","headers"]),E=w?{content:this.getBodyContent(w)}:{};if(!X)return Object.assign(Object.assign({},G),E);let J=J0(X,"ZodObject")?this.getResponseHeaders(X):X;return Object.assign(Object.assign(Object.assign({},G),{headers:J}),E)}isReferenceObject($){return"$ref"in $}getResponseHeaders($){let w=$._def.shape();return y6(w,(G)=>this.generateSimpleParameter(G))}getBodyContent($){return y6($,(w)=>{if(!w||!Vk(w.schema))return w;let{schema:X}=w,G=f6(w,["schema"]),E=this.generateSchemaWithRef(X);return Object.assign({schema:E},G)})}toOpenAPISchema($,w,X){return this.openApiTransformer.transform($,w,(G)=>this.generateSchemaWithRef(G),(G)=>this.generateSchemaRef(G),X)}}class j3{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=Tk($);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 vW{constructor($){let w=new j3;this.generator=new CW($,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 jk($){return"type"in $&&$.type==="webhook"}class _W{constructor($){this.definitions=$,this.webhookRefs={};let w=new P3;this.generator=new CW(this.definitions,w)}generateDocument($){let w=this.generator.generateDocumentData();return this.definitions.filter(jk).forEach((X)=>this.generateSingleWebhook(X.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 bW,UG,g6,U3;var q3=B(()=>{bW=OJ;UG=class UG extends h6{constructor($,w){super($);this.data=w}};g6=class g6 extends h6{constructor($){super(`Missing parameter data, please specify \`${$.missingField}\` and other OpenAPI parameter props using the \`param\` field of \`ZodSchema.openapi\``);this.data=$}};U3=class U3 extends h6{constructor($){super("Unknown zod object type, please specify `type` and other OpenAPI props using `ZodSchema.openapi`.");this.data=$}}});var xW=($)=>{let w=$.split("/");if(w[0]==="")w.shift();return w},S3=($)=>{let{groups:w,path:X}=Pk($),G=xW(X);return qk(G,w)},Pk=($)=>{let w=[];return $=$.replace(/\{[^}]+\}/g,(X,G)=>{let E=`@${G}`;return w.push([E,X]),E}),{groups:w,path:$}},qk=($,w)=>{for(let X=w.length-1;X>=0;X--){let[G]=w[X];for(let E=$.length-1;E>=0;E--)if($[E].includes(G)){$[E]=$[E].replace(G,w[X][1]);break}}return $},NJ,Z3=($,w)=>{if($==="*")return"*";let X=$.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(X){let G=`${$}#${w}`;if(!NJ[G])if(X[2])NJ[G]=w&&w[0]!==":"&&w[0]!=="*"?[G,X[1],new RegExp(`^${X[2]}(?=/${w})`)]:[$,X[1],new RegExp(`^${X[2]}$`)];else NJ[G]=[$,X[1],!0];return NJ[G]}return null},NG=($,w)=>{try{return w($)}catch{return $.replace(/(?:%[0-9A-Fa-f]{2})+/g,(X)=>{try{return w(X)}catch{return X}})}},Sk=($)=>NG($,decodeURI),yW=($)=>{let w=$.url,X=w.indexOf("/",w.indexOf(":")+4),G=X;for(;G<w.length;G++){let E=w.charCodeAt(G);if(E===37){let J=w.indexOf("?",G),W=w.indexOf("#",G),Y=J===-1?W===-1?void 0:W:W===-1?J:Math.min(J,W),A=w.slice(X,Y);return Sk(A.includes("%25")?A.replace(/%25/g,"%2525"):A)}else if(E===63||E===35)break}return w.slice(X,G)},b3=($)=>{let w=yW($);return w.length>1&&w.at(-1)==="/"?w.slice(0,-1):w},S1=($,w,...X)=>{if(X.length)w=S1(w,...X);return`${$?.[0]==="/"?"":"/"}${$}${w==="/"?"":`${$?.at(-1)==="/"?"":"/"}${w?.[0]==="/"?w.slice(1):w}`}`},HJ=($)=>{if($.charCodeAt($.length-1)!==63||!$.includes(":"))return null;let w=$.split("/"),X=[],G="";return w.forEach((E)=>{if(E!==""&&!/\:/.test(E))G+="/"+E;else if(/\:/.test(E))if(/\?/.test(E)){if(X.length===0&&G==="")X.push("/");else X.push(G);let J=E.replace("?","");G+="/"+J,X.push(G)}else G+="/"+E}),X.filter((E,J,W)=>W.indexOf(E)===J)},fW=($)=>{if(!/[%+]/.test($))return $;if($.indexOf("+")!==-1)$=$.replace(/\+/g," ");return $.indexOf("%")!==-1?NG($,u6):$},k3=($,w,X)=>{let G;if(!X&&w&&!/[%+]/.test(w)){let W=$.indexOf("?",8);if(W===-1)return;if(!$.startsWith(w,W+1))W=$.indexOf(`&${w}`,W+1);while(W!==-1){let Y=$.charCodeAt(W+w.length+1);if(Y===61){let A=W+w.length+2,D=$.indexOf("&",A);return fW($.slice(A,D===-1?void 0:D))}else if(Y==38||isNaN(Y))return"";W=$.indexOf(`&${w}`,W+1)}if(G=/[%+]/.test($),!G)return}let E={};G??=/[%+]/.test($);let J=$.indexOf("?",8);while(J!==-1){let W=$.indexOf("&",J+1),Y=$.indexOf("=",J);if(Y>W&&W!==-1)Y=-1;let A=$.slice(J+1,Y===-1?W===-1?void 0:W:Y);if(G)A=fW(A);if(J=W,A==="")continue;let D;if(Y===-1)D="";else if(D=$.slice(Y+1,W===-1?void 0:W),G)D=fW(D);if(X){if(!(E[A]&&Array.isArray(E[A])))E[A]=[];E[A].push(D)}else E[A]??=D}return w?E[w]:E},C3,v3=($,w)=>{return k3($,w,!0)},u6;var vw=B(()=>{NJ={},C3=k3,u6=decodeURIComponent});var Zk,bk,gW=($,w)=>{if(w&&$.indexOf(w)===-1)return{};let X=$.trim().split(";"),G={};for(let E of X){E=E.trim();let J=E.indexOf("=");if(J===-1)continue;let W=E.substring(0,J).trim();if(w&&w!==W||!Zk.test(W))continue;let Y=E.substring(J+1).trim();if(Y.startsWith('"')&&Y.endsWith('"'))Y=Y.slice(1,-1);if(bk.test(Y)){if(G[W]=Y.indexOf("%")!==-1?NG(Y,u6):Y,w)break}}return G};var _3=B(()=>{vw();Zk=/^[\w!#$%&'*.^`|~+-]+$/,bk=/^[ !#-:<-[\]-~]*$/});var f3=($,w,X)=>{let G=$.req.raw.headers.get("Cookie");if(typeof w==="string"){if(!G)return;let J=w;if(X==="secure")J="__Secure-"+w;else if(X==="host")J="__Host-"+w;return gW(G,J)[J]}if(!G)return{};return gW(G)};var x3=B(()=>{_3()});var LJ;var hW=B(()=>{LJ=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 y3=()=>{};var g3=($,w)=>{return new Response($,{headers:{"Content-Type":w}}).formData()};var h3=B(()=>{y3()});var kk,Ck,vk,uW=($,w)=>{return async(X,G)=>{let E={},J=X.req.header("Content-Type");switch($){case"json":if(!J||!kk.test(J))break;try{E=await X.req.json()}catch{throw new LJ(400,{message:"Malformed JSON in request body"})}break;case"form":{if(!J||!(Ck.test(J)||vk.test(J)))break;let Y;if(X.req.bodyCache.formData)Y=await X.req.bodyCache.formData;else try{let D=await X.req.arrayBuffer();Y=await g3(D,J),X.req.bodyCache.formData=Y}catch(D){let U="Malformed FormData request.";throw U+=D instanceof Error?` ${D.message}`:` ${String(D)}`,new LJ(400,{message:U})}let A=Object.create(null);Y.forEach((D,U)=>{if(U.endsWith("[]"))(A[U]??=[]).push(D);else if(Array.isArray(A[U]))A[U].push(D);else if(Object.hasOwn(A,U))A[U]=[A[U],D];else A[U]=D}),E=A;break}case"query":E=Object.fromEntries(Object.entries(X.req.queries()).map(([Y,A])=>{return A.length===1?[Y,A[0]]:[Y,A]}));break;case"param":E=X.req.param();break;case"header":E=X.req.header();break;case"cookie":E=f3(X);break}let W=await w(E,X);if(W instanceof Response)return W;return X.req.addValidatedData($,W),await G()}};var u3=B(()=>{x3();hW();h3();kk=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,Ck=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,vk=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/});var c3=B(()=>{u3()});function _k($,w,X,G){return uW($,async(E,J)=>{let W=E;if($==="header"&&"_def"in w||$==="header"&&"_zod"in w){let A=Object.keys("in"in w?w.in.shape:w.shape),D=Object.fromEntries(A.map((U)=>[U.toLowerCase(),U]));W=Object.fromEntries(Object.entries(E).map(([U,N])=>[D[U]||U,N]))}let Y=G&&G.validationFunction?await G.validationFunction(w,W):await w.safeParseAsync(W);if(X){let A=await X({data:W,...Y,target:$},J);if(A){if(A instanceof Response)return A;if("response"in A)return A.response}}if(!Y.success)return J.json(Y,400);return Y.data})}var OX;var m3=B(()=>{c3();OX=_k});var cW=($,w,X)=>{return(G,E)=>{let J=-1;return W(0);async function W(Y){if(Y<=J)throw Error("next() called multiple times");J=Y;let A,D=!1,U;if($[Y])U=$[Y][0][0],G.req.routeIndex=Y;else U=Y===$.length&&E||void 0;if(U)try{A=await U(G,()=>W(Y+1))}catch(N){if(N instanceof Error&&w)G.error=N,A=await w(N,G),D=!0;else throw N}else if(G.finalized===!1&&X)A=await X(G);if(A&&(G.finalized===!1||D))G.res=A;return G}}};var n3=()=>{};var p3;var r3=B(()=>{p3=Symbol()});async function fk($,w){let X=await $.formData();if(X)return xk(X,w);return{}}function xk($,w){let X=Object.create(null);if($.forEach((G,E)=>{if(!(w.all||E.endsWith("[]")))X[E]=G;else yk(X,E,G)}),w.dot)Object.entries(X).forEach(([G,E])=>{if(G.includes("."))gk(X,G,E),delete X[G]});return X}var i3=async($,w=Object.create(null))=>{let{all:X=!1,dot:G=!1}=w,J=($ instanceof FJ?$.raw.headers:$.headers).get("Content-Type");if(J?.startsWith("multipart/form-data")||J?.startsWith("application/x-www-form-urlencoded"))return fk($,{all:X,dot:G});return{}},yk=($,w,X)=>{if($[w]!==void 0)if(Array.isArray($[w]))$[w].push(X);else $[w]=[$[w],X];else if(!w.endsWith("[]"))$[w]=X;else $[w]=[X]},gk=($,w,X)=>{if(/(?:^|\.)__proto__\./.test(w))return;let G=$,E=w.split(".");E.forEach((J,W)=>{if(W===E.length-1)G[J]=X;else{if(!G[J]||typeof G[J]!=="object"||Array.isArray(G[J])||G[J]instanceof File)G[J]=Object.create(null);G=G[J]}})};var o3=B(()=>{mW()});var t3=($)=>NG($,u6),FJ;var mW=B(()=>{hW();r3();o3();vw();FJ=class{raw;#$;#w;routeIndex=0;path;bodyCache={};constructor($,w="/",X=[[]]){this.raw=$,this.path=w,this.#w=X,this.#$={}}param($){return $?this.#X($):this.#J()}#X($){let w=this.#w[0][this.routeIndex][1][$],X=this.#E(w);return X&&/\%/.test(X)?t3(X):X}#J(){let $={},w=Object.keys(this.#w[0][this.routeIndex][1]);for(let X of w){let G=this.#E(this.#w[0][this.routeIndex][1][X]);if(G!==void 0)$[X]=/\%/.test(G)?t3(G):G}return $}#E($){return this.#w[1]?this.#w[1][$]:$}query($){return C3(this.url,$)}queries($){return v3(this.url,$)}header($){if($)return this.raw.headers.get($)??void 0;let w={};return this.raw.headers.forEach((X,G)=>{w[G]=X}),w}async parseBody($){return this.bodyCache.parsedBody??=await i3(this,$)}#G=($)=>{let{bodyCache:w,raw:X}=this,G=w[$];if(G)return G;let E=Object.keys(w)[0];if(E)return w[E].then((J)=>{if(E==="json")J=JSON.stringify(J);return new Response(J)[$]()});return w[$]=X[$]()};json(){return this.#G("text").then(($)=>JSON.parse($))}text(){return this.#G("text")}arrayBuffer(){return this.#G("arrayBuffer")}blob(){return this.#G("blob")}formData(){return this.#G("formData")}addValidatedData($,w){this.#$[$]=w}valid($){return this.#$[$]}get url(){return this.raw.url}get method(){return this.raw.method}get[p3](){return this.#w}get matchedRoutes(){return this.#w[0].map(([[,$]])=>$)}get routePath(){return this.#w[0].map(([[,$]])=>$)[this.routeIndex].path}}});var hk="text/plain; charset=UTF-8",nW=($,w)=>{return{"Content-Type":$,...w}},c6=($,w)=>new Response($,w),d3=class{#$;#w;env={};#X;finalized=!1;error;#J;#E;#G;#U;#A;#D;#Y;#O;#N;constructor($,w){if(this.#$=$,w)this.#E=w.executionCtx,this.env=w.env,this.#D=w.notFoundHandler,this.#N=w.path,this.#O=w.matchResult}get req(){return this.#w??=new FJ(this.#$,this.#N,this.#O),this.#w}get event(){if(this.#E&&"respondWith"in this.#E)return this.#E;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#E)return this.#E;else throw Error("This context has no ExecutionContext")}get res(){return this.#G||=c6(null,{headers:this.#Y??=new Headers})}set res($){if(this.#G&&$){$=c6($.body,$);for(let[w,X]of this.#G.headers.entries()){if(w==="content-type")continue;if(w==="set-cookie"){let G=this.#G.headers.getSetCookie();$.headers.delete("set-cookie");for(let E of G)$.headers.append("set-cookie",E)}else $.headers.set(w,X)}}this.#G=$,this.finalized=!0}render=(...$)=>{return this.#A??=(w)=>this.html(w),this.#A(...$)};setLayout=($)=>this.#U=$;getLayout=()=>this.#U;setRenderer=($)=>{this.#A=$};header=($,w,X)=>{if(this.finalized)this.#G=c6(this.#G.body,this.#G);let G=this.#G?this.#G.headers:this.#Y??=new Headers;if(w===void 0)G.delete($);else if(X?.append)G.append($,w);else G.set($,w)};status=($)=>{this.#J=$};set=($,w)=>{this.#X??=new Map,this.#X.set($,w)};get=($)=>{return this.#X?this.#X.get($):void 0};get var(){if(!this.#X)return{};return Object.fromEntries(this.#X)}#W($,w,X){let G=this.#G?new Headers(this.#G.headers):this.#Y??new Headers;if(typeof w==="object"&&"headers"in w){let J=w.headers instanceof Headers?w.headers:new Headers(w.headers);for(let[W,Y]of J)if(W.toLowerCase()==="set-cookie")G.append(W,Y);else G.set(W,Y)}if(X)for(let[J,W]of Object.entries(X))if(typeof W==="string")G.set(J,W);else{G.delete(J);for(let Y of W)G.append(J,Y)}let E=typeof w==="number"?w:w?.status??this.#J;return c6($,{status:E,headers:G})}newResponse=(...$)=>this.#W(...$);body=($,w,X)=>this.#W($,w,X);text=($,w,X)=>{return!this.#Y&&!this.#J&&!w&&!X&&!this.finalized?new Response($):this.#W($,w,nW(hk,X))};json=($,w,X)=>{return this.#W(JSON.stringify($),w,nW("application/json",X))};html=($,w,X)=>{let G=(E)=>this.#W(E,w,nW("text/html; charset=UTF-8",X));return typeof $==="object"?qW($,PW.Stringify,!1,{}).then(G):G($)};redirect=($,w)=>{let X=String($);return this.header("Location",!/[^\x00-\xFF]/.test(X)?X:encodeURI(X)),this.newResponse(null,w??302)};notFound=()=>{return this.#D??=()=>c6(),this.#D(this)}};var l3=B(()=>{mW();SW()});var I0="ALL",s3="all",a3,MJ="Can not add a route since the matcher is already built.",zJ;var NX=B(()=>{a3=["get","post","put","delete","options","patch"],zJ=class extends Error{}});var e3="__COMPOSED_HANDLER";var $F=()=>{};var uk=($)=>{return $.text("404 Not Found",404)},wF=($,w)=>{if("getResponse"in $){let X=$.getResponse();return w.newResponse(X.body,X)}return console.error($),w.text("Internal Server Error",500)},XF=class ${get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#$="/";routes=[];constructor(w={}){[...a3,s3].forEach((J)=>{this[J]=(W,...Y)=>{if(typeof W==="string")this.#$=W;else this.#J(J,this.#$,W);return Y.forEach((A)=>{this.#J(J,this.#$,A)}),this}}),this.on=(J,W,...Y)=>{for(let A of[W].flat()){this.#$=A;for(let D of[J].flat())Y.map((U)=>{this.#J(D.toUpperCase(),this.#$,U)})}return this},this.use=(J,...W)=>{if(typeof J==="string")this.#$=J;else this.#$="*",W.unshift(J);return W.forEach((Y)=>{this.#J(I0,this.#$,Y)}),this};let{strict:G,...E}=w;Object.assign(this,E),this.getPath=G??!0?w.getPath??yW:b3}#w(){let w=new $({router:this.router,getPath:this.getPath});return w.errorHandler=this.errorHandler,w.#X=this.#X,w.routes=this.routes,w}#X=uk;errorHandler=wF;route(w,X){let G=this.basePath(w);return X.routes.map((E)=>{let J;if(X.errorHandler===wF)J=E.handler;else J=async(W,Y)=>(await cW([],X.errorHandler)(W,()=>E.handler(W,Y))).res,J[e3]=E.handler;G.#J(E.method,E.path,J)}),this}basePath(w){let X=this.#w();return X._basePath=S1(this._basePath,w),X}onError=(w)=>{return this.errorHandler=w,this};notFound=(w)=>{return this.#X=w,this};mount(w,X,G){let E,J;if(G)if(typeof G==="function")J=G;else if(J=G.optionHandler,G.replaceRequest===!1)E=(A)=>A;else E=G.replaceRequest;let W=J?(A)=>{let D=J(A);return Array.isArray(D)?D:[D]}:(A)=>{let D=void 0;try{D=A.executionCtx}catch{}return[A.env,D]};E||=(()=>{let A=S1(this._basePath,w),D=A==="/"?0:A.length;return(U)=>{let N=new URL(U.url);return N.pathname=N.pathname.slice(D)||"/",new Request(N,U)}})();let Y=async(A,D)=>{let U=await X(E(A.req.raw),...W(A));if(U)return U;await D()};return this.#J(I0,S1(w,"*"),Y),this}#J(w,X,G){w=w.toUpperCase(),X=S1(this._basePath,X);let E={basePath:this._basePath,path:X,method:w,handler:G};this.router.add(w,X,[G,E]),this.routes.push(E)}#E(w,X){if(w instanceof Error)return this.errorHandler(w,X);throw w}#G(w,X,G,E){if(E==="HEAD")return(async()=>new Response(null,await this.#G(w,X,G,"GET")))();let J=this.getPath(w,{env:G}),W=this.router.match(E,J),Y=new d3(w,{path:J,matchResult:W,env:G,executionCtx:X,notFoundHandler:this.#X});if(W[0].length===1){let D;try{D=W[0][0][0][0](Y,async()=>{Y.res=await this.#X(Y)})}catch(U){return this.#E(U,Y)}return D instanceof Promise?D.then((U)=>U||(Y.finalized?Y.res:this.#X(Y))).catch((U)=>this.#E(U,Y)):D??this.#X(Y)}let A=cW(W[0],this.errorHandler,this.#X);return(async()=>{try{let D=await A(Y);if(!D.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return D.res}catch(D){return this.#E(D,Y)}})()}fetch=(w,...X)=>{return this.#G(w,X[1],X[0],w.method)};request=(w,X,G,E)=>{if(w instanceof Request)return this.fetch(X?new Request(w,X):w,G,E);return w=w.toString(),this.fetch(new Request(/^https?:\/\//.test(w)?w:`http://localhost${S1("/",w)}`,X),G,E)};fire=()=>{addEventListener("fetch",(w)=>{w.respondWith(this.#G(w.request,w,void 0,w.request.method))})}};var GF=B(()=>{n3();l3();NX();$F();vw()});function QJ($,w){let X=this.buildAllMatchers(),G=(E,J)=>{let W=X[E]||X[I0],Y=W[2][J];if(Y)return Y;let A=J.match(W[0]);if(!A)return[[],m6];let D=A.indexOf("",1);return[W[1][D],A]};return this.match=G,G($,w)}var m6;var pW=B(()=>{NX();m6=[]});function mk($,w){if($.length===1)return w.length===1?$<w?-1:1:-1;if(w.length===1)return 1;if($===n6||$===p6)return 1;else if(w===n6||w===p6)return-1;if($===BJ)return 1;else if(w===BJ)return-1;return $.length===w.length?$<w?-1:1:w.length-$.length}var BJ="[^/]+",n6=".*",p6="(?:|/.*)",HX,ck,EF=class ${#$;#w;#X=Object.create(null);insert(w,X,G,E,J){if(w.length===0){if(this.#$!==void 0)throw HX;if(J)return;this.#$=X;return}let[W,...Y]=w,A=W==="*"?Y.length===0?["","",n6]:["","",BJ]:W==="/*"?["","",p6]:W.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),D;if(A){let U=A[1],N=A[2]||BJ;if(U&&A[2]){if(N===".*")throw HX;if(N=N.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(N))throw HX}if(D=this.#X[N],!D){if(Object.keys(this.#X).some((H)=>H!==n6&&H!==p6))throw HX;if(J)return;if(D=this.#X[N]=new $,U!=="")D.#w=E.varIndex++}if(!J&&U!=="")G.push([U,D.#w])}else if(D=this.#X[W],!D){if(Object.keys(this.#X).some((U)=>U.length>1&&U!==n6&&U!==p6))throw HX;if(J)return;D=this.#X[W]=new $}D.insert(Y,X,G,E,J)}buildRegExpStr(){let X=Object.keys(this.#X).sort(mk).map((G)=>{let E=this.#X[G];return(typeof E.#w==="number"?`(${G})@${E.#w}`:ck.has(G)?`\\${G}`:G)+E.buildRegExpStr()});if(typeof this.#$==="number")X.unshift(`#${this.#$}`);if(X.length===0)return"";if(X.length===1)return X[0];return"(?:"+X.join("|")+")"}};var rW=B(()=>{HX=Symbol(),ck=new Set(".\\+*[^]$()")});var JF=class{#$={varIndex:0};#w=new EF;insert($,w,X){let G=[],E=[];for(let W=0;;){let Y=!1;if($=$.replace(/\{[^}]+\}/g,(A)=>{let D=`@\\${W}`;return E[W]=[D,A],W++,Y=!0,D}),!Y)break}let J=$.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let W=E.length-1;W>=0;W--){let[Y]=E[W];for(let A=J.length-1;A>=0;A--)if(J[A].indexOf(Y)!==-1){J[A]=J[A].replace(Y,E[W][1]);break}}return this.#w.insert(J,w,G,this.#$,X),G}buildRegExp(){let $=this.#w.buildRegExpStr();if($==="")return[/^$/,[],[]];let w=0,X=[],G=[];return $=$.replace(/#(\d+)|@(\d+)|\.\*\$/g,(E,J,W)=>{if(J!==void 0)return X[++w]=Number(J),"$()";if(W!==void 0)return G[Number(W)]=++w,"";return""}),[new RegExp(`^${$}`),X,G]}};var WF=B(()=>{rW()});function AF($){return YF[$]??=new RegExp($==="*"?"":`^${$.replace(/\/\*$|([.\\+*[^\]$()])/g,(w,X)=>X?`\\${X}`:"(?:|/.*)")}$`)}function pk(){YF=Object.create(null)}function rk($){let w=new JF,X=[];if($.length===0)return nk;let G=$.map((D)=>[!/\*|\/:/.test(D[0]),...D]).sort(([D,U],[N,H])=>D?1:N?-1:U.length-H.length),E=Object.create(null);for(let D=0,U=-1,N=G.length;D<N;D++){let[H,L,F]=G[D];if(H)E[L]=[F.map(([z])=>[z,Object.create(null)]),m6];else U++;let M;try{M=w.insert(L,U,H)}catch(z){throw z===HX?new zJ(L):z}if(H)continue;X[U]=F.map(([z,Q])=>{let R=Object.create(null);Q-=1;for(;Q>=0;Q--){let[T,v]=M[Q];R[T]=v}return[z,R]})}let[J,W,Y]=w.buildRegExp();for(let D=0,U=X.length;D<U;D++)for(let N=0,H=X[D].length;N<H;N++){let L=X[D][N]?.[1];if(!L)continue;let F=Object.keys(L);for(let M=0,z=F.length;M<z;M++)L[F[M]]=Y[L[F[M]]]}let A=[];for(let D in W)A[D]=X[W[D]];return[J,A,E]}function HG($,w){if(!$)return;for(let X of Object.keys($).sort((G,E)=>E.length-G.length))if(AF(X).test(w))return[...$[X]];return}var nk,YF,KJ=class{name="RegExpRouter";#$;#w;constructor(){this.#$={[I0]:Object.create(null)},this.#w={[I0]:Object.create(null)}}add($,w,X){let G=this.#$,E=this.#w;if(!G||!E)throw Error(MJ);if(!G[$])[G,E].forEach((Y)=>{Y[$]=Object.create(null),Object.keys(Y[I0]).forEach((A)=>{Y[$][A]=[...Y[I0][A]]})});if(w==="/*")w="*";let J=(w.match(/\/:/g)||[]).length;if(/\*$/.test(w)){let Y=AF(w);if($===I0)Object.keys(G).forEach((A)=>{G[A][w]||=HG(G[A],w)||HG(G[I0],w)||[]});else G[$][w]||=HG(G[$],w)||HG(G[I0],w)||[];Object.keys(G).forEach((A)=>{if($===I0||$===A)Object.keys(G[A]).forEach((D)=>{Y.test(D)&&G[A][D].push([X,J])})}),Object.keys(E).forEach((A)=>{if($===I0||$===A)Object.keys(E[A]).forEach((D)=>Y.test(D)&&E[A][D].push([X,J]))});return}let W=HJ(w)||[w];for(let Y=0,A=W.length;Y<A;Y++){let D=W[Y];Object.keys(E).forEach((U)=>{if($===I0||$===U)E[U][D]||=[...HG(G[U],D)||HG(G[I0],D)||[]],E[U][D].push([X,J-A+Y+1])})}}match=QJ;buildAllMatchers(){let $=Object.create(null);return Object.keys(this.#w).concat(Object.keys(this.#$)).forEach((w)=>{$[w]||=this.#X(w)}),this.#$=this.#w=void 0,pk(),$}#X($){let w=[],X=$===I0;if([this.#$,this.#w].forEach((G)=>{let E=G[$]?Object.keys(G[$]).map((J)=>[J,G[$][J]]):[];if(E.length!==0)X||=!0,w.push(...E);else if($!==I0)w.push(...Object.keys(G[I0]).map((J)=>[J,G[I0][J]]))}),!X)return null;else return rk(w)}};var iW=B(()=>{NX();vw();pW();rW();WF();nk=[/^$/,[],Object.create(null)],YF=Object.create(null)});var ik=class{name="PreparedRegExpRouter";#$;#w;constructor($,w){this.#$=$,this.#w=w}#X($,w){let X=this.#$[$];X[1].forEach((G)=>G&&G.push(w)),Object.values(X[2]).forEach((G)=>G[0].push(w))}#J($,w,X,G,E){let J=this.#$[$];if(!E)J[2][w][0].push([X,{}]);else G.forEach((W)=>{if(typeof W==="number")J[1][W].push([X,E]);else J[2][W||w][0].push([X,E])})}add($,w,X){if(!this.#$[$]){let E=this.#$[I0],J={};for(let W in E[2])J[W]=[E[2][W][0].slice(),m6];this.#$[$]=[E[0],E[1].map((W)=>Array.isArray(W)?W.slice():0),J]}if(w==="/*"||w==="*"){let E=[X,{}];if($===I0)for(let J in this.#$)this.#X(J,E);else this.#X($,E);return}let G=this.#w[w];if(!G)throw Error(`Path ${w} is not registered`);for(let[E,J]of G)if($===I0)for(let W in this.#$)this.#J(W,w,X,E,J);else this.#J($,w,X,E,J)}buildAllMatchers(){return this.#$}match=QJ};var DF=B(()=>{NX();pW();iW()});var UF=B(()=>{iW();DF()});var oW=class{name="SmartRouter";#$=[];#w=[];constructor($){this.#$=$.routers}add($,w,X){if(!this.#w)throw Error(MJ);this.#w.push([$,w,X])}match($,w){if(!this.#w)throw Error("Fatal error");let X=this.#$,G=this.#w,E=X.length,J=0,W;for(;J<E;J++){let Y=X[J];try{for(let A=0,D=G.length;A<D;A++)Y.add(...G[A]);W=Y.match($,w)}catch(A){if(A instanceof zJ)continue;throw A}this.match=Y.match.bind(Y),this.#$=[Y],this.#w=void 0;break}if(J===E)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,W}get activeRouter(){if(this.#w||this.#$.length!==1)throw Error("No active router has been determined yet.");return this.#$[0]}};var OF=B(()=>{NX()});var NF=B(()=>{OF()});var r6,ok=($)=>{for(let w in $)return!0;return!1},HF=class ${#$;#w;#X;#J=0;#E=r6;constructor(w,X,G){if(this.#w=G||Object.create(null),this.#$=[],w&&X){let E=Object.create(null);E[w]={handler:X,possibleKeys:[],score:0},this.#$=[E]}this.#X=[]}insert(w,X,G){this.#J=++this.#J;let E=this,J=S3(X),W=[];for(let Y=0,A=J.length;Y<A;Y++){let D=J[Y],U=J[Y+1],N=Z3(D,U),H=Array.isArray(N)?N[0]:D;if(H in E.#w){if(E=E.#w[H],N)W.push(N[1]);continue}if(E.#w[H]=new $,N)E.#X.push(N),W.push(N[1]);E=E.#w[H]}return E.#$.push({[w]:{handler:G,possibleKeys:W.filter((Y,A,D)=>D.indexOf(Y)===A),score:this.#J}}),E}#G(w,X,G,E,J){for(let W=0,Y=X.#$.length;W<Y;W++){let A=X.#$[W],D=A[G]||A[I0],U={};if(D!==void 0){if(D.params=Object.create(null),w.push(D),E!==r6||J&&J!==r6)for(let N=0,H=D.possibleKeys.length;N<H;N++){let L=D.possibleKeys[N],F=U[D.score];D.params[L]=J?.[L]&&!F?J[L]:E[L]??J?.[L],U[D.score]=!0}}}}search(w,X){let G=[];this.#E=r6;let J=[this],W=xW(X),Y=[],A=W.length,D=null;for(let U=0;U<A;U++){let N=W[U],H=U===A-1,L=[];for(let M=0,z=J.length;M<z;M++){let Q=J[M],R=Q.#w[N];if(R)if(R.#E=Q.#E,H){if(R.#w["*"])this.#G(G,R.#w["*"],w,Q.#E);this.#G(G,R,w,Q.#E)}else L.push(R);for(let T=0,v=Q.#X.length;T<v;T++){let f=Q.#X[T],k=Q.#E===r6?{}:{...Q.#E};if(f==="*"){let c0=Q.#w["*"];if(c0)this.#G(G,c0,w,Q.#E),c0.#E=k,L.push(c0);continue}let[m,F0,b0]=f;if(!N&&!(b0 instanceof RegExp))continue;let f0=Q.#w[m];if(b0 instanceof RegExp){if(D===null){D=Array(A);let J$=X[0]==="/"?1:0;for(let G1=0;G1<A;G1++)D[G1]=J$,J$+=W[G1].length+1}let c0=X.substring(D[U]),K0=b0.exec(c0);if(K0){if(k[F0]=K0[0],this.#G(G,f0,w,Q.#E,k),ok(f0.#w)){f0.#E=k;let J$=K0[0].match(/\//)?.length??0;(Y[J$]||=[]).push(f0)}continue}}if(b0===!0||b0.test(N))if(k[F0]=N,H){if(this.#G(G,f0,w,k,Q.#E),f0.#w["*"])this.#G(G,f0.#w["*"],w,k,Q.#E)}else f0.#E=k,L.push(f0)}}let F=Y.shift();J=F?L.concat(F):L}if(G.length>1)G.sort((U,N)=>{return U.score-N.score});return[G.map(({handler:U,params:N})=>[U,N])]}};var LF=B(()=>{NX();vw();r6=Object.create(null)});var tW=class{name="TrieRouter";#$;constructor(){this.#$=new HF}add($,w,X){let G=HJ(w);if(G){for(let E=0,J=G.length;E<J;E++)this.#$.insert($,G[E],X);return}this.#$.insert($,w,X)}match($,w){return this.#$.search($,w)}};var FF=B(()=>{vw();LF()});var MF=B(()=>{FF()});var dW;var zF=B(()=>{GF();UF();NF();MF();dW=class extends XF{constructor($={}){super($);this.router=$.router??new oW({routers:[new KJ,new tW]})}}});var QF=B(()=>{zF()});function BF($,w){let X={};return Object.keys($.paths).forEach((G)=>{X[S1(w.replaceAll(/:([^\/]+)/g,"{$1}"),G)]=$.paths[G]}),{...$,paths:X}}function KF($){return/^application\/([a-z-\.]+\+)?json/.test($)}function VF($){return $.startsWith("multipart/form-data")||$.startsWith("application/x-www-form-urlencoded")}var a0,t=($)=>{let w={...$,getRoutingPath(){return $.path.replaceAll(/\/{(.+?)}/g,"/:$1")}};return Object.defineProperty(w,"getRoutingPath",{enumerable:!1})};var A1=B(()=>{q3();m3();QF();vw();aG();a0=class $ extends dW{openAPIRegistry;defaultHook;constructor(w){super(w);this.openAPIRegistry=new kW,this.defaultHook=w?.defaultHook}openapi=({middleware:w,hide:X,...G},E,J=this.defaultHook)=>{if(!X)this.openAPIRegistry.registerPath(G);let W=[];if(G.request?.query){let D=OX("query",G.request.query,J);W.push(D)}if(G.request?.params){let D=OX("param",G.request.params,J);W.push(D)}if(G.request?.headers){let D=OX("header",G.request.headers,J);W.push(D)}if(G.request?.cookies){let D=OX("cookie",G.request.cookies,J);W.push(D)}let Y=G.request?.body?.content;if(Y)for(let D of Object.keys(Y)){if(!Y[D])continue;let U=Y[D].schema;if(!(U instanceof w0))continue;if(KF(D)){let N=OX("json",U,J);if(G.request?.body?.required)W.push(N);else{let H=async(L,F)=>{if(L.req.header("content-type")){if(KF(L.req.header("content-type")))return await N(L,F)}L.req.addValidatedData("json",{}),await F()};W.push(H)}}if(VF(D)){let N=OX("form",U,J);if(G.request?.body?.required)W.push(N);else{let H=async(L,F)=>{if(L.req.header("content-type")){if(VF(L.req.header("content-type")))return await N(L,F)}L.req.addValidatedData("form",{}),await F()};W.push(H)}}}let A=w?Array.isArray(w)?w:[w]:[];return this.on([G.method],G.path.replaceAll(/\/{(.+?)}/g,"/:$1"),...A,...W,E),this};getOpenAPIDocument=(w)=>{let G=new vW(this.openAPIRegistry.definitions).generateDocument(w);return this._basePath?BF(G,this._basePath):G};getOpenAPI31Document=(w)=>{let G=new _W(this.openAPIRegistry.definitions).generateDocument(w);return this._basePath?BF(G,this._basePath):G};doc=(w,X)=>{return this.get(w,(G)=>{let E=typeof X==="function"?X(G):X;try{let J=this.getOpenAPIDocument(E);return G.json(J)}catch(J){return G.json(J,500)}})};doc31=(w,X)=>{return this.get(w,(G)=>{let E=typeof X==="function"?X(G):X;try{let J=this.getOpenAPI31Document(E);return G.json(J)}catch(J){return G.json(J,500)}})};route(w,X){let G=w.replaceAll(/:([^\/]+)/g,"{$1}");if(super.route(w,X),!(X instanceof $))return this;return X.openAPIRegistry.definitions.forEach((E)=>{switch(E.type){case"component":return this.openAPIRegistry.registerComponent(E.componentType,E.name,E.component);case"route":{this.openAPIRegistry.registerPath({...E.route,path:S1(G,X._basePath.replaceAll(/:([^\/]+)/g,"{$1}"),E.route.path)});return}case"webhook":{this.openAPIRegistry.registerWebhook({...E.webhook,path:S1(G,X._basePath.replaceAll(/:([^\/]+)/g,"{$1}"),E.webhook.path)});return}case"schema":return this.openAPIRegistry.register(E.schema._def.openapi._internal.refId,E.schema);case"parameter":return this.openAPIRegistry.registerParameter(E.schema._def.openapi._internal.refId,E.schema);default:throw Error(`Unknown registry type: ${E}`)}}),this}basePath(w){return new $({...super.basePath(w),defaultHook:this.defaultHook})}};Y3(O)});var LG,M0,Ow,lW;var Z1=B(()=>{LG=class LG extends Error{code;statusCode;constructor($,w,X=500){super($);this.code=w;this.statusCode=X;this.name="OrcError"}};M0=class M0 extends LG{constructor($,w){super(`${$} not found: ${w}`,"NOT_FOUND",404);this.name="NotFoundError"}};Ow=class Ow extends LG{constructor($){super($,"VALIDATION_ERROR",400);this.name="ValidationError"}};lW=class lW extends LG{constructor($="Unauthorized"){super($,"UNAUTHORIZED",401);this.name="UnauthorizedError"}}});function RF($){return async(w,X)=>{if(!$)return X();let G=w.req.header("Authorization");if(!G?.startsWith("Bearer ")||G.slice(7)!==$)throw new lW;return X()}}var TF=B(()=>{Z1()});var VJ,tk,dk,lk,sk;var IF=B(()=>{A1();HW();VJ=new a0,tk=O.object({running:O.boolean(),status:O.string()}).openapi("GatewayStatus"),dk=O.object({platform:O.string(),chat_id:O.string(),text:O.string(),thread_id:O.string().optional()}).openapi("GatewaySend"),lk=t({method:"get",path:"/gateway/status",tags:["Gateway"],summary:"Get gateway status",responses:{200:{content:{"application/json":{schema:tk}},description:"Gateway status"}}}),sk=t({method:"post",path:"/gateway/send",tags:["Gateway"],summary:"Send a message via the gateway",request:{body:{content:{"application/json":{schema:dk}}}},responses:{204:{description:"Message sent"},503:{content:{"application/json":{schema:O.object({error:O.string()})}},description:"Gateway not running"}}});VJ.openapi(lk,async($)=>{let w=XJ()!==null;return $.json({running:w,status:NW()})});VJ.openapi(sk,async($)=>{if(!XJ())return $.json({error:"Gateway is not running"},503);let{platform:w,chat_id:X,text:G,thread_id:E}=$.req.valid("json");return await OW(w,X,G,E?{threadId:E}:void 0),$.body(null,204)})});var sW,ak,ek;var jF=B(()=>{A1();sW=new a0,ak=t({method:"get",path:"/health",tags:["System"],summary:"Health check",responses:{200:{description:"Service is healthy",content:{"application/json":{schema:O.object({status:O.literal("ok"),version:O.string(),uptime:O.number()})}}}}}),ek=Date.now();sW.openapi(ak,($)=>{return $.json({status:"ok",version:"0.0.1",uptime:Math.floor((Date.now()-ek)/1000)})})});var RJ,TJ,aW,PF,eW,K10,V10,R10,$7,T10,I10,j10;var IJ=B(()=>{aG();RJ=O.enum(["todo","doing","review","changes_requested","blocked","done","cancelled"]),TJ=O.enum(["low","normal","high","critical"]),aW=O.enum(["one-shot","cron","watch","webhook","manual","bridge-msg"]),PF=O.enum(["pending","running","success","failed","cancelled","skipped"]),eW=O.enum(["skip","queue","kill"]),K10=O.enum(["low","normal","high","critical"]),V10=O.enum(["telegram","slack","discord","feishu"]),R10=O.enum(["direct","agent:claude","agent:codex","agent:cursor","multi"]).or(O.string().startsWith("job:")),$7=O.enum(["blocks","blocked_by","relates_to","duplicates","clones","subtask_of","parent_of"]),T10=O.enum(["active","archived","paused"]),I10=O.enum(["solo","pair","parallel","handoff"]),j10=O.enum(["solo","human_agent","multi_agent"])});function X7($){return{...$,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 UC($){return{...$,started_at:$.started_at?.toISOString()??null,ended_at:$.ended_at?.toISOString()??null,created_at:$.created_at.toISOString()}}var $C,_w,w7,wC,XC,GC,EC,JC,WC,YC,AC,DC;var qF=B(()=>{A1();Z1();l$();f$();IJ();c$();u$();bw();g$();$C=P0("api:jobs"),_w=new a0,w7=O.object({id:O.string(),name:O.string(),description:O.string().nullable(),command:O.string(),trigger_type:aW,cron_expr:O.string().nullable(),enabled:O.boolean(),timeout_secs:O.number(),max_retries:O.number(),overlap:eW,notify_on:O.enum(["never","failure","always"]),run_count:O.number(),last_run_at:O.string().datetime().nullable(),next_run_at:O.string().datetime().nullable(),created_at:O.string().datetime(),updated_at:O.string().datetime()}).openapi("Job"),wC=O.object({name:O.string().min(1).max(100),description:O.string().optional(),command:O.string().min(1),trigger_type:aW,cron_expr:O.string().optional(),watch_path:O.string().optional(),timeout_secs:O.number().int().positive().optional().default(300),max_retries:O.number().int().min(0).optional().default(0),overlap:eW.optional().default("skip"),notify_on:O.enum(["never","failure","always"]).optional().default("failure"),env_vars:O.record(O.string()).optional(),working_dir:O.string().optional()}).openapi("CreateJob"),XC=O.object({id:O.string(),job_id:O.string(),status:PF,trigger_by:O.string().nullable(),started_at:O.string().datetime().nullable(),ended_at:O.string().datetime().nullable(),exit_code:O.number().nullable(),error_msg:O.string().nullable(),retry_num:O.number(),created_at:O.string().datetime()}).openapi("JobRun"),GC=O.object({id:O.number(),run_id:O.string(),ts:O.string().datetime(),stream:O.enum(["stdout","stderr"]),line:O.string()}).openapi("JobRunLog"),EC=t({method:"get",path:"/jobs",tags:["Jobs"],summary:"List jobs",request:{query:O.object({enabled:O.coerce.boolean().optional(),limit:O.coerce.number().int().min(1).max(100).optional().default(50)})},responses:{200:{description:"Jobs",content:{"application/json":{schema:O.object({jobs:O.array(w7)})}}}}}),JC=t({method:"get",path:"/jobs/{id}",tags:["Jobs"],summary:"Get job",request:{params:O.object({id:O.string()})},responses:{200:{description:"Job",content:{"application/json":{schema:w7}}}}}),WC=t({method:"post",path:"/jobs",tags:["Jobs"],summary:"Create job",request:{body:{content:{"application/json":{schema:wC}}}},responses:{201:{description:"Created",content:{"application/json":{schema:w7}}}}}),YC=t({method:"post",path:"/jobs/{id}/trigger",tags:["Jobs"],summary:"Manually trigger a job",request:{params:O.object({id:O.string()})},responses:{202:{description:"Triggered",content:{"application/json":{schema:O.object({run_id:O.string()})}}}}}),AC=t({method:"get",path:"/jobs/{id}/runs",tags:["Jobs"],summary:"List job runs",request:{params:O.object({id:O.string()}),query:O.object({limit:O.coerce.number().int().min(1).max(50).optional().default(20)})},responses:{200:{description:"Runs",content:{"application/json":{schema:O.object({runs:O.array(XC)})}}}}}),DC=t({method:"get",path:"/jobs/{id}/runs/{runId}/logs",tags:["Jobs"],summary:"Stream log lines for a specific run",request:{params:O.object({id:O.string(),runId:O.string()}),query:O.object({stream:O.enum(["stdout","stderr"]).optional(),limit:O.coerce.number().int().min(1).max(5000).optional().default(500)})},responses:{200:{description:"Log lines",content:{"application/json":{schema:O.object({logs:O.array(GC)})}}}}});_w.openapi(EC,async($)=>{let w=g(),{limit:X}=$.req.valid("query"),G=await w.query.jobs.findMany({limit:X,orderBy:(E,{asc:J})=>[J(E.name)]});return $.json({jobs:G.map(X7)})});_w.openapi(JC,async($)=>{let w=g(),{id:X}=$.req.valid("param"),G=await w.query.jobs.findFirst({where:S(d0.id,X)});if(!G)throw new M0("Job",X);return $.json(X7(G))});_w.openapi(WC,async($)=>{let w=g(),X=$.req.valid("json"),G=new Date,E=e();await w.insert(d0).values({id:E,name:X.name,description:X.description,command:X.command,trigger_type:X.trigger_type,cron_expr:X.cron_expr,watch_path:X.watch_path,timeout_secs:X.timeout_secs,max_retries:X.max_retries,overlap:X.overlap,notify_on:X.notify_on,env_vars:X.env_vars,working_dir:X.working_dir,created_at:G,updated_at:G});let J=await w.query.jobs.findFirst({where:S(d0.id,E)});if(!J)throw Error("Expected job to exist after write");return $.json(X7(J),201)});_w.openapi(YC,async($)=>{let w=g(),{id:X}=$.req.valid("param");if(!await w.query.jobs.findFirst({where:S(d0.id,X)}))throw new M0("Job",X);let E=e();return await w.insert(l0).values({id:E,job_id:X,status:"pending",trigger_by:"api",created_at:new Date}),$1({jobId:X,runId:E,triggerBy:"api"}).catch((J)=>$C.error(`Background execution failed for run ${E}: ${J instanceof Error?J.message:String(J)}`)),$.json({run_id:E},202)});_w.openapi(AC,async($)=>{let w=g(),{id:X}=$.req.valid("param"),{limit:G}=$.req.valid("query"),E=await w.query.job_runs.findMany({where:S(l0.job_id,X),limit:G,orderBy:[p0(l0.created_at)]});return $.json({runs:E.map(UC)})});_w.openapi(DC,async($)=>{let w=g(),{id:X,runId:G}=$.req.valid("param"),{stream:E,limit:J}=$.req.valid("query"),W=await w.query.job_runs.findFirst({where:S(l0.id,G)});if(!W||W.job_id!==X)throw new M0("JobRun",G);let Y=await w.query.job_run_logs.findMany({where:E?Y$(S(Zw.run_id,G),S(Zw.stream,E)):S(Zw.run_id,G),limit:J,orderBy:[D4(Zw.ts)]});return $.json({logs:Y.map((A)=>({...A,ts:A.ts.toISOString()}))})})});function OC($,w=80){return $.length<=w?$:`${$.slice(0,w-1)}\u2026`}function NC($){let w=Date.now()-$*1000,X=Math.floor(w/60000);if(X<60)return`${X}m ago`;let G=Math.floor(X/60);if(G<24)return`${G}h ago`;return`${Math.floor(G/24)}d ago`}function PJ($,w,X){return{id:$.id,snippet:OC($.content),scope:$.scope,type:$.type??"fact",importance:$.importance,age:NC($.created_at),rank:w,matchLayer:X}}function E7(){return g().$client}function ZF($,w){let X=[],G=[];if($)X.push("m.scope = ?"),G.push($);if(w)X.push("m.type = ?"),G.push(w);return{clause:X.length?` AND ${X.join(" AND ")}`:"",params:G}}function jJ($,w,X,G,E,J){let{clause:W,params:Y}=ZF(G,E),A=`SELECT ${FG}
|
|
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}
|
|
410
440
|
FROM ${w} f JOIN memories m ON m.id = f.id
|
|
411
|
-
WHERE f.${w} MATCH ?${
|
|
412
|
-
ORDER BY
|
|
413
|
-
WHERE m.content LIKE ?${
|
|
414
|
-
ORDER BY m.created_at DESC LIMIT ?`).all(...
|
|
415
|
-
m.created_at, m.updated_at, m.source, m.tags, m.expires_at`;var
|
|
416
|
-
Use memory_timeline(id) for context, memory_get([ids]) for full content.`),
|
|
417
|
-
`)}case"
|
|
418
|
-
${J.full_content}`),J.after.length){W.push(""),W.push("After:");for(let A of J.after)W.push(` \xB7 [${A.id}] ${A.snippet} (${A.age})`)}return W.join(`
|
|
419
|
-
`)}case"memory_get":{let{ids:G}=w,E=CF(G);if(E.length===0)return"No memories found.";return E.map((J)=>{return`${J.title?`[${J.id}] [${J.type}] "${J.title}" (${J.importance})`:`[${J.id}] [${J.type}] (${J.importance})`}
|
|
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 H9($,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 rF($,w){return H9($,w)}function F9($,w,E=10,X,G){let J=pF(),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(oC(B,D.size,M));return z}let W=[],O=mA(J,"memories_fts",H9(A,"AND"),w,X,E,G);if(W.push(...N(O,"porter")),W.length>=E)return J6(W.slice(0,E));let Y=mA(J,"memories_fts",H9(A,"OR"),w,X,E,G);if(W.push(...N(Y,"porter")),W.length>=E)return J6(W.slice(0,E));let H=mA(J,"memories_fts_trigram",rF(A,"AND"),w,X,E,G);if(W.push(...N(H,"trigram")),W.length>=E)return J6(W.slice(0,E));let L=mA(J,"memories_fts_trigram",rF(A,"OR"),w,X,E,G);if(W.push(...N(L,"trigram")),W.length>=E)return J6(W.slice(0,E));if(W.length===0){let{clause:j,params:M}=oF(w,X,G),z=[`%${A.toLowerCase()}%`,...M,E],B=J.query(`SELECT ${L9} FROM memories m
|
|
443
|
+
WHERE m.content LIKE ?${j}
|
|
444
|
+
ORDER BY m.created_at DESC LIMIT ?`).all(...z);W.push(...N(B,"fallback"))}let F=J6(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 J6($){return $.map((w,E)=>({...w,rank:E+1}))}function tF($){if($.length===0)return[];let w=pF(),E=$.map(()=>"?").join(",");return w.query(`SELECT ${L9} 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 L9=`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 iF=R(()=>{y$()});import{createHash as tC}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 A6($,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=F9(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
|
+
Use memory_timeline(id) for context, memory_get([ids]) for full content.`),O.join(`
|
|
447
|
+
`)}case"memory_get":{let{ids:X}=w,G=tF(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})`}
|
|
420
448
|
${J.content}`}).join(`
|
|
421
449
|
|
|
422
450
|
---
|
|
423
451
|
|
|
424
|
-
`)}case"memory_store":{let{content:
|
|
425
|
-
`)}case"task_get":{let{ids:
|
|
452
|
+
`)}case"memory_store":{let{content:X,title:G,type:J,scope:A,tags:D,importance:N,project:W}=w,O=Qw(z$(E),W),Y=i(),H=new Date;await E.insert(H1).values({id:Y,title:G,type:J??"fact",content:X,scope:A,tags:D,importance:N??"normal",project_id:O?.id,created_at:H,updated_at:H});let L=G?` "${G}"`:"",F=O?` (${O.name})`:"";return`Stored: ${Y}${L} [${J??"fact"}]${F}`}case"task_list":{let{project:X,status:G,limit:J}=w,A=Qw(z$(E),X),D=[];if(G)D.push(V(r.status,G));if(A)D.push(V(r.project_id,A.id));let N=await E.query.tasks.findMany({where:D.length>0?S0(...D):void 0,limit:J??20,orderBy:(O,{desc:Y})=>[Y(O.updated_at)]}),W=G?N:N.filter((O)=>!["done","cancelled"].includes(O.status));if(W.length===0)return"No active tasks.";return W.map((O)=>`[${O.id}] ${O.status.padEnd(18)} ${O.priority.padEnd(8)} ${O.title}`).join(`
|
|
453
|
+
`)}case"task_get":{let{ids:X}=w;return(await Promise.all(X.map((J)=>E.query.tasks.findFirst({where:V(r.id,J)})))).filter(Boolean).map((J)=>`[${J?.id}] ${J?.status} \u2014 ${J?.title}
|
|
426
454
|
${J?.body??""}`).join(`
|
|
427
455
|
|
|
428
|
-
`)}case"task_create":{let{title:
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
456
|
+
`)}case"task_create":{let{title:X,body:G,project:J,priority:A,author:D}=w,N=Qw(z$(E),J),W=i(),O=new Date;await E.insert(r).values({id:W,title:X,body:G,project_id:N?.id,priority:A??"normal",author:D??"agent",status:"todo",created_at:O,updated_at:O});let Y=N?` (${N.name})`:"";return`Created: ${W} \u2014 ${X}${Y}`}case"task_update":{let{id:X,status:G,body:J,priority:A}=w;if(G==="doing"){let N=z$(E).query(`SELECT t.id, t.title FROM task_links tl JOIN tasks t ON t.id = tl.from_task_id
|
|
457
|
+
WHERE tl.to_task_id = ? AND tl.link_type = 'blocks' AND t.status NOT IN ('done', 'cancelled')
|
|
458
|
+
UNION
|
|
459
|
+
SELECT t.id, t.title FROM task_links tl JOIN tasks t ON t.id = tl.to_task_id
|
|
460
|
+
WHERE tl.from_task_id = ? AND tl.link_type = 'blocked_by' AND t.status NOT IN ('done', 'cancelled')`).all(X,X);if(N.length>0)return`Cannot start: blocked by ${N.map((O)=>`[${O.id.slice(-6)}] ${O.title}`).join(", ")}`}if(await E.update(r).set({...G?{status:G}:{},...J!==void 0?{body:J}:{},...A?{priority:A}:{},updated_at:new Date}).where(V(r.id,X)),G&&["done","cancelled"].includes(G)){let D=z$(E),N=D.query(`SELECT DISTINCT dependent_id AS id FROM (
|
|
461
|
+
SELECT tl.to_task_id AS dependent_id FROM task_links tl WHERE tl.from_task_id = ? AND tl.link_type = 'blocks'
|
|
462
|
+
UNION SELECT tl.from_task_id AS dependent_id FROM task_links tl WHERE tl.to_task_id = ? AND tl.link_type = 'blocked_by'
|
|
463
|
+
)`).all(X,X);for(let O of N)if(!D.query(`SELECT 1 FROM task_links tl JOIN tasks t ON t.id = tl.from_task_id
|
|
464
|
+
WHERE tl.to_task_id = ? AND tl.link_type = 'blocks' AND t.status NOT IN ('done','cancelled')
|
|
465
|
+
LIMIT 1`).get(O.id)){if(D.query("SELECT status FROM tasks WHERE id = ?").get(O.id)?.status==="blocked")D.query("UPDATE tasks SET status = 'todo', updated_at = unixepoch() WHERE id = ?").run(O.id)}let W=D.query("SELECT tl.to_task_id FROM task_links tl WHERE tl.from_task_id = ? AND tl.link_type = 'subtask_of' LIMIT 1").get(X);if(W){let O=D.query(`SELECT COUNT(*) as total, SUM(CASE WHEN t.status IN ('done','cancelled') THEN 1 ELSE 0 END) as done
|
|
466
|
+
FROM task_links tl JOIN tasks t ON t.id = tl.from_task_id
|
|
467
|
+
WHERE tl.to_task_id = ? AND tl.link_type = 'subtask_of'`).get(W.to_task_id);if(!O||O.total===0)return`Updated: ${X}`;let Y=Math.round(O.done/O.total*100);if(D.query("UPDATE tasks SET progress = ?, updated_at = unixepoch() WHERE id = ?").run(Y,W.to_task_id),O.done===O.total){let H=D.query("SELECT status FROM tasks WHERE id = ?").get(W.to_task_id);if(H&&!["done","cancelled","review"].includes(H.status))D.query("UPDATE tasks SET status = 'review', updated_at = unixepoch() WHERE id = ?").run(W.to_task_id)}}}return`Updated: ${X}`}case"task_submit_review":{let{id:X,summary:G}=w,J=await E.query.tasks.findFirst({where:V(r.id,X)}),A=J?.body?`${J.body}
|
|
468
|
+
|
|
469
|
+
---
|
|
470
|
+
## Review Summary
|
|
471
|
+
${G}`:`## Review Summary
|
|
472
|
+
${G}`;return await E.update(r).set({status:"review",body:A,updated_at:new Date}).where(V(r.id,X)),`Task ${X} in review. Reviewer notified if bridge configured.`}case"task_check_review":{let{id:X}=w,G=await E.query.tasks.findFirst({where:V(r.id,X)});if(!G)return`Task not found: ${X}`;return`Review status: ${{review:"pending",done:"approved",changes_requested:"changes_requested"}[G.status]??G.status}
|
|
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
|
+
`)}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
|
+
## 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)} (${dC(k.created_at)})`)}if(B?.summary)Q.push(`
|
|
477
|
+
## Last Session (${B.agent})`),Q.push(` ${B.summary}`);return Q.push(`
|
|
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=tC("sha256").update(W).digest("hex").slice(0,16);if(D.query(`SELECT data_hash FROM session_events
|
|
434
480
|
WHERE session_id = ? AND type = ?
|
|
435
|
-
ORDER BY created_at DESC LIMIT ?`).all(
|
|
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 = (
|
|
436
482
|
SELECT id FROM session_events WHERE session_id = ?
|
|
437
483
|
ORDER BY priority ASC, created_at ASC LIMIT 1
|
|
438
|
-
)`).run(
|
|
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
|
|
439
485
|
WHERE session_id = ?
|
|
440
|
-
ORDER BY priority ASC, created_at DESC LIMIT 100`).all(
|
|
441
|
-
|
|
442
|
-
${
|
|
443
|
-
`),
|
|
444
|
-
`),
|
|
445
|
-
`
|
|
446
|
-
${G}
|
|
447
|
-
|
|
486
|
+
ORDER BY priority ASC, created_at DESC LIMIT 100`).all(A),Y=iC(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
|
+
|
|
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
|
+
`),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
|
+
`)}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
|
+
${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=F9(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 iC($,w,E){let X=$.map((O)=>` <task id="${O.id.slice(-6)}" status="${O.status}" priority="${O.priority}">${sF(O.title)}</task>`).join(`
|
|
494
|
+
`),G=w.filter((O)=>dF.has(O.type)),J=w.filter((O)=>lF.has(O.type)),A=w.filter((O)=>!dF.has(O.type)&&!lF.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>${sF(j)}</item>`).join("")}</${L}s>`).join(`
|
|
495
|
+
`)}function N(O,Y){let H=[`<tasks>
|
|
496
|
+
${X}
|
|
497
|
+
</tasks>`],L=D(G);if(L)H.push(`<context priority="high">
|
|
448
498
|
${L}
|
|
449
|
-
</context>`);if(
|
|
499
|
+
</context>`);if(O){let F=D(J);if(F)H.push(`<context priority="normal">
|
|
450
500
|
${F}
|
|
451
|
-
</context>`)}if(
|
|
501
|
+
</context>`)}if(Y){let F=D(A,3);if(F)H.push(`<context priority="low">
|
|
452
502
|
${F}
|
|
453
503
|
</context>`)}return`<session>
|
|
454
504
|
${H.join(`
|
|
455
505
|
`)}
|
|
456
|
-
</session>`}let
|
|
506
|
+
</session>`}let W=[[!0,!0],[!0,!1],[!1,!1]];for(let[O,Y]of W){let H=N(O,Y);if(Buffer.byteLength(H)<=E)return H}return`<session>
|
|
457
507
|
<tasks>
|
|
458
|
-
${
|
|
508
|
+
${X}
|
|
459
509
|
</tasks>
|
|
460
|
-
</session>`}function
|
|
461
|
-
m.importance, m.expires_at, m.created_at, m.updated_at`;var
|
|
462
|
-
WHERE f.${
|
|
463
|
-
WHERE m.content LIKE ?${
|
|
464
|
-
ORDER BY m.created_at DESC LIMIT ?`).all(...z)}return $.json({results:N.map(gF)})});zG.openapi(BC,async($)=>{let w=g(),{scope:X,type:G,limit:E}=$.req.valid("query"),J=w.$client,W=[],Y=[];if(X)W.push("scope = ?"),Y.push(X);if(G)W.push("type = ?"),Y.push(G);Y.push(E);let A=W.length?`WHERE ${W.join(" AND ")}`:"",D=J.query(`SELECT ${W7} FROM memories m ${A} ORDER BY m.created_at DESC LIMIT ?`).all(...Y);return $.json({memories:D.map(gF)})});zG.openapi(KC,async($)=>{let w=g(),X=$.req.valid("json"),G=new Date,E=e();await w.insert(h$).values({id:E,title:X.title,type:X.type??"fact",content:X.content,source:X.source,scope:X.scope,tags:X.tags,importance:X.importance,expires_at:X.expires_at?new Date(X.expires_at):void 0,created_at:G,updated_at:G});let J=await w.query.memories.findFirst({where:S(h$.id,E)});return $.json(RC(J),201)});zG.openapi(VC,async($)=>{let w=g(),{id:X}=$.req.valid("param");if(!await w.query.memories.findFirst({where:S(h$.id,X)}))throw new M0("Memory",X);return await w.delete(h$).where(S(h$.id,X)),new Response(null,{status:204})})});function kJ($){return{...$,created_at:$.created_at.toISOString(),updated_at:$.updated_at.toISOString()}}var LX,bJ,TC,IC,jC,PC,qC,SC,ZC;var uF=B(()=>{A1();Z1();l$();c$();u$();g$();LX=new a0,bJ=O.object({id:O.string(),name:O.string(),description:O.string().nullable(),status:O.enum(["active","archived","paused"]),scope:O.string().nullable(),tags:O.array(O.string()).nullable(),obsidian_path:O.string().nullable(),created_at:O.string().datetime(),updated_at:O.string().datetime()}).openapi("Project"),TC=O.object({name:O.string().min(1).max(200),description:O.string().optional(),status:O.enum(["active","archived","paused"]).optional().default("active"),scope:O.string().optional(),tags:O.array(O.string()).optional(),obsidian_path:O.string().optional()}).openapi("CreateProject"),IC=O.object({name:O.string().min(1).max(200).optional(),description:O.string().optional(),status:O.enum(["active","archived","paused"]).optional(),scope:O.string().optional(),tags:O.array(O.string()).optional(),obsidian_path:O.string().optional()}).openapi("UpdateProject"),jC=t({method:"get",path:"/projects",tags:["Projects"],summary:"List projects",request:{query:O.object({status:O.enum(["active","archived","paused"]).optional(),limit:O.coerce.number().int().min(1).max(100).optional().default(50)})},responses:{200:{description:"Projects",content:{"application/json":{schema:O.object({projects:O.array(bJ)})}}}}}),PC=t({method:"get",path:"/projects/{id}",tags:["Projects"],summary:"Get project by ID",request:{params:O.object({id:O.string()})},responses:{200:{description:"Project",content:{"application/json":{schema:bJ}}}}}),qC=t({method:"post",path:"/projects",tags:["Projects"],summary:"Create project",request:{body:{content:{"application/json":{schema:TC}}}},responses:{201:{description:"Created",content:{"application/json":{schema:bJ}}}}}),SC=t({method:"patch",path:"/projects/{id}",tags:["Projects"],summary:"Update project",request:{params:O.object({id:O.string()}),body:{content:{"application/json":{schema:IC}}}},responses:{200:{description:"Updated",content:{"application/json":{schema:bJ}}}}}),ZC=t({method:"delete",path:"/projects/{id}",tags:["Projects"],summary:"Delete project",request:{params:O.object({id:O.string()})},responses:{204:{description:"Deleted"}}});LX.openapi(jC,async($)=>{let w=g(),{status:X,limit:G}=$.req.valid("query"),E=X?[S(Z$.status,X)]:[],J=await w.query.projects.findMany({where:E.length>0?Y$(...E):void 0,limit:G,orderBy:(W,{asc:Y})=>[Y(W.name)]});return $.json({projects:J.map(kJ)})});LX.openapi(PC,async($)=>{let w=g(),{id:X}=$.req.valid("param"),G=await w.query.projects.findFirst({where:S(Z$.id,X)});if(!G)throw new M0("Project",X);return $.json(kJ(G))});LX.openapi(qC,async($)=>{let w=g(),X=$.req.valid("json"),G=new Date,E=e();await w.insert(Z$).values({id:E,name:X.name,description:X.description,status:X.status,scope:X.scope,tags:X.tags,obsidian_path:X.obsidian_path,created_at:G,updated_at:G});let J=await w.query.projects.findFirst({where:S(Z$.id,E)});if(!J)throw Error("Expected project to exist after write");return $.json(kJ(J),201)});LX.openapi(SC,async($)=>{let w=g(),{id:X}=$.req.valid("param"),G=$.req.valid("json");if(!await w.query.projects.findFirst({where:S(Z$.id,X)}))throw new M0("Project",X);await w.update(Z$).set({...G.name!==void 0?{name:G.name}:{},...G.description!==void 0?{description:G.description}:{},...G.status!==void 0?{status:G.status}:{},...G.scope!==void 0?{scope:G.scope}:{},...G.tags!==void 0?{tags:G.tags}:{},...G.obsidian_path!==void 0?{obsidian_path:G.obsidian_path}:{},updated_at:new Date}).where(S(Z$.id,X));let J=await w.query.projects.findFirst({where:S(Z$.id,X)});if(!J)throw Error("Expected updated to exist after write");return $.json(kJ(J))});LX.openapi(ZC,async($)=>{let w=g(),{id:X}=$.req.valid("param");if(!await w.query.projects.findFirst({where:S(Z$.id,X)}))throw new M0("Project",X);return await w.delete(Z$).where(S(Z$.id,X)),new Response(null,{status:204})})});function vJ($){return{...$,last_used_at:$.last_used_at?.toISOString()??null,created_at:$.created_at.toISOString(),updated_at:$.updated_at.toISOString()}}function cC($,w){return $.replace(/\{\{(\w+)\}\}/g,(X,G)=>w[G]??`{{${G}}}`)}function mC($){return{...$,changed_at:$.changed_at.toISOString()}}var Nw,CJ,bC,kC,CC,vC,_C,fC,xC,yC,gC,hC,uC;var cF=B(()=>{A1();Z1();l$();c$();u$();g$();Nw=new a0,CJ=O.object({id:O.string(),name:O.string(),description:O.string().nullable(),template:O.string(),is_skill:O.boolean(),skill_dir:O.string().nullable(),skill_version:O.string().nullable(),tags:O.array(O.string()).nullable(),version:O.number(),pinned:O.boolean(),last_used_at:O.string().datetime().nullable(),created_at:O.string().datetime(),updated_at:O.string().datetime()}).openapi("Prompt"),bC=O.object({name:O.string().min(1).max(200),description:O.string().optional(),template:O.string().min(1),is_skill:O.boolean().optional().default(!1),skill_dir:O.string().optional(),skill_version:O.string().optional(),tags:O.array(O.string()).optional(),pinned:O.boolean().optional().default(!1)}).openapi("CreatePrompt"),kC=O.object({name:O.string().min(1).max(200).optional(),description:O.string().optional(),template:O.string().min(1).optional(),is_skill:O.boolean().optional(),skill_dir:O.string().optional(),skill_version:O.string().optional(),tags:O.array(O.string()).optional(),pinned:O.boolean().optional()}).openapi("UpdatePrompt"),CC=O.object({vars:O.record(O.string()).optional().default({})}).openapi("RenderPrompt"),vC=t({method:"get",path:"/prompts",tags:["Prompts"],summary:"List prompts",request:{query:O.object({is_skill:O.coerce.boolean().optional(),limit:O.coerce.number().int().min(1).max(100).optional().default(50)})},responses:{200:{description:"Prompts",content:{"application/json":{schema:O.object({prompts:O.array(CJ)})}}}}}),_C=t({method:"get",path:"/prompts/{id}",tags:["Prompts"],summary:"Get prompt by ID",request:{params:O.object({id:O.string()})},responses:{200:{description:"Prompt",content:{"application/json":{schema:CJ}}}}}),fC=t({method:"post",path:"/prompts",tags:["Prompts"],summary:"Create prompt",request:{body:{content:{"application/json":{schema:bC}}}},responses:{201:{description:"Created",content:{"application/json":{schema:CJ}}}}}),xC=t({method:"patch",path:"/prompts/{id}",tags:["Prompts"],summary:"Update prompt (bumps version)",request:{params:O.object({id:O.string()}),body:{content:{"application/json":{schema:kC}}}},responses:{200:{description:"Updated",content:{"application/json":{schema:CJ}}}}}),yC=t({method:"delete",path:"/prompts/{id}",tags:["Prompts"],summary:"Delete prompt",request:{params:O.object({id:O.string()})},responses:{204:{description:"Deleted"}}}),gC=t({method:"post",path:"/prompts/{id}/render",tags:["Prompts"],summary:"Render prompt with variable interpolation",request:{params:O.object({id:O.string()}),body:{content:{"application/json":{schema:CC}}}},responses:{200:{description:"Rendered",content:{"application/json":{schema:O.object({rendered:O.string(),prompt_id:O.string(),version:O.number()}).openapi("RenderedPrompt")}}}}}),hC=O.object({id:O.string(),prompt_id:O.string(),version:O.number(),name:O.string(),description:O.string().nullable(),template:O.string(),tags:O.array(O.string()).nullable(),changed_by:O.string(),changed_at:O.string().datetime()}).openapi("PromptHistoryEntry"),uC=t({method:"get",path:"/prompts/{id}/history",tags:["Prompts"],summary:"List prompt version history (newest first)",request:{params:O.object({id:O.string()}),query:O.object({limit:O.coerce.number().int().min(1).max(100).optional().default(20)})},responses:{200:{description:"History",content:{"application/json":{schema:O.object({history:O.array(hC)})}}}}});Nw.openapi(vC,async($)=>{let w=g(),{is_skill:X,limit:G}=$.req.valid("query"),E=await w.query.prompts.findMany({where:X!==void 0?S(w$.is_skill,X):void 0,limit:G,orderBy:(J,{asc:W})=>[W(J.name)]});return $.json({prompts:E.map(vJ)})});Nw.openapi(_C,async($)=>{let w=g(),{id:X}=$.req.valid("param"),G=await w.query.prompts.findFirst({where:S(w$.id,X)});if(!G)throw new M0("Prompt",X);return $.json(vJ(G))});Nw.openapi(fC,async($)=>{let w=g(),X=$.req.valid("json"),G=new Date,E=e();await w.insert(w$).values({id:E,name:X.name,description:X.description,template:X.template,is_skill:X.is_skill,skill_dir:X.skill_dir,skill_version:X.skill_version,tags:X.tags,pinned:X.pinned,created_at:G,updated_at:G});let J=await w.query.prompts.findFirst({where:S(w$.id,E)});if(!J)throw Error("Expected prompt to exist after write");return $.json(vJ(J),201)});Nw.openapi(xC,async($)=>{let w=g(),{id:X}=$.req.valid("param"),G=$.req.valid("json"),E=await w.query.prompts.findFirst({where:S(w$.id,X)});if(!E)throw new M0("Prompt",X);await w.insert(Q6).values({id:e(),prompt_id:E.id,version:E.version,name:E.name,description:E.description,template:E.template,tags:E.tags,changed_by:"human",changed_at:new Date}),await w.update(w$).set({...G.name!==void 0?{name:G.name}:{},...G.description!==void 0?{description:G.description}:{},...G.template!==void 0?{template:G.template}:{},...G.is_skill!==void 0?{is_skill:G.is_skill}:{},...G.skill_dir!==void 0?{skill_dir:G.skill_dir}:{},...G.skill_version!==void 0?{skill_version:G.skill_version}:{},...G.tags!==void 0?{tags:G.tags}:{},...G.pinned!==void 0?{pinned:G.pinned}:{},version:E.version+1,updated_at:new Date}).where(S(w$.id,X));let J=await w.query.prompts.findFirst({where:S(w$.id,X)});if(!J)throw Error("Expected updated to exist after write");return $.json(vJ(J))});Nw.openapi(yC,async($)=>{let w=g(),{id:X}=$.req.valid("param");if(!await w.query.prompts.findFirst({where:S(w$.id,X)}))throw new M0("Prompt",X);return await w.delete(w$).where(S(w$.id,X)),new Response(null,{status:204})});Nw.openapi(gC,async($)=>{let w=g(),{id:X}=$.req.valid("param"),{vars:G}=$.req.valid("json"),E=await w.query.prompts.findFirst({where:S(w$.id,X)});if(!E)throw new M0("Prompt",X);return await w.update(w$).set({last_used_at:new Date}).where(S(w$.id,X)),$.json({rendered:cC(E.template,G??{}),prompt_id:E.id,version:E.version})});Nw.openapi(uC,async($)=>{let w=g(),{id:X}=$.req.valid("param"),{limit:G}=$.req.valid("query");if(!await w.query.prompts.findFirst({where:S(w$.id,X)}))throw new M0("Prompt",X);let J=await w.query.prompt_history.findMany({where:S(Q6.prompt_id,X),limit:G,orderBy:[p0(Q6.version)]});return $.json({history:J.map(mC)})})});function nF($){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 _J,mF,nC,pC,rC;var pF=B(()=>{A1();Z1();c$();u$();g$();_J=new a0,mF=O.object({id:O.string(),agent:O.string(),agent_version:O.string().nullable(),project_id:O.string().nullable(),job_run_id:O.string().nullable(),summary:O.string().nullable(),tokens_used:O.number().nullable(),created_at:O.string().datetime()}).openapi("Session"),nC=mF.extend({events:O.array(O.object({id:O.string(),type:O.string(),priority:O.number(),data:O.string(),created_at:O.string().datetime()})),snapshot:O.string().nullable()}).openapi("SessionDetail"),pC=t({method:"get",path:"/sessions",tags:["Sessions"],summary:"List recent sessions",request:{query:O.object({agent:O.string().optional(),job_run_id:O.string().optional(),limit:O.coerce.number().int().min(1).max(100).optional().default(20)})},responses:{200:{description:"Sessions list",content:{"application/json":{schema:O.object({sessions:O.array(mF)})}}}}}),rC=t({method:"get",path:"/sessions/{id}",tags:["Sessions"],summary:"Get session detail with events",request:{params:O.object({id:O.string()})},responses:{200:{description:"Session detail",content:{"application/json":{schema:nC}}},404:{description:"Not found"}}});_J.openapi(pC,async($)=>{let w=g(),{agent:X,job_run_id:G,limit:E}=$.req.valid("query"),J=[];if(X)J.push(S(j1.agent,X));if(G)J.push(S(j1.job_run_id,G));let W=await w.query.sessions.findMany({limit:E,orderBy:[p0(j1.created_at)],where:J.length>0?Y$(...J):void 0});return $.json({sessions:W.map(nF)})});_J.openapi(rC,async($)=>{let w=g(),{id:X}=$.req.valid("param"),G=await w.query.sessions.findFirst({where:S(j1.id,X)});if(!G)throw new M0("Session",X);let E=w.$client,J=E.query(`SELECT id, type, priority, data, created_at
|
|
510
|
+
</session>`}function sF($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function dC($){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,PX,dF,lF;var rA=R(()=>{C$();X1();y$();d$();nw();i$();WG();iF();Bw=U.string().optional().describe("Project name (e.g. 'orc'). Defaults to activeProject from config if not set."),PX=[{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()})}];dF=new Set(["file","task","rule"]),lF=new Set(["decision","git","env","error","plan"])});var j9,lC;var aF=R(()=>{N1();x1();rA();j9=new p0,lC=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")}}}}});j9.openapi(lC,async($)=>{let{name:w,args:E}=$.req.valid("json"),X=PX.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 A6(w,G.data);return $.json({result:J})})});function eF($){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 E_($){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 qX,pA,R9,sC,aC,eC,$_,w_,M9=`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 $j=R(()=>{N1();x1();X1();y$();d$();i$();qX=new p0,pA=U.enum(["fact","decision","event","rule","discovery"]),R9=U.object({id:U.string(),title:U.string().nullable(),type:pA,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"),sC=U.object({content:U.string().min(1),title:U.string().optional(),type:pA.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"),aC=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:pA.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(R9)})}}}}}),eC=m({method:"get",path:"/memories",tags:["Memory"],summary:"List memories",request:{query:U.object({scope:U.string().optional(),type:pA.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(R9)})}}}}}),$_=m({method:"post",path:"/memories",tags:["Memory"],summary:"Store a memory",request:{body:{content:{"application/json":{schema:sC}}}},responses:{201:{description:"Created",content:{"application/json":{schema:R9}}}}}),w_=m({method:"delete",path:"/memories/{id}",tags:["Memory"],summary:"Delete memory",request:{params:U.object({id:U.string()})},responses:{204:{description:"Deleted"}}});qX.openapi(aC,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 ${M9} 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 ${M9} FROM memories m
|
|
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
|
|
465
515
|
FROM session_events WHERE session_id = ?
|
|
466
|
-
ORDER BY created_at ASC`).all(X),W=E.query("SELECT xml FROM session_snapshots WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(X);return $.json({...nF(G),snapshot:W?.xml??null,events:J.map((Y)=>({id:Y.id,type:Y.type,priority:Y.priority,data:Y.data,created_at:new Date(Y.created_at*1000).toISOString()}))})})});function iF($){return{...$,created_at:$.created_at.toISOString()}}var t6,rF,iC,oC,tC,dC;var oF=B(()=>{A1();Z1();l$();IJ();c$();u$();g$();t6=new a0,rF=O.object({id:O.string(),from_task_id:O.string(),to_task_id:O.string(),link_type:$7,created_at:O.string().datetime()}).openapi("TaskLink"),iC=O.object({to_task_id:O.string(),link_type:$7}).openapi("CreateTaskLink"),oC=t({method:"get",path:"/tasks/{id}/links",tags:["Tasks"],summary:"List links for a task (both directions)",request:{params:O.object({id:O.string()})},responses:{200:{description:"Links",content:{"application/json":{schema:O.object({links:O.array(rF)})}}}}}),tC=t({method:"post",path:"/tasks/{id}/links",tags:["Tasks"],summary:"Link this task to another task",request:{params:O.object({id:O.string()}),body:{content:{"application/json":{schema:iC}}}},responses:{201:{description:"Created",content:{"application/json":{schema:rF}}}}}),dC=t({method:"delete",path:"/tasks/{id}/links/{linkId}",tags:["Tasks"],summary:"Remove a task link",request:{params:O.object({id:O.string(),linkId:O.string()})},responses:{204:{description:"Deleted"}}});t6.openapi(oC,async($)=>{let w=g(),{id:X}=$.req.valid("param");if(!await w.query.tasks.findFirst({where:S(r.id,X)}))throw new M0("Task",X);let E=await w.query.task_links.findMany({where:Y4(S(I1.from_task_id,X),S(I1.to_task_id,X))});return $.json({links:E.map(iF)})});t6.openapi(tC,async($)=>{let w=g(),{id:X}=$.req.valid("param"),{to_task_id:G,link_type:E}=$.req.valid("json"),[J,W]=await Promise.all([w.query.tasks.findFirst({where:S(r.id,X)}),w.query.tasks.findFirst({where:S(r.id,G)})]);if(!J)throw new M0("Task",X);if(!W)throw new M0("Task",G);if(X===G)throw new Ow("Cannot link a task to itself");if(await w.query.task_links.findFirst({where:Y$(S(I1.from_task_id,X),S(I1.to_task_id,G))}))throw new Ow("Link already exists between these tasks");let A=e();await w.insert(I1).values({id:A,from_task_id:X,to_task_id:G,link_type:E,created_at:new Date});let D=await w.query.task_links.findFirst({where:S(I1.id,A)});if(!D)throw Error("Expected link to exist after write");return $.json(iF(D),201)});t6.openapi(dC,async($)=>{let w=g(),{id:X,linkId:G}=$.req.valid("param"),E=await w.query.task_links.findFirst({where:S(I1.id,G)});if(!E||E.from_task_id!==X&&E.to_task_id!==X)throw new M0("TaskLink",G);return await w.delete(I1).where(S(I1.id,G)),new Response(null,{status:204})})});function l6($){return{...$,due_at:$.due_at?.toISOString()??null,created_at:$.created_at.toISOString(),updated_at:$.updated_at.toISOString()}}function dF($){return{...$,created_at:$.created_at.toISOString()}}var b1,d6,tF,lC,sC,aC,eC,$v,wv,Xv,Gv,Ev,Jv,Wv;var lF=B(()=>{A1();Z1();l$();IJ();c$();u$();g$();b1=new a0,d6=O.object({id:O.string(),project_id:O.string().nullable(),title:O.string(),body:O.string().nullable(),status:RJ,priority:TJ,progress:O.number().int(),due_at:O.string().datetime().nullable(),tags:O.array(O.string()).nullable(),author:O.string(),claimed_by:O.string().nullable(),claim_expires_at:O.string().datetime().nullable(),created_at:O.string().datetime(),updated_at:O.string().datetime()}).openapi("Task"),tF=O.object({id:O.string(),task_id:O.string(),content:O.string(),author:O.string(),created_at:O.string().datetime()}).openapi("TaskNote"),lC=O.object({title:O.string().min(1).max(500),body:O.string().optional(),project_id:O.string().optional(),status:O.enum(["todo","doing","blocked"]).optional().default("todo"),priority:TJ.optional().default("normal"),due_at:O.string().datetime().optional(),tags:O.array(O.string()).optional(),author:O.string().optional().default("human")}).openapi("CreateTask"),sC=O.object({title:O.string().min(1).max(500).optional(),body:O.string().optional(),status:RJ.optional(),priority:TJ.optional(),due_at:O.string().datetime().optional(),tags:O.array(O.string()).optional()}).openapi("UpdateTask"),aC=t({method:"get",path:"/tasks",tags:["Tasks"],summary:"List tasks",request:{query:O.object({project_id:O.string().optional(),status:RJ.optional(),limit:O.coerce.number().int().min(1).max(100).optional().default(50)})},responses:{200:{description:"Task list",content:{"application/json":{schema:O.object({tasks:O.array(d6),total:O.number()})}}}}}),eC=t({method:"get",path:"/tasks/{id}",tags:["Tasks"],summary:"Get task by ID",request:{params:O.object({id:O.string()})},responses:{200:{description:"Task",content:{"application/json":{schema:d6}}}}}),$v=t({method:"post",path:"/tasks",tags:["Tasks"],summary:"Create task",request:{body:{content:{"application/json":{schema:lC}}}},responses:{201:{description:"Created",content:{"application/json":{schema:d6}}}}}),wv=t({method:"patch",path:"/tasks/{id}",tags:["Tasks"],summary:"Update task",request:{params:O.object({id:O.string()}),body:{content:{"application/json":{schema:sC}}}},responses:{200:{description:"Updated",content:{"application/json":{schema:d6}}}}}),Xv=t({method:"delete",path:"/tasks/{id}",tags:["Tasks"],summary:"Delete task",request:{params:O.object({id:O.string()})},responses:{204:{description:"Deleted"}}}),Gv=t({method:"post",path:"/tasks/{id}/review",tags:["Tasks"],summary:"Submit task for human review (HITL checkpoint)",request:{params:O.object({id:O.string()}),body:{content:{"application/json":{schema:O.object({summary:O.string().min(1)}).openapi("SubmitReview")}}}},responses:{200:{description:"Submitted",content:{"application/json":{schema:d6}}}}}),Ev=t({method:"get",path:"/tasks/{id}/review",tags:["Tasks"],summary:"Poll HITL review result",request:{params:O.object({id:O.string()})},responses:{200:{description:"Review status",content:{"application/json":{schema:O.object({status:O.enum(["review","approved","changes_requested","pending"]),note:O.string().nullable()}).openapi("ReviewStatus")}}}}}),Jv=t({method:"get",path:"/tasks/{id}/notes",tags:["Tasks"],summary:"List task notes",request:{params:O.object({id:O.string()})},responses:{200:{description:"Notes",content:{"application/json":{schema:O.object({notes:O.array(tF)})}}}}}),Wv=t({method:"post",path:"/tasks/{id}/notes",tags:["Tasks"],summary:"Add a note to a task",request:{params:O.object({id:O.string()}),body:{content:{"application/json":{schema:O.object({content:O.string().min(1),author:O.string().optional().default("human")}).openapi("AddNote")}}}},responses:{201:{description:"Note added",content:{"application/json":{schema:tF}}}}});b1.openapi(aC,async($)=>{let w=g(),{project_id:X,status:G,limit:E}=$.req.valid("query"),J=[];if(X)J.push(S(r.project_id,X));if(G)J.push(S(r.status,G));let W=await w.query.tasks.findMany({where:J.length>0?Y$(...J):void 0,limit:E,orderBy:[p0(r.updated_at)]});return $.json({tasks:W.map(l6),total:W.length})});b1.openapi(eC,async($)=>{let w=g(),{id:X}=$.req.valid("param"),G=await w.query.tasks.findFirst({where:S(r.id,X)});if(!G)throw new M0("Task",X);return $.json(l6(G))});b1.openapi($v,async($)=>{let w=g(),X=$.req.valid("json"),G=new Date,E=e();await w.insert(r).values({id:E,title:X.title,body:X.body,project_id:X.project_id,status:X.status,priority:X.priority,...X.due_at?{due_at:new Date(X.due_at)}:{},tags:X.tags,author:X.author,created_at:G,updated_at:G});let J=await w.query.tasks.findFirst({where:S(r.id,E)});if(!J)throw Error("Expected task to exist after write");return $.json(l6(J),201)});b1.openapi(wv,async($)=>{let w=g(),{id:X}=$.req.valid("param"),G=$.req.valid("json");if(!await w.query.tasks.findFirst({where:S(r.id,X)}))throw new M0("Task",X);await w.update(r).set({...G.title!==void 0?{title:G.title}:{},...G.body!==void 0?{body:G.body}:{},...G.status!==void 0?{status:G.status}:{},...G.priority!==void 0?{priority:G.priority}:{},...G.due_at!==void 0?{due_at:new Date(G.due_at)}:{},...G.tags!==void 0?{tags:G.tags}:{},updated_at:new Date}).where(S(r.id,X));let J=await w.query.tasks.findFirst({where:S(r.id,X)});if(!J)throw Error("Expected updated to exist after write");return $.json(l6(J))});b1.openapi(Xv,async($)=>{let w=g(),{id:X}=$.req.valid("param");if(!await w.query.tasks.findFirst({where:S(r.id,X)}))throw new M0("Task",X);return await w.delete(r).where(S(r.id,X)),new Response(null,{status:204})});b1.openapi(Gv,async($)=>{let w=g(),{id:X}=$.req.valid("param"),{summary:G}=$.req.valid("json"),E=await w.query.tasks.findFirst({where:S(r.id,X)});if(!E)throw new M0("Task",X);if(!["doing","blocked"].includes(E.status))throw new Ow(`Task must be in doing/blocked to submit for review (current: ${E.status})`);let J=new Date;await w.update(r).set({status:"review",body:G,updated_at:J}).where(S(r.id,X)),await w.insert(e$).values({id:e(),task_id:X,content:`[review submitted] ${G}`,author:"agent",created_at:J});let W=await w.query.tasks.findFirst({where:S(r.id,X)});if(!W)throw Error("Expected updated to exist after write");return $.json(l6(W))});b1.openapi(Ev,async($)=>{let w=g(),{id:X}=$.req.valid("param"),G=await w.query.tasks.findFirst({where:S(r.id,X)});if(!G)throw new M0("Task",X);let E=await w.query.task_notes.findFirst({where:Y$(S(e$.task_id,X),S(e$.author,"human")),orderBy:[p0(e$.created_at)]}),W={review:"review",done:"approved",changes_requested:"changes_requested"}[G.status]??"pending";return $.json({status:W,note:E?.content??null})});b1.openapi(Jv,async($)=>{let w=g(),{id:X}=$.req.valid("param");if(!await w.query.tasks.findFirst({where:S(r.id,X)}))throw new M0("Task",X);let E=await w.query.task_notes.findMany({where:S(e$.task_id,X),orderBy:[p0(e$.created_at)]});return $.json({notes:E.map(dF)})});b1.openapi(Wv,async($)=>{let w=g(),{id:X}=$.req.valid("param"),{content:G,author:E}=$.req.valid("json");if(!await w.query.tasks.findFirst({where:S(r.id,X)}))throw new M0("Task",X);let W=e(),Y=new Date;await w.insert(e$).values({id:W,task_id:X,content:G,author:E,created_at:Y});let A=await w.query.task_notes.findFirst({where:S(e$.id,W)});if(!A)throw Error("Expected note to exist after write");return $.json(dF(A),201)})});function sF(){let $=Q0(),w=new a0;return w.use("*",RF($.api.secret)),w.onError((X,G)=>{let E=X instanceof LG?X:null;if(E)return G.json({error:E.message,code:E.code},E.statusCode);return Yv.error("Unhandled error",X),G.json({error:"Internal server error",code:"INTERNAL_ERROR"},500)}),w.route("/",sW),w.route("/",J7),w.route("/",LX),w.route("/",Nw),w.route("/",b1),w.route("/",t6),w.route("/",zG),w.route("/",_J),w.route("/",_w),w.route("/",VJ),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",E3({url:"/openapi.json"})),w}var Yv;var aF=B(()=>{J3();A1();d$();Z1();f$();TF();IF();jF();qF();yF();hF();uF();cF();pF();oF();lF();Yv=P0("api")});var D7={};e1(D7,{app:()=>eF});var A7,fw,eF;var U7=B(()=>{d$();f$();aF();A7=P0("api"),fw=Q0(),eF=sF();Bun.serve({port:fw.api.port,hostname:fw.api.host,fetch:eF.fetch});A7.info(`API server running on http://${fw.api.host}:${fw.api.port}`);A7.info(`OpenAPI spec: http://${fw.api.host}:${fw.api.port}/openapi.json`);A7.info(`Swagger UI: http://${fw.api.host}:${fw.api.port}/docs`)});function P($,w,X){function G(Y,A){var D;Object.defineProperty(Y,"_zod",{value:Y._zod??{},enumerable:!1}),(D=Y._zod).traits??(D.traits=new Set),Y._zod.traits.add($),w(Y,A);for(let U in W.prototype)if(!(U in Y))Object.defineProperty(Y,U,{value:W.prototype[U].bind(Y)});Y._zod.constr=W,Y._zod.def=A}let E=X?.Parent??Object;class J extends E{}Object.defineProperty(J,"name",{value:$});function W(Y){var A;let D=X?.Parent?new J:this;G(D,Y),(A=D._zod).deferred??(A.deferred=[]);for(let U of D._zod.deferred)U();return D}return Object.defineProperty(W,"init",{value:G}),Object.defineProperty(W,Symbol.hasInstance,{value:(Y)=>{if(X?.Parent&&Y instanceof X.Parent)return!0;return Y?._zod?.traits?.has($)}}),Object.defineProperty(W,"name",{value:$}),W}function D1($){if($)Object.assign(gJ,$);return gJ}var xX0,yX0,yw,gJ;var BG=B(()=>{xX0=Object.freeze({status:"aborted"});yX0=Symbol("zod_brand");yw=class yw extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};gJ={}});var z0={};e1(z0,{unwrapMessage:()=>s6,stringifyPrimitive:()=>cJ,required:()=>_v,randomString:()=>jv,propertyKeyTypes:()=>B7,promiseAllObject:()=>Iv,primitiveTypes:()=>UM,prefixIssues:()=>d1,pick:()=>Zv,partial:()=>vv,optionalKeys:()=>K7,omit:()=>bv,numKeys:()=>Pv,nullish:()=>e6,normalizeParams:()=>o,merge:()=>Cv,jsonStringifyReplacer:()=>F7,joinValues:()=>hJ,issue:()=>R7,isPlainObject:()=>VG,isObject:()=>KG,getSizableOrigin:()=>NM,getParsedType:()=>qv,getLengthableOrigin:()=>wE,getEnumValues:()=>L7,getElementAtPath:()=>Tv,floatSafeRemainder:()=>M7,finalizeIssue:()=>k1,extend:()=>kv,escapeRegex:()=>gw,esc:()=>FX,defineLazy:()=>q0,createTransparentProxy:()=>Sv,clone:()=>t1,cleanRegex:()=>$E,cleanEnum:()=>fv,captureStackTrace:()=>uJ,cached:()=>a6,assignProp:()=>z7,assertNotEqual:()=>Bv,assertNever:()=>Vv,assertIs:()=>Kv,assertEqual:()=>Qv,assert:()=>Rv,allowsEval:()=>Q7,aborted:()=>MX,NUMBER_FORMAT_RANGES:()=>V7,Class:()=>HM,BIGINT_FORMAT_RANGES:()=>OM});function Qv($){return $}function Bv($){return $}function Kv($){}function Vv($){throw Error()}function Rv($){}function L7($){let w=Object.values($).filter((G)=>typeof G==="number");return Object.entries($).filter(([G,E])=>w.indexOf(+G)===-1).map(([G,E])=>E)}function hJ($,w="|"){return $.map((X)=>cJ(X)).join(w)}function F7($,w){if(typeof w==="bigint")return w.toString();return w}function a6($){return{get value(){{let X=$();return Object.defineProperty(this,"value",{value:X}),X}throw Error("cached value already set")}}}function e6($){return $===null||$===void 0}function $E($){let w=$.startsWith("^")?1:0,X=$.endsWith("$")?$.length-1:$.length;return $.slice(w,X)}function M7($,w){let X=($.toString().split(".")[1]||"").length,G=(w.toString().split(".")[1]||"").length,E=X>G?X:G,J=Number.parseInt($.toFixed(E).replace(".","")),W=Number.parseInt(w.toFixed(E).replace(".",""));return J%W/10**E}function q0($,w,X){Object.defineProperty($,w,{get(){{let E=X();return $[w]=E,E}throw Error("cached value already set")},set(E){Object.defineProperty($,w,{value:E})},configurable:!0})}function z7($,w,X){Object.defineProperty($,w,{value:X,writable:!0,enumerable:!0,configurable:!0})}function Tv($,w){if(!w)return $;return w.reduce((X,G)=>X?.[G],$)}function Iv($){let w=Object.keys($),X=w.map((G)=>$[G]);return Promise.all(X).then((G)=>{let E={};for(let J=0;J<w.length;J++)E[w[J]]=G[J];return E})}function jv($=10){let X="";for(let G=0;G<$;G++)X+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return X}function FX($){return JSON.stringify($)}function KG($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function VG($){if(KG($)===!1)return!1;let w=$.constructor;if(w===void 0)return!0;let X=w.prototype;if(KG(X)===!1)return!1;if(Object.prototype.hasOwnProperty.call(X,"isPrototypeOf")===!1)return!1;return!0}function Pv($){let w=0;for(let X in $)if(Object.prototype.hasOwnProperty.call($,X))w++;return w}function gw($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function t1($,w,X){let G=new $._zod.constr(w??$._zod.def);if(!w||X?.parent)G._zod.parent=$;return G}function o($){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 Sv($){let w;return new Proxy({},{get(X,G,E){return w??(w=$()),Reflect.get(w,G,E)},set(X,G,E,J){return w??(w=$()),Reflect.set(w,G,E,J)},has(X,G){return w??(w=$()),Reflect.has(w,G)},deleteProperty(X,G){return w??(w=$()),Reflect.deleteProperty(w,G)},ownKeys(X){return w??(w=$()),Reflect.ownKeys(w)},getOwnPropertyDescriptor(X,G){return w??(w=$()),Reflect.getOwnPropertyDescriptor(w,G)},defineProperty(X,G,E){return w??(w=$()),Reflect.defineProperty(w,G,E)}})}function cJ($){if(typeof $==="bigint")return $.toString()+"n";if(typeof $==="string")return`"${$}"`;return`${$}`}function K7($){return Object.keys($).filter((w)=>{return $[w]._zod.optin==="optional"&&$[w]._zod.optout==="optional"})}function Zv($,w){let X={},G=$._zod.def;for(let E in w){if(!(E in G.shape))throw Error(`Unrecognized key: "${E}"`);if(!w[E])continue;X[E]=G.shape[E]}return t1($,{...$._zod.def,shape:X,checks:[]})}function bv($,w){let X={...$._zod.def.shape},G=$._zod.def;for(let E in w){if(!(E in G.shape))throw Error(`Unrecognized key: "${E}"`);if(!w[E])continue;delete X[E]}return t1($,{...$._zod.def,shape:X,checks:[]})}function kv($,w){if(!VG(w))throw Error("Invalid input to extend: expected a plain object");let X={...$._zod.def,get shape(){let G={...$._zod.def.shape,...w};return z7(this,"shape",G),G},checks:[]};return t1($,X)}function Cv($,w){return t1($,{...$._zod.def,get shape(){let X={...$._zod.def.shape,...w._zod.def.shape};return z7(this,"shape",X),X},catchall:w._zod.def.catchall,checks:[]})}function vv($,w,X){let G=w._zod.def.shape,E={...G};if(X)for(let J in X){if(!(J in G))throw Error(`Unrecognized key: "${J}"`);if(!X[J])continue;E[J]=$?new $({type:"optional",innerType:G[J]}):G[J]}else for(let J in G)E[J]=$?new $({type:"optional",innerType:G[J]}):G[J];return t1(w,{...w._zod.def,shape:E,checks:[]})}function _v($,w,X){let G=w._zod.def.shape,E={...G};if(X)for(let J in X){if(!(J in E))throw Error(`Unrecognized key: "${J}"`);if(!X[J])continue;E[J]=new $({type:"nonoptional",innerType:G[J]})}else for(let J in G)E[J]=new $({type:"nonoptional",innerType:G[J]});return t1(w,{...w._zod.def,shape:E,checks:[]})}function MX($,w=0){for(let X=w;X<$.issues.length;X++)if($.issues[X]?.continue!==!0)return!0;return!1}function d1($,w){return w.map((X)=>{var G;return(G=X).path??(G.path=[]),X.path.unshift($),X})}function s6($){return typeof $==="string"?$:$?.message}function k1($,w,X){let G={...$,path:$.path??[]};if(!$.message){let E=s6($.inst?._zod.def?.error?.($))??s6(w?.error?.($))??s6(X.customError?.($))??s6(X.localeError?.($))??"Invalid input";G.message=E}if(delete G.inst,delete G.continue,!w?.reportInput)delete G.input;return G}function NM($){if($ instanceof Set)return"set";if($ instanceof Map)return"map";if($ instanceof File)return"file";return"unknown"}function wE($){if(Array.isArray($))return"array";if(typeof $==="string")return"string";return"unknown"}function R7(...$){let[w,X,G]=$;if(typeof w==="string")return{message:w,code:"custom",input:X,inst:G};return{...w}}function fv($){return Object.entries($).filter(([w,X])=>{return Number.isNaN(Number.parseInt(w,10))}).map((w)=>w[1])}class HM{constructor(...$){}}var uJ,Q7,qv=($)=>{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}`)}},B7,UM,V7,OM;var Hw=B(()=>{uJ=Error.captureStackTrace?Error.captureStackTrace:(...$)=>{};Q7=a6(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch($){return!1}});B7=new Set(["string","number","symbol"]),UM=new Set(["string","number","bigint","boolean","symbol","undefined"]);V7={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]},OM={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]}});function FM($,w=(X)=>X.message){let X={},G=[];for(let E of $.issues)if(E.path.length>0)X[E.path[0]]=X[E.path[0]]||[],X[E.path[0]].push(w(E));else G.push(w(E));return{formErrors:G,fieldErrors:X}}function MM($,w){let X=w||function(J){return J.message},G={_errors:[]},E=(J)=>{for(let W of J.issues)if(W.code==="invalid_union"&&W.errors.length)W.errors.map((Y)=>E({issues:Y}));else if(W.code==="invalid_key")E({issues:W.issues});else if(W.code==="invalid_element")E({issues:W.issues});else if(W.path.length===0)G._errors.push(X(W));else{let Y=G,A=0;while(A<W.path.length){let D=W.path[A];if(A!==W.path.length-1)Y[D]=Y[D]||{_errors:[]};else Y[D]=Y[D]||{_errors:[]},Y[D]._errors.push(X(W));Y=Y[D],A++}}};return E($),G}var LM=($,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,F7,2)},enumerable:!0}),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},mJ,T7;var I7=B(()=>{BG();Hw();mJ=P("$ZodError",LM),T7=P("$ZodError",LM,{Parent:Error})});var zM=($)=>(w,X,G,E)=>{let J=G?Object.assign(G,{async:!1}):{async:!1},W=w._zod.run({value:X,issues:[]},J);if(W instanceof Promise)throw new yw;if(W.issues.length){let Y=new(E?.Err??$)(W.issues.map((A)=>k1(A,J,D1())));throw uJ(Y,E?.callee),Y}return W.value},QM=($)=>async(w,X,G,E)=>{let J=G?Object.assign(G,{async:!0}):{async:!0},W=w._zod.run({value:X,issues:[]},J);if(W instanceof Promise)W=await W;if(W.issues.length){let Y=new(E?.Err??$)(W.issues.map((A)=>k1(A,J,D1())));throw uJ(Y,E?.callee),Y}return W.value},j7=($)=>(w,X,G)=>{let E=G?{...G,async:!1}:{async:!1},J=w._zod.run({value:X,issues:[]},E);if(J instanceof Promise)throw new yw;return J.issues.length?{success:!1,error:new($??mJ)(J.issues.map((W)=>k1(W,E,D1())))}:{success:!0,data:J.value}},XE,P7=($)=>async(w,X,G)=>{let E=G?Object.assign(G,{async:!0}):{async:!0},J=w._zod.run({value:X,issues:[]},E);if(J instanceof Promise)J=await J;return J.issues.length?{success:!1,error:new $(J.issues.map((W)=>k1(W,E,D1())))}:{success:!0,data:J.value}},nJ;var q7=B(()=>{BG();I7();Hw();XE=j7(T7),nJ=P7(T7)});function SM(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}function gM($){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 hM($){return new RegExp(`^${gM($)}$`)}function uM($){let w=gM({precision:$.precision}),X=["Z"];if($.local)X.push("");if($.offset)X.push("([+-]\\d{2}:\\d{2})");let G=`${w}(?:${X.join("|")})`;return new RegExp(`^${xM}T(?:${G})$`)}var BM,KM,VM,RM,TM,IM,jM,PM,S7=($)=>{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})$`)},qM,ZM,bM,kM,CM,vM,Z7,_M,fM,xM="(?:(?:\\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])))",yM,cM=($)=>{let w=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${w}$`)},mM,nM,pM,rM,iM,oM;var pJ=B(()=>{BM=/^[cC][^\s-]{8,}$/,KM=/^[0-9a-z]+$/,VM=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,RM=/^[0-9a-vA-V]{20}$/,TM=/^[A-Za-z0-9]{27}$/,IM=/^[a-zA-Z0-9_-]{21}$/,jM=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,PM=/^([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})$/,qM=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;ZM=/^(?:(?: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])$/,bM=/^(([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})$/,kM=/^((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])$/,CM=/^(([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])$/,vM=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Z7=/^[A-Za-z0-9_-]*$/,_M=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,fM=/^\+(?:[0-9]){6,14}[0-9]$/,yM=new RegExp(`^${xM}$`);mM=/^\d+$/,nM=/^-?\d+(?:\.\d+)?/i,pM=/true|false/i,rM=/null/i,iM=/^[^A-Z]*$/,oM=/^[^a-z]*$/});var j$,tM,k7,C7,dM,lM,sM,aM,eM,GE,$z,wz,Xz,Gz,Ez,Jz,Wz;var rJ=B(()=>{BG();pJ();Hw();j$=P("$ZodCheck",($,w)=>{var X;$._zod??($._zod={}),$._zod.def=w,(X=$._zod).onattach??(X.onattach=[])}),tM={number:"number",bigint:"bigint",object:"date"},k7=P("$ZodCheckLessThan",($,w)=>{j$.init($,w);let X=tM[typeof w.value];$._zod.onattach.push((G)=>{let E=G._zod.bag,J=(w.inclusive?E.maximum:E.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(w.value<J)if(w.inclusive)E.maximum=w.value;else E.exclusiveMaximum=w.value}),$._zod.check=(G)=>{if(w.inclusive?G.value<=w.value:G.value<w.value)return;G.issues.push({origin:X,code:"too_big",maximum:w.value,input:G.value,inclusive:w.inclusive,inst:$,continue:!w.abort})}}),C7=P("$ZodCheckGreaterThan",($,w)=>{j$.init($,w);let X=tM[typeof w.value];$._zod.onattach.push((G)=>{let E=G._zod.bag,J=(w.inclusive?E.minimum:E.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(w.value>J)if(w.inclusive)E.minimum=w.value;else E.exclusiveMinimum=w.value}),$._zod.check=(G)=>{if(w.inclusive?G.value>=w.value:G.value>w.value)return;G.issues.push({origin:X,code:"too_small",minimum:w.value,input:G.value,inclusive:w.inclusive,inst:$,continue:!w.abort})}}),dM=P("$ZodCheckMultipleOf",($,w)=>{j$.init($,w),$._zod.onattach.push((X)=>{var G;(G=X._zod.bag).multipleOf??(G.multipleOf=w.value)}),$._zod.check=(X)=>{if(typeof X.value!==typeof w.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof X.value==="bigint"?X.value%w.value===BigInt(0):M7(X.value,w.value)===0)return;X.issues.push({origin:typeof X.value,code:"not_multiple_of",divisor:w.value,input:X.value,inst:$,continue:!w.abort})}}),lM=P("$ZodCheckNumberFormat",($,w)=>{j$.init($,w),w.format=w.format||"float64";let X=w.format?.includes("int"),G=X?"int":"number",[E,J]=V7[w.format];$._zod.onattach.push((W)=>{let Y=W._zod.bag;if(Y.format=w.format,Y.minimum=E,Y.maximum=J,X)Y.pattern=mM}),$._zod.check=(W)=>{let Y=W.value;if(X){if(!Number.isInteger(Y)){W.issues.push({expected:G,format:w.format,code:"invalid_type",input:Y,inst:$});return}if(!Number.isSafeInteger(Y)){if(Y>0)W.issues.push({input:Y,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:G,continue:!w.abort});else W.issues.push({input:Y,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:G,continue:!w.abort});return}}if(Y<E)W.issues.push({origin:"number",input:Y,code:"too_small",minimum:E,inclusive:!0,inst:$,continue:!w.abort});if(Y>J)W.issues.push({origin:"number",input:Y,code:"too_big",maximum:J,inst:$})}}),sM=P("$ZodCheckMaxLength",($,w)=>{var X;j$.init($,w),(X=$._zod.def).when??(X.when=(G)=>{let E=G.value;return!e6(E)&&E.length!==void 0}),$._zod.onattach.push((G)=>{let E=G._zod.bag.maximum??Number.POSITIVE_INFINITY;if(w.maximum<E)G._zod.bag.maximum=w.maximum}),$._zod.check=(G)=>{let E=G.value;if(E.length<=w.maximum)return;let W=wE(E);G.issues.push({origin:W,code:"too_big",maximum:w.maximum,inclusive:!0,input:E,inst:$,continue:!w.abort})}}),aM=P("$ZodCheckMinLength",($,w)=>{var X;j$.init($,w),(X=$._zod.def).when??(X.when=(G)=>{let E=G.value;return!e6(E)&&E.length!==void 0}),$._zod.onattach.push((G)=>{let E=G._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(w.minimum>E)G._zod.bag.minimum=w.minimum}),$._zod.check=(G)=>{let E=G.value;if(E.length>=w.minimum)return;let W=wE(E);G.issues.push({origin:W,code:"too_small",minimum:w.minimum,inclusive:!0,input:E,inst:$,continue:!w.abort})}}),eM=P("$ZodCheckLengthEquals",($,w)=>{var X;j$.init($,w),(X=$._zod.def).when??(X.when=(G)=>{let E=G.value;return!e6(E)&&E.length!==void 0}),$._zod.onattach.push((G)=>{let E=G._zod.bag;E.minimum=w.length,E.maximum=w.length,E.length=w.length}),$._zod.check=(G)=>{let E=G.value,J=E.length;if(J===w.length)return;let W=wE(E),Y=J>w.length;G.issues.push({origin:W,...Y?{code:"too_big",maximum:w.length}:{code:"too_small",minimum:w.length},inclusive:!0,exact:!0,input:G.value,inst:$,continue:!w.abort})}}),GE=P("$ZodCheckStringFormat",($,w)=>{var X,G;if(j$.init($,w),$._zod.onattach.push((E)=>{let J=E._zod.bag;if(J.format=w.format,w.pattern)J.patterns??(J.patterns=new Set),J.patterns.add(w.pattern)}),w.pattern)(X=$._zod).check??(X.check=(E)=>{if(w.pattern.lastIndex=0,w.pattern.test(E.value))return;E.issues.push({origin:"string",code:"invalid_format",format:w.format,input:E.value,...w.pattern?{pattern:w.pattern.toString()}:{},inst:$,continue:!w.abort})});else(G=$._zod).check??(G.check=()=>{})}),$z=P("$ZodCheckRegex",($,w)=>{GE.init($,w),$._zod.check=(X)=>{if(w.pattern.lastIndex=0,w.pattern.test(X.value))return;X.issues.push({origin:"string",code:"invalid_format",format:"regex",input:X.value,pattern:w.pattern.toString(),inst:$,continue:!w.abort})}}),wz=P("$ZodCheckLowerCase",($,w)=>{w.pattern??(w.pattern=iM),GE.init($,w)}),Xz=P("$ZodCheckUpperCase",($,w)=>{w.pattern??(w.pattern=oM),GE.init($,w)}),Gz=P("$ZodCheckIncludes",($,w)=>{j$.init($,w);let X=gw(w.includes),G=new RegExp(typeof w.position==="number"?`^.{${w.position}}${X}`:X);w.pattern=G,$._zod.onattach.push((E)=>{let J=E._zod.bag;J.patterns??(J.patterns=new Set),J.patterns.add(G)}),$._zod.check=(E)=>{if(E.value.includes(w.includes,w.position))return;E.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:w.includes,input:E.value,inst:$,continue:!w.abort})}}),Ez=P("$ZodCheckStartsWith",($,w)=>{j$.init($,w);let X=new RegExp(`^${gw(w.prefix)}.*`);w.pattern??(w.pattern=X),$._zod.onattach.push((G)=>{let E=G._zod.bag;E.patterns??(E.patterns=new Set),E.patterns.add(X)}),$._zod.check=(G)=>{if(G.value.startsWith(w.prefix))return;G.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:w.prefix,input:G.value,inst:$,continue:!w.abort})}}),Jz=P("$ZodCheckEndsWith",($,w)=>{j$.init($,w);let X=new RegExp(`.*${gw(w.suffix)}$`);w.pattern??(w.pattern=X),$._zod.onattach.push((G)=>{let E=G._zod.bag;E.patterns??(E.patterns=new Set),E.patterns.add(X)}),$._zod.check=(G)=>{if(G.value.endsWith(w.suffix))return;G.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:w.suffix,input:G.value,inst:$,continue:!w.abort})}}),Wz=P("$ZodCheckOverwrite",($,w)=>{j$.init($,w),$._zod.check=(X)=>{X.value=w.tx(X.value)}})});class v7{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 X=$.split(`
|
|
467
|
-
|
|
468
|
-
`))}}var Az;var _7=B(()=>{Az={major:4,minor:0,patch:0}});function yz($){if($==="")return!0;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}function yv($){if(!Z7.test($))return!1;let w=$.replace(/[-_]/g,(G)=>G==="-"?"+":"/"),X=w.padEnd(Math.ceil(w.length/4)*4,"=");return yz(X)}function gv($,w=null){try{let X=$.split(".");if(X.length!==3)return!1;let[G]=X;if(!G)return!1;let E=JSON.parse(atob(G));if("typ"in E&&E?.typ!=="JWT")return!1;if(!E.alg)return!1;if(w&&(!("alg"in E)||E.alg!==w))return!1;return!0}catch{return!1}}function Dz($,w,X){if($.issues.length)w.issues.push(...d1(X,$.issues));w.value[X]=$.value}function iJ($,w,X){if($.issues.length)w.issues.push(...d1(X,$.issues));w.value[X]=$.value}function Uz($,w,X,G){if($.issues.length)if(G[X]===void 0)if(X in G)w.value[X]=void 0;else w.value[X]=$.value;else w.issues.push(...d1(X,$.issues));else if($.value===void 0){if(X in G)w.value[X]=void 0}else w.value[X]=$.value}function Oz($,w,X,G){for(let E of $)if(E.issues.length===0)return w.value=E.value,w;return w.issues.push({code:"invalid_union",input:w.value,inst:X,errors:$.map((E)=>E.issues.map((J)=>k1(J,G,D1())))}),w}function f7($,w){if($===w)return{valid:!0,data:$};if($ instanceof Date&&w instanceof Date&&+$===+w)return{valid:!0,data:$};if(VG($)&&VG(w)){let X=Object.keys(w),G=Object.keys($).filter((J)=>X.indexOf(J)!==-1),E={...$,...w};for(let J of G){let W=f7($[J],w[J]);if(!W.valid)return{valid:!1,mergeErrorPath:[J,...W.mergeErrorPath]};E[J]=W.data}return{valid:!0,data:E}}if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return{valid:!1,mergeErrorPath:[]};let X=[];for(let G=0;G<$.length;G++){let E=$[G],J=w[G],W=f7(E,J);if(!W.valid)return{valid:!1,mergeErrorPath:[G,...W.mergeErrorPath]};X.push(W.data)}return{valid:!0,data:X}}return{valid:!1,mergeErrorPath:[]}}function Nz($,w,X){if(w.issues.length)$.issues.push(...w.issues);if(X.issues.length)$.issues.push(...X.issues);if(MX($))return $;let G=f7(w.value,X.value);if(!G.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(G.mergeErrorPath)}`);return $.value=G.data,$}function Hz($,w){if($.value===void 0)$.value=w.defaultValue;return $}function Lz($,w){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:w});return $}function Fz($,w,X){if(MX($))return $;return w.out._zod.run({value:$.value,issues:$.issues},X)}function Mz($){return $.value=Object.freeze($.value),$}function zz($,w,X,G){if(!$){let E={code:"custom",input:X,inst:G,path:[...G._zod.def.path??[]],continue:!G._zod.def.abort};if(G._zod.def.params)E.params=G._zod.def.params;w.issues.push(R7(E))}}var S0,oJ,v0,Qz,Bz,Kz,Vz,Rz,Tz,Iz,jz,Pz,qz,Sz,Zz,bz,kz,Cz,vz,_z,fz,xz,gz,hz,uz,cz,x7,mz,nz,pz,rz,iz,oz,tz,y7,dz,lz,sz,az,ez,$Q,wQ,XQ,GQ,EQ,JQ,WQ,YQ,AQ,DQ;var UQ=B(()=>{rJ();BG();q7();pJ();Hw();_7();Hw();S0=P("$ZodType",($,w)=>{var X;$??($={}),$._zod.def=w,$._zod.bag=$._zod.bag||{},$._zod.version=Az;let G=[...$._zod.def.checks??[]];if($._zod.traits.has("$ZodCheck"))G.unshift($);for(let E of G)for(let J of E._zod.onattach)J($);if(G.length===0)(X=$._zod).deferred??(X.deferred=[]),$._zod.deferred?.push(()=>{$._zod.run=$._zod.parse});else{let E=(J,W,Y)=>{let A=MX(J),D;for(let U of W){if(U._zod.def.when){if(!U._zod.def.when(J))continue}else if(A)continue;let N=J.issues.length,H=U._zod.check(J);if(H instanceof Promise&&Y?.async===!1)throw new yw;if(D||H instanceof Promise)D=(D??Promise.resolve()).then(async()=>{if(await H,J.issues.length===N)return;if(!A)A=MX(J,N)});else{if(J.issues.length===N)continue;if(!A)A=MX(J,N)}}if(D)return D.then(()=>{return J});return J};$._zod.run=(J,W)=>{let Y=$._zod.parse(J,W);if(Y instanceof Promise){if(W.async===!1)throw new yw;return Y.then((A)=>E(A,G,W))}return E(Y,G,W)}}$["~standard"]={validate:(E)=>{try{let J=XE($,E);return J.success?{value:J.data}:{issues:J.error?.issues}}catch(J){return nJ($,E).then((W)=>W.success?{value:W.data}:{issues:W.error?.issues})}},vendor:"zod",version:1}}),oJ=P("$ZodString",($,w)=>{S0.init($,w),$._zod.pattern=[...$?._zod.bag?.patterns??[]].pop()??cM($._zod.bag),$._zod.parse=(X,G)=>{if(w.coerce)try{X.value=String(X.value)}catch(E){}if(typeof X.value==="string")return X;return X.issues.push({expected:"string",code:"invalid_type",input:X.value,inst:$}),X}}),v0=P("$ZodStringFormat",($,w)=>{GE.init($,w),oJ.init($,w)}),Qz=P("$ZodGUID",($,w)=>{w.pattern??(w.pattern=PM),v0.init($,w)}),Bz=P("$ZodUUID",($,w)=>{if(w.version){let G={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[w.version];if(G===void 0)throw Error(`Invalid UUID version: "${w.version}"`);w.pattern??(w.pattern=S7(G))}else w.pattern??(w.pattern=S7());v0.init($,w)}),Kz=P("$ZodEmail",($,w)=>{w.pattern??(w.pattern=qM),v0.init($,w)}),Vz=P("$ZodURL",($,w)=>{v0.init($,w),$._zod.check=(X)=>{try{let G=X.value,E=new URL(G),J=E.href;if(w.hostname){if(w.hostname.lastIndex=0,!w.hostname.test(E.hostname))X.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:_M.source,input:X.value,inst:$,continue:!w.abort})}if(w.protocol){if(w.protocol.lastIndex=0,!w.protocol.test(E.protocol.endsWith(":")?E.protocol.slice(0,-1):E.protocol))X.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:w.protocol.source,input:X.value,inst:$,continue:!w.abort})}if(!G.endsWith("/")&&J.endsWith("/"))X.value=J.slice(0,-1);else X.value=J;return}catch(G){X.issues.push({code:"invalid_format",format:"url",input:X.value,inst:$,continue:!w.abort})}}}),Rz=P("$ZodEmoji",($,w)=>{w.pattern??(w.pattern=SM()),v0.init($,w)}),Tz=P("$ZodNanoID",($,w)=>{w.pattern??(w.pattern=IM),v0.init($,w)}),Iz=P("$ZodCUID",($,w)=>{w.pattern??(w.pattern=BM),v0.init($,w)}),jz=P("$ZodCUID2",($,w)=>{w.pattern??(w.pattern=KM),v0.init($,w)}),Pz=P("$ZodULID",($,w)=>{w.pattern??(w.pattern=VM),v0.init($,w)}),qz=P("$ZodXID",($,w)=>{w.pattern??(w.pattern=RM),v0.init($,w)}),Sz=P("$ZodKSUID",($,w)=>{w.pattern??(w.pattern=TM),v0.init($,w)}),Zz=P("$ZodISODateTime",($,w)=>{w.pattern??(w.pattern=uM(w)),v0.init($,w)}),bz=P("$ZodISODate",($,w)=>{w.pattern??(w.pattern=yM),v0.init($,w)}),kz=P("$ZodISOTime",($,w)=>{w.pattern??(w.pattern=hM(w)),v0.init($,w)}),Cz=P("$ZodISODuration",($,w)=>{w.pattern??(w.pattern=jM),v0.init($,w)}),vz=P("$ZodIPv4",($,w)=>{w.pattern??(w.pattern=ZM),v0.init($,w),$._zod.onattach.push((X)=>{let G=X._zod.bag;G.format="ipv4"})}),_z=P("$ZodIPv6",($,w)=>{w.pattern??(w.pattern=bM),v0.init($,w),$._zod.onattach.push((X)=>{let G=X._zod.bag;G.format="ipv6"}),$._zod.check=(X)=>{try{new URL(`http://[${X.value}]`)}catch{X.issues.push({code:"invalid_format",format:"ipv6",input:X.value,inst:$,continue:!w.abort})}}}),fz=P("$ZodCIDRv4",($,w)=>{w.pattern??(w.pattern=kM),v0.init($,w)}),xz=P("$ZodCIDRv6",($,w)=>{w.pattern??(w.pattern=CM),v0.init($,w),$._zod.check=(X)=>{let[G,E]=X.value.split("/");try{if(!E)throw Error();let J=Number(E);if(`${J}`!==E)throw Error();if(J<0||J>128)throw Error();new URL(`http://[${G}]`)}catch{X.issues.push({code:"invalid_format",format:"cidrv6",input:X.value,inst:$,continue:!w.abort})}}});gz=P("$ZodBase64",($,w)=>{w.pattern??(w.pattern=vM),v0.init($,w),$._zod.onattach.push((X)=>{X._zod.bag.contentEncoding="base64"}),$._zod.check=(X)=>{if(yz(X.value))return;X.issues.push({code:"invalid_format",format:"base64",input:X.value,inst:$,continue:!w.abort})}});hz=P("$ZodBase64URL",($,w)=>{w.pattern??(w.pattern=Z7),v0.init($,w),$._zod.onattach.push((X)=>{X._zod.bag.contentEncoding="base64url"}),$._zod.check=(X)=>{if(yv(X.value))return;X.issues.push({code:"invalid_format",format:"base64url",input:X.value,inst:$,continue:!w.abort})}}),uz=P("$ZodE164",($,w)=>{w.pattern??(w.pattern=fM),v0.init($,w)});cz=P("$ZodJWT",($,w)=>{v0.init($,w),$._zod.check=(X)=>{if(gv(X.value,w.alg))return;X.issues.push({code:"invalid_format",format:"jwt",input:X.value,inst:$,continue:!w.abort})}}),x7=P("$ZodNumber",($,w)=>{S0.init($,w),$._zod.pattern=$._zod.bag.pattern??nM,$._zod.parse=(X,G)=>{if(w.coerce)try{X.value=Number(X.value)}catch(W){}let E=X.value;if(typeof E==="number"&&!Number.isNaN(E)&&Number.isFinite(E))return X;let J=typeof E==="number"?Number.isNaN(E)?"NaN":!Number.isFinite(E)?"Infinity":void 0:void 0;return X.issues.push({expected:"number",code:"invalid_type",input:E,inst:$,...J?{received:J}:{}}),X}}),mz=P("$ZodNumber",($,w)=>{lM.init($,w),x7.init($,w)}),nz=P("$ZodBoolean",($,w)=>{S0.init($,w),$._zod.pattern=pM,$._zod.parse=(X,G)=>{if(w.coerce)try{X.value=Boolean(X.value)}catch(J){}let E=X.value;if(typeof E==="boolean")return X;return X.issues.push({expected:"boolean",code:"invalid_type",input:E,inst:$}),X}}),pz=P("$ZodNull",($,w)=>{S0.init($,w),$._zod.pattern=rM,$._zod.values=new Set([null]),$._zod.parse=(X,G)=>{let E=X.value;if(E===null)return X;return X.issues.push({expected:"null",code:"invalid_type",input:E,inst:$}),X}}),rz=P("$ZodUnknown",($,w)=>{S0.init($,w),$._zod.parse=(X)=>X}),iz=P("$ZodNever",($,w)=>{S0.init($,w),$._zod.parse=(X,G)=>{return X.issues.push({expected:"never",code:"invalid_type",input:X.value,inst:$}),X}});oz=P("$ZodArray",($,w)=>{S0.init($,w),$._zod.parse=(X,G)=>{let E=X.value;if(!Array.isArray(E))return X.issues.push({expected:"array",code:"invalid_type",input:E,inst:$}),X;X.value=Array(E.length);let J=[];for(let W=0;W<E.length;W++){let Y=E[W],A=w.element._zod.run({value:Y,issues:[]},G);if(A instanceof Promise)J.push(A.then((D)=>Dz(D,X,W)));else Dz(A,X,W)}if(J.length)return Promise.all(J).then(()=>X);return X}});tz=P("$ZodObject",($,w)=>{S0.init($,w);let X=a6(()=>{let N=Object.keys(w.shape);for(let L of N)if(!(w.shape[L]instanceof S0))throw Error(`Invalid element at key "${L}": expected a Zod schema`);let H=K7(w.shape);return{shape:w.shape,keys:N,keySet:new Set(N),numKeys:N.length,optionalKeys:new Set(H)}});q0($._zod,"propValues",()=>{let N=w.shape,H={};for(let L in N){let F=N[L]._zod;if(F.values){H[L]??(H[L]=new Set);for(let M of F.values)H[L].add(M)}}return H});let G=(N)=>{let H=new v7(["shape","payload","ctx"]),L=X.value,F=(R)=>{let T=FX(R);return`shape[${T}]._zod.run({ value: input[${T}], issues: [] }, ctx)`};H.write("const input = payload.value;");let M=Object.create(null),z=0;for(let R of L.keys)M[R]=`key_${z++}`;H.write("const newResult = {}");for(let R of L.keys)if(L.optionalKeys.has(R)){let T=M[R];H.write(`const ${T} = ${F(R)};`);let v=FX(R);H.write(`
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
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({...Dj(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 Z_(){return x().$client}var z9,Wj,b_;var Oj=R(()=>{N1();y$();z9=new p0,Wj={task:"tasks",project:"projects",memory:"memories",prompt:"prompts"},b_=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()}))})}}}}});z9.openapi(b_,async($)=>{let{resource_type:w}=$.req.valid("query"),E=Z_(),X=w?[[w,Wj[w]]]:Object.entries(Wj),G=[];for(let[J,A]of X){let D=E.query(`SELECT j.value AS tag, COUNT(*) AS count
|
|
517
|
+
FROM ${A}, json_each(${A}.tags) AS j
|
|
518
|
+
WHERE ${A}.tags IS NOT NULL
|
|
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 Yj($){return{...$,created_at:$.created_at.toISOString()}}var N6,Uj,C_,__,v_,f_;var Hj=R(()=>{N1();x1();X1();hA();y$();d$();i$();N6=new p0,Uj=U.object({id:U.string(),from_task_id:U.string(),to_task_id:U.string(),link_type:Y9,created_at:U.string().datetime()}).openapi("TaskLink"),C_=U.object({to_task_id:U.string(),link_type:Y9}).openapi("CreateTaskLink"),__=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(Uj)})}}}}}),v_=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:C_}}}},responses:{201:{description:"Created",content:{"application/json":{schema:Uj}}}}}),f_=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"}}});N6.openapi(__,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:IJ(V(f$.from_task_id,E),V(f$.to_task_id,E))});return $.json({links:G.map(Yj)})});N6.openapi(v_,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(Yj(W),201)});N6.openapi(f_,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 T9($,w){return $.query(`SELECT t.id, t.title, t.status
|
|
521
|
+
FROM task_links tl
|
|
522
|
+
JOIN tasks t ON t.id = tl.from_task_id
|
|
523
|
+
WHERE tl.to_task_id = ? AND tl.link_type = 'blocks'
|
|
524
|
+
AND t.status NOT IN ('done', 'cancelled')
|
|
525
|
+
UNION
|
|
526
|
+
SELECT t.id, t.title, t.status
|
|
527
|
+
FROM task_links tl
|
|
528
|
+
JOIN tasks t ON t.id = tl.to_task_id
|
|
529
|
+
WHERE tl.from_task_id = ? AND tl.link_type = 'blocked_by'
|
|
530
|
+
AND t.status NOT IN ('done', 'cancelled')`).all(w,w)}function Lj($,w){let E=$.query(`SELECT DISTINCT dependent_id AS id FROM (
|
|
531
|
+
SELECT tl.to_task_id AS dependent_id
|
|
532
|
+
FROM task_links tl
|
|
533
|
+
WHERE tl.from_task_id = ? AND tl.link_type = 'blocks'
|
|
534
|
+
UNION
|
|
535
|
+
SELECT tl.from_task_id AS dependent_id
|
|
536
|
+
FROM task_links tl
|
|
537
|
+
WHERE tl.to_task_id = ? AND tl.link_type = 'blocked_by'
|
|
538
|
+
)`).all(w,w),X=[];for(let{id:G}of E)if(T9($,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 Fj($,w){let E=$.query(`SELECT tl.to_task_id FROM task_links tl
|
|
539
|
+
WHERE tl.from_task_id = ? AND tl.link_type = 'subtask_of'
|
|
540
|
+
LIMIT 1`).get(w);if(!E)return null;let X=E.to_task_id,G=$.query(`SELECT
|
|
541
|
+
COUNT(*) as total,
|
|
542
|
+
SUM(CASE WHEN t.status IN ('done', 'cancelled') THEN 1 ELSE 0 END) as done
|
|
543
|
+
FROM task_links tl
|
|
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(`
|
|
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(`
|
|
548
|
+
if (${Q}.issues.length) {
|
|
549
|
+
if (input[${k}] === undefined) {
|
|
550
|
+
if (${k} in input) {
|
|
551
|
+
newResult[${k}] = undefined;
|
|
473
552
|
}
|
|
474
553
|
} else {
|
|
475
554
|
payload.issues = payload.issues.concat(
|
|
476
|
-
${
|
|
555
|
+
${Q}.issues.map((iss) => ({
|
|
477
556
|
...iss,
|
|
478
|
-
path: iss.path ? [${
|
|
557
|
+
path: iss.path ? [${k}, ...iss.path] : [${k}],
|
|
479
558
|
}))
|
|
480
559
|
);
|
|
481
560
|
}
|
|
482
|
-
} else if (${
|
|
483
|
-
if (${
|
|
561
|
+
} else if (${Q}.value === undefined) {
|
|
562
|
+
if (${k} in input) newResult[${k}] = undefined;
|
|
484
563
|
} else {
|
|
485
|
-
newResult[${
|
|
564
|
+
newResult[${k}] = ${Q}.value;
|
|
486
565
|
}
|
|
487
|
-
`)}else{let
|
|
488
|
-
if (${
|
|
566
|
+
`)}else{let Q=j[B];H.write(`const ${Q} = ${F(B)};`),H.write(`
|
|
567
|
+
if (${Q}.issues.length) payload.issues = payload.issues.concat(${Q}.issues.map(iss => ({
|
|
489
568
|
...iss,
|
|
490
|
-
path: iss.path ? [${
|
|
491
|
-
})));`),H.write(`newResult[${FX(R)}] = ${T}.value`)}H.write("payload.value = newResult;"),H.write("return payload;");let Q=H.compile();return(R,T)=>Q(N,R,T)},E,J=KG,W=!gJ.jitless,A=W&&Q7.value,D=w.catchall,U;$._zod.parse=(N,H)=>{U??(U=X.value);let L=N.value;if(!J(L))return N.issues.push({expected:"object",code:"invalid_type",input:L,inst:$}),N;let F=[];if(W&&A&&H?.async===!1&&H.jitless!==!0){if(!E)E=G(w.shape);N=E(N,H)}else{N.value={};let T=U.shape;for(let v of U.keys){let f=T[v],k=f._zod.run({value:L[v],issues:[]},H),m=f._zod.optin==="optional"&&f._zod.optout==="optional";if(k instanceof Promise)F.push(k.then((F0)=>m?Uz(F0,N,v,L):iJ(F0,N,v)));else if(m)Uz(k,N,v,L);else iJ(k,N,v)}}if(!D)return F.length?Promise.all(F).then(()=>N):N;let M=[],z=U.keySet,Q=D._zod,R=Q.def.type;for(let T of Object.keys(L)){if(z.has(T))continue;if(R==="never"){M.push(T);continue}let v=Q.run({value:L[T],issues:[]},H);if(v instanceof Promise)F.push(v.then((f)=>iJ(f,N,T)));else iJ(v,N,T)}if(M.length)N.issues.push({code:"unrecognized_keys",keys:M,input:L,inst:$});if(!F.length)return N;return Promise.all(F).then(()=>{return N})}});y7=P("$ZodUnion",($,w)=>{S0.init($,w),q0($._zod,"optin",()=>w.options.some((X)=>X._zod.optin==="optional")?"optional":void 0),q0($._zod,"optout",()=>w.options.some((X)=>X._zod.optout==="optional")?"optional":void 0),q0($._zod,"values",()=>{if(w.options.every((X)=>X._zod.values))return new Set(w.options.flatMap((X)=>Array.from(X._zod.values)));return}),q0($._zod,"pattern",()=>{if(w.options.every((X)=>X._zod.pattern)){let X=w.options.map((G)=>G._zod.pattern);return new RegExp(`^(${X.map((G)=>$E(G.source)).join("|")})$`)}return}),$._zod.parse=(X,G)=>{let E=!1,J=[];for(let W of w.options){let Y=W._zod.run({value:X.value,issues:[]},G);if(Y instanceof Promise)J.push(Y),E=!0;else{if(Y.issues.length===0)return Y;J.push(Y)}}if(!E)return Oz(J,X,$,G);return Promise.all(J).then((W)=>{return Oz(W,X,$,G)})}}),dz=P("$ZodDiscriminatedUnion",($,w)=>{y7.init($,w);let X=$._zod.parse;q0($._zod,"propValues",()=>{let E={};for(let J of w.options){let W=J._zod.propValues;if(!W||Object.keys(W).length===0)throw Error(`Invalid discriminated union option at index "${w.options.indexOf(J)}"`);for(let[Y,A]of Object.entries(W)){if(!E[Y])E[Y]=new Set;for(let D of A)E[Y].add(D)}}return E});let G=a6(()=>{let E=w.options,J=new Map;for(let W of E){let Y=W._zod.propValues[w.discriminator];if(!Y||Y.size===0)throw Error(`Invalid discriminated union option at index "${w.options.indexOf(W)}"`);for(let A of Y){if(J.has(A))throw Error(`Duplicate discriminator value "${String(A)}"`);J.set(A,W)}}return J});$._zod.parse=(E,J)=>{let W=E.value;if(!KG(W))return E.issues.push({code:"invalid_type",expected:"object",input:W,inst:$}),E;let Y=G.value.get(W?.[w.discriminator]);if(Y)return Y._zod.run(E,J);if(w.unionFallback)return X(E,J);return E.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:W,path:[w.discriminator],inst:$}),E}}),lz=P("$ZodIntersection",($,w)=>{S0.init($,w),$._zod.parse=(X,G)=>{let E=X.value,J=w.left._zod.run({value:E,issues:[]},G),W=w.right._zod.run({value:E,issues:[]},G);if(J instanceof Promise||W instanceof Promise)return Promise.all([J,W]).then(([A,D])=>{return Nz(X,A,D)});return Nz(X,J,W)}});sz=P("$ZodRecord",($,w)=>{S0.init($,w),$._zod.parse=(X,G)=>{let E=X.value;if(!VG(E))return X.issues.push({expected:"record",code:"invalid_type",input:E,inst:$}),X;let J=[];if(w.keyType._zod.values){let W=w.keyType._zod.values;X.value={};for(let A of W)if(typeof A==="string"||typeof A==="number"||typeof A==="symbol"){let D=w.valueType._zod.run({value:E[A],issues:[]},G);if(D instanceof Promise)J.push(D.then((U)=>{if(U.issues.length)X.issues.push(...d1(A,U.issues));X.value[A]=U.value}));else{if(D.issues.length)X.issues.push(...d1(A,D.issues));X.value[A]=D.value}}let Y;for(let A in E)if(!W.has(A))Y=Y??[],Y.push(A);if(Y&&Y.length>0)X.issues.push({code:"unrecognized_keys",input:E,inst:$,keys:Y})}else{X.value={};for(let W of Reflect.ownKeys(E)){if(W==="__proto__")continue;let Y=w.keyType._zod.run({value:W,issues:[]},G);if(Y instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(Y.issues.length){X.issues.push({origin:"record",code:"invalid_key",issues:Y.issues.map((D)=>k1(D,G,D1())),input:W,path:[W],inst:$}),X.value[Y.value]=Y.value;continue}let A=w.valueType._zod.run({value:E[W],issues:[]},G);if(A instanceof Promise)J.push(A.then((D)=>{if(D.issues.length)X.issues.push(...d1(W,D.issues));X.value[Y.value]=D.value}));else{if(A.issues.length)X.issues.push(...d1(W,A.issues));X.value[Y.value]=A.value}}}if(J.length)return Promise.all(J).then(()=>X);return X}}),az=P("$ZodEnum",($,w)=>{S0.init($,w);let X=L7(w.entries);$._zod.values=new Set(X),$._zod.pattern=new RegExp(`^(${X.filter((G)=>B7.has(typeof G)).map((G)=>typeof G==="string"?gw(G):G.toString()).join("|")})$`),$._zod.parse=(G,E)=>{let J=G.value;if($._zod.values.has(J))return G;return G.issues.push({code:"invalid_value",values:X,input:J,inst:$}),G}}),ez=P("$ZodLiteral",($,w)=>{S0.init($,w),$._zod.values=new Set(w.values),$._zod.pattern=new RegExp(`^(${w.values.map((X)=>typeof X==="string"?gw(X):X?X.toString():String(X)).join("|")})$`),$._zod.parse=(X,G)=>{let E=X.value;if($._zod.values.has(E))return X;return X.issues.push({code:"invalid_value",values:w.values,input:E,inst:$}),X}}),$Q=P("$ZodTransform",($,w)=>{S0.init($,w),$._zod.parse=(X,G)=>{let E=w.transform(X.value,X);if(G.async)return(E instanceof Promise?E:Promise.resolve(E)).then((W)=>{return X.value=W,X});if(E instanceof Promise)throw new yw;return X.value=E,X}}),wQ=P("$ZodOptional",($,w)=>{S0.init($,w),$._zod.optin="optional",$._zod.optout="optional",q0($._zod,"values",()=>{return w.innerType._zod.values?new Set([...w.innerType._zod.values,void 0]):void 0}),q0($._zod,"pattern",()=>{let X=w.innerType._zod.pattern;return X?new RegExp(`^(${$E(X.source)})?$`):void 0}),$._zod.parse=(X,G)=>{if(w.innerType._zod.optin==="optional")return w.innerType._zod.run(X,G);if(X.value===void 0)return X;return w.innerType._zod.run(X,G)}}),XQ=P("$ZodNullable",($,w)=>{S0.init($,w),q0($._zod,"optin",()=>w.innerType._zod.optin),q0($._zod,"optout",()=>w.innerType._zod.optout),q0($._zod,"pattern",()=>{let X=w.innerType._zod.pattern;return X?new RegExp(`^(${$E(X.source)}|null)$`):void 0}),q0($._zod,"values",()=>{return w.innerType._zod.values?new Set([...w.innerType._zod.values,null]):void 0}),$._zod.parse=(X,G)=>{if(X.value===null)return X;return w.innerType._zod.run(X,G)}}),GQ=P("$ZodDefault",($,w)=>{S0.init($,w),$._zod.optin="optional",q0($._zod,"values",()=>w.innerType._zod.values),$._zod.parse=(X,G)=>{if(X.value===void 0)return X.value=w.defaultValue,X;let E=w.innerType._zod.run(X,G);if(E instanceof Promise)return E.then((J)=>Hz(J,w));return Hz(E,w)}});EQ=P("$ZodPrefault",($,w)=>{S0.init($,w),$._zod.optin="optional",q0($._zod,"values",()=>w.innerType._zod.values),$._zod.parse=(X,G)=>{if(X.value===void 0)X.value=w.defaultValue;return w.innerType._zod.run(X,G)}}),JQ=P("$ZodNonOptional",($,w)=>{S0.init($,w),q0($._zod,"values",()=>{let X=w.innerType._zod.values;return X?new Set([...X].filter((G)=>G!==void 0)):void 0}),$._zod.parse=(X,G)=>{let E=w.innerType._zod.run(X,G);if(E instanceof Promise)return E.then((J)=>Lz(J,$));return Lz(E,$)}});WQ=P("$ZodCatch",($,w)=>{S0.init($,w),$._zod.optin="optional",q0($._zod,"optout",()=>w.innerType._zod.optout),q0($._zod,"values",()=>w.innerType._zod.values),$._zod.parse=(X,G)=>{let E=w.innerType._zod.run(X,G);if(E instanceof Promise)return E.then((J)=>{if(X.value=J.value,J.issues.length)X.value=w.catchValue({...X,error:{issues:J.issues.map((W)=>k1(W,G,D1()))},input:X.value}),X.issues=[];return X});if(X.value=E.value,E.issues.length)X.value=w.catchValue({...X,error:{issues:E.issues.map((J)=>k1(J,G,D1()))},input:X.value}),X.issues=[];return X}}),YQ=P("$ZodPipe",($,w)=>{S0.init($,w),q0($._zod,"values",()=>w.in._zod.values),q0($._zod,"optin",()=>w.in._zod.optin),q0($._zod,"optout",()=>w.out._zod.optout),$._zod.parse=(X,G)=>{let E=w.in._zod.run(X,G);if(E instanceof Promise)return E.then((J)=>Fz(J,w,G));return Fz(E,w,G)}});AQ=P("$ZodReadonly",($,w)=>{S0.init($,w),q0($._zod,"propValues",()=>w.innerType._zod.propValues),q0($._zod,"values",()=>w.innerType._zod.values),q0($._zod,"optin",()=>w.innerType._zod.optin),q0($._zod,"optout",()=>w.innerType._zod.optout),$._zod.parse=(X,G)=>{let E=w.innerType._zod.run(X,G);if(E instanceof Promise)return E.then(Mz);return Mz(E)}});DQ=P("$ZodCustom",($,w)=>{j$.init($,w),S0.init($,w),$._zod.parse=(X,G)=>{return X},$._zod.check=(X)=>{let G=X.value,E=w.fn(G);if(E instanceof Promise)return E.then((J)=>zz(J,X,G,$));zz(E,X,G,$);return}})});function g7(){return{localeError:uv()}}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},uv=()=>{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(G){return $[G]??null}let X={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(G)=>{switch(G.code){case"invalid_type":return`Invalid input: expected ${G.expected}, received ${hv(G.input)}`;case"invalid_value":if(G.values.length===1)return`Invalid input: expected ${cJ(G.values[0])}`;return`Invalid option: expected one of ${hJ(G.values,"|")}`;case"too_big":{let E=G.inclusive?"<=":"<",J=w(G.origin);if(J)return`Too big: expected ${G.origin??"value"} to have ${E}${G.maximum.toString()} ${J.unit??"elements"}`;return`Too big: expected ${G.origin??"value"} to be ${E}${G.maximum.toString()}`}case"too_small":{let E=G.inclusive?">=":">",J=w(G.origin);if(J)return`Too small: expected ${G.origin} to have ${E}${G.minimum.toString()} ${J.unit}`;return`Too small: expected ${G.origin} to be ${E}${G.minimum.toString()}`}case"invalid_format":{let E=G;if(E.format==="starts_with")return`Invalid string: must start with "${E.prefix}"`;if(E.format==="ends_with")return`Invalid string: must end with "${E.suffix}"`;if(E.format==="includes")return`Invalid string: must include "${E.includes}"`;if(E.format==="regex")return`Invalid string: must match pattern ${E.pattern}`;return`Invalid ${X[E.format]??G.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${G.divisor}`;case"unrecognized_keys":return`Unrecognized key${G.keys.length>1?"s":""}: ${hJ(G.keys,", ")}`;case"invalid_key":return`Invalid key in ${G.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${G.origin}`;default:return"Invalid input"}}};var OQ=B(()=>{Hw()});var tJ=()=>{};class NQ{constructor(){this._map=new Map,this._idmap=new Map}add($,...w){let X=w[0];if(this._map.set($,X),X&&typeof X==="object"&&"id"in X){if(this._idmap.has(X.id))throw Error(`ID ${X.id} already exists in the registry`);this._idmap.set(X.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 X={...this.get(w)??{}};return delete X.id,{...X,...this._map.get($)}}return this._map.get($)}has($){return this._map.has($)}}function cv(){return new NQ}var sX0,aX0,EE;var HQ=B(()=>{sX0=Symbol("ZodOutput"),aX0=Symbol("ZodInput");EE=cv()});function LQ($,w){return new $({type:"string",...o(w)})}function FQ($,w){return new $({type:"string",format:"email",check:"string_format",abort:!1,...o(w)})}function u7($,w){return new $({type:"string",format:"guid",check:"string_format",abort:!1,...o(w)})}function MQ($,w){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,...o(w)})}function zQ($,w){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...o(w)})}function QQ($,w){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...o(w)})}function BQ($,w){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...o(w)})}function KQ($,w){return new $({type:"string",format:"url",check:"string_format",abort:!1,...o(w)})}function VQ($,w){return new $({type:"string",format:"emoji",check:"string_format",abort:!1,...o(w)})}function RQ($,w){return new $({type:"string",format:"nanoid",check:"string_format",abort:!1,...o(w)})}function TQ($,w){return new $({type:"string",format:"cuid",check:"string_format",abort:!1,...o(w)})}function IQ($,w){return new $({type:"string",format:"cuid2",check:"string_format",abort:!1,...o(w)})}function jQ($,w){return new $({type:"string",format:"ulid",check:"string_format",abort:!1,...o(w)})}function PQ($,w){return new $({type:"string",format:"xid",check:"string_format",abort:!1,...o(w)})}function qQ($,w){return new $({type:"string",format:"ksuid",check:"string_format",abort:!1,...o(w)})}function SQ($,w){return new $({type:"string",format:"ipv4",check:"string_format",abort:!1,...o(w)})}function ZQ($,w){return new $({type:"string",format:"ipv6",check:"string_format",abort:!1,...o(w)})}function bQ($,w){return new $({type:"string",format:"cidrv4",check:"string_format",abort:!1,...o(w)})}function kQ($,w){return new $({type:"string",format:"cidrv6",check:"string_format",abort:!1,...o(w)})}function CQ($,w){return new $({type:"string",format:"base64",check:"string_format",abort:!1,...o(w)})}function vQ($,w){return new $({type:"string",format:"base64url",check:"string_format",abort:!1,...o(w)})}function _Q($,w){return new $({type:"string",format:"e164",check:"string_format",abort:!1,...o(w)})}function fQ($,w){return new $({type:"string",format:"jwt",check:"string_format",abort:!1,...o(w)})}function xQ($,w){return new $({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...o(w)})}function yQ($,w){return new $({type:"string",format:"date",check:"string_format",...o(w)})}function gQ($,w){return new $({type:"string",format:"time",check:"string_format",precision:null,...o(w)})}function hQ($,w){return new $({type:"string",format:"duration",check:"string_format",...o(w)})}function uQ($,w){return new $({type:"number",checks:[],...o(w)})}function cQ($,w){return new $({type:"number",check:"number_format",abort:!1,format:"safeint",...o(w)})}function mQ($,w){return new $({type:"boolean",...o(w)})}function nQ($,w){return new $({type:"null",...o(w)})}function pQ($){return new $({type:"unknown"})}function rQ($,w){return new $({type:"never",...o(w)})}function dJ($,w){return new k7({check:"less_than",...o(w),value:$,inclusive:!1})}function JE($,w){return new k7({check:"less_than",...o(w),value:$,inclusive:!0})}function lJ($,w){return new C7({check:"greater_than",...o(w),value:$,inclusive:!1})}function WE($,w){return new C7({check:"greater_than",...o(w),value:$,inclusive:!0})}function sJ($,w){return new dM({check:"multiple_of",...o(w),value:$})}function aJ($,w){return new sM({check:"max_length",...o(w),maximum:$})}function RG($,w){return new aM({check:"min_length",...o(w),minimum:$})}function eJ($,w){return new eM({check:"length_equals",...o(w),length:$})}function c7($,w){return new $z({check:"string_format",format:"regex",...o(w),pattern:$})}function m7($){return new wz({check:"string_format",format:"lowercase",...o($)})}function n7($){return new Xz({check:"string_format",format:"uppercase",...o($)})}function p7($,w){return new Gz({check:"string_format",format:"includes",...o(w),includes:$})}function r7($,w){return new Ez({check:"string_format",format:"starts_with",...o(w),prefix:$})}function i7($,w){return new Jz({check:"string_format",format:"ends_with",...o(w),suffix:$})}function zX($){return new Wz({check:"overwrite",tx:$})}function o7($){return zX((w)=>w.normalize($))}function t7(){return zX(($)=>$.trim())}function d7(){return zX(($)=>$.toLowerCase())}function l7(){return zX(($)=>$.toUpperCase())}function iQ($,w,X){return new $({type:"array",element:w,...o(X)})}function oQ($,w,X){let G=o(X);return G.abort??(G.abort=!0),new $({type:"custom",check:"custom",fn:w,...G})}function tQ($,w,X){return new $({type:"custom",check:"custom",fn:w,...o(X)})}var dQ=B(()=>{rJ();Hw()});var lQ=()=>{};var sQ=()=>{};var aQ=()=>{};var U1=B(()=>{Hw();pJ();tJ();aQ();BG();q7();I7();UQ();rJ();_7();HQ();lQ();dQ();sQ()});var eQ=B(()=>{U1()});var $B=()=>{};var wB=()=>{};var XB=()=>{};var GB=()=>{};var EB=B(()=>{U1();tJ();XB();GB();eQ();$B();wB()});var JB=B(()=>{EB()});var WB=B(()=>{JB()});function IG($){return!!$._zod}function hw($,w){if(IG($))return XE($,w);return $.safeParse(w)}function $8($){if(!$)return;let w;if(IG($))w=$._zod?.def?.shape;else w=$.shape;if(!w)return;if(typeof w==="function")try{return w()}catch{return}return w}function YB($){if(IG($)){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 X=$._def;if(X){if(X.value!==void 0)return X.value;if(Array.isArray(X.values)&&X.values.length>0)return X.values[0]}let G=$.value;if(G!==void 0)return G;return}var w8=B(()=>{WB()});var s7=B(()=>{U1()});var YE={};e1(YE,{time:()=>$Y,duration:()=>wY,datetime:()=>a7,date:()=>e7,ZodISOTime:()=>UB,ZodISODuration:()=>OB,ZodISODateTime:()=>AB,ZodISODate:()=>DB});function a7($){return xQ(AB,$)}function e7($){return yQ(DB,$)}function $Y($){return gQ(UB,$)}function wY($){return hQ(OB,$)}var AB,DB,UB,OB;var XY=B(()=>{U1();GY();AB=P("ZodISODateTime",($,w)=>{Zz.init($,w),g0.init($,w)});DB=P("ZodISODate",($,w)=>{bz.init($,w),g0.init($,w)});UB=P("ZodISOTime",($,w)=>{kz.init($,w),g0.init($,w)});OB=P("ZodISODuration",($,w)=>{Cz.init($,w),g0.init($,w)})});var NB=($,w)=>{mJ.init($,w),$.name="ZodError",Object.defineProperties($,{format:{value:(X)=>MM($,X)},flatten:{value:(X)=>FM($,X)},addIssue:{value:(X)=>$.issues.push(X)},addIssues:{value:(X)=>$.issues.push(...X)},isEmpty:{get(){return $.issues.length===0}}})},mG0,AE;var EY=B(()=>{U1();U1();mG0=P("ZodError",NB),AE=P("ZodError",NB,{Parent:Error})});var HB,LB,FB,MB;var JY=B(()=>{U1();EY();HB=zM(AE),LB=QM(AE),FB=j7(AE),MB=P7(AE)});function j($){return LQ(av,$)}function T0($){return uQ(VB,$)}function QB($){return cQ(M_,$)}function U$($){return mQ(z_,$)}function AY($){return nQ(Q_,$)}function h0(){return pQ(B_)}function V_($){return rQ(K_,$)}function U0($,w){return iQ(R_,$,w)}function h($,w){let X={type:"object",get shape(){return z0.assignProp(this,"shape",{...$}),this.shape},...z0.normalizeParams(w)};return new RB(X)}function k$($,w){return new RB({type:"object",get shape(){return z0.assignProp(this,"shape",{...$}),this.shape},catchall:h0(),...z0.normalizeParams(w)})}function Z0($,w){return new TB({type:"union",options:$,...z0.normalizeParams(w)})}function DY($,w,X){return new T_({type:"union",options:w,discriminator:$,...z0.normalizeParams(X)})}function G8($,w){return new I_({type:"intersection",left:$,right:w})}function u0($,w,X){return new j_({type:"record",keyType:$,valueType:w,...z0.normalizeParams(X)})}function p$($,w){let X=Array.isArray($)?Object.fromEntries($.map((G)=>[G,G])):$;return new WY({type:"enum",entries:X,...z0.normalizeParams(w)})}function n($,w){return new P_({type:"literal",values:Array.isArray($)?$:[$],...z0.normalizeParams(w)})}function IB($){return new q_({type:"transform",transform:$})}function i0($){return new jB({type:"optional",innerType:$})}function BB($){return new S_({type:"nullable",innerType:$})}function b_($,w){return new Z_({type:"default",innerType:$,get defaultValue(){return typeof w==="function"?w():w}})}function C_($,w){return new k_({type:"prefault",innerType:$,get defaultValue(){return typeof w==="function"?w():w}})}function v_($,w){return new PB({type:"nonoptional",innerType:$,...z0.normalizeParams(w)})}function f_($,w){return new __({type:"catch",innerType:$,catchValue:typeof w==="function"?w:()=>w})}function YY($,w){return new x_({type:"pipe",in:$,out:w})}function g_($){return new y_({type:"readonly",innerType:$})}function h_($){let w=new j$({check:"custom"});return w._zod.check=$,w}function SB($,w){return oQ(qB,$??(()=>!0),w)}function u_($,w={}){return tQ(qB,$,w)}function c_($){let w=h_((X)=>{return X.addIssue=(G)=>{if(typeof G==="string")X.issues.push(z0.issue(G,X.value,w._zod.def));else{let E=G;if(E.fatal)E.continue=!1;E.code??(E.code="custom"),E.input??(E.input=X.value),E.inst??(E.inst=w),E.continue??(E.continue=!w._zod.def.abort),X.issues.push(z0.issue(E))}},$(X.value,X)});return w}function UY($,w){return YY(IB($),w)}var o0,KB,av,g0,ev,zB,X8,$_,w_,X_,G_,E_,J_,W_,Y_,A_,D_,U_,O_,N_,H_,L_,F_,VB,M_,z_,Q_,B_,K_,R_,RB,TB,T_,I_,j_,WY,P_,q_,jB,S_,Z_,k_,PB,__,x_,y_,qB;var GY=B(()=>{U1();U1();s7();XY();JY();o0=P("ZodType",($,w)=>{return S0.init($,w),$.def=w,Object.defineProperty($,"_def",{value:w}),$.check=(...X)=>{return $.clone({...w,checks:[...w.checks??[],...X.map((G)=>typeof G==="function"?{_zod:{check:G,def:{check:"custom"},onattach:[]}}:G)]})},$.clone=(X,G)=>t1($,X,G),$.brand=()=>$,$.register=(X,G)=>{return X.add($,G),$},$.parse=(X,G)=>HB($,X,G,{callee:$.parse}),$.safeParse=(X,G)=>FB($,X,G),$.parseAsync=async(X,G)=>LB($,X,G,{callee:$.parseAsync}),$.safeParseAsync=async(X,G)=>MB($,X,G),$.spa=$.safeParseAsync,$.refine=(X,G)=>$.check(u_(X,G)),$.superRefine=(X)=>$.check(c_(X)),$.overwrite=(X)=>$.check(zX(X)),$.optional=()=>i0($),$.nullable=()=>BB($),$.nullish=()=>i0(BB($)),$.nonoptional=(X)=>v_($,X),$.array=()=>U0($),$.or=(X)=>Z0([$,X]),$.and=(X)=>G8($,X),$.transform=(X)=>YY($,IB(X)),$.default=(X)=>b_($,X),$.prefault=(X)=>C_($,X),$.catch=(X)=>f_($,X),$.pipe=(X)=>YY($,X),$.readonly=()=>g_($),$.describe=(X)=>{let G=$.clone();return EE.add(G,{description:X}),G},Object.defineProperty($,"description",{get(){return EE.get($)?.description},configurable:!0}),$.meta=(...X)=>{if(X.length===0)return EE.get($);let G=$.clone();return EE.add(G,X[0]),G},$.isOptional=()=>$.safeParse(void 0).success,$.isNullable=()=>$.safeParse(null).success,$}),KB=P("_ZodString",($,w)=>{oJ.init($,w),o0.init($,w);let X=$._zod.bag;$.format=X.format??null,$.minLength=X.minimum??null,$.maxLength=X.maximum??null,$.regex=(...G)=>$.check(c7(...G)),$.includes=(...G)=>$.check(p7(...G)),$.startsWith=(...G)=>$.check(r7(...G)),$.endsWith=(...G)=>$.check(i7(...G)),$.min=(...G)=>$.check(RG(...G)),$.max=(...G)=>$.check(aJ(...G)),$.length=(...G)=>$.check(eJ(...G)),$.nonempty=(...G)=>$.check(RG(1,...G)),$.lowercase=(G)=>$.check(m7(G)),$.uppercase=(G)=>$.check(n7(G)),$.trim=()=>$.check(t7()),$.normalize=(...G)=>$.check(o7(...G)),$.toLowerCase=()=>$.check(d7()),$.toUpperCase=()=>$.check(l7())}),av=P("ZodString",($,w)=>{oJ.init($,w),KB.init($,w),$.email=(X)=>$.check(FQ(ev,X)),$.url=(X)=>$.check(KQ($_,X)),$.jwt=(X)=>$.check(fQ(F_,X)),$.emoji=(X)=>$.check(VQ(w_,X)),$.guid=(X)=>$.check(u7(zB,X)),$.uuid=(X)=>$.check(MQ(X8,X)),$.uuidv4=(X)=>$.check(zQ(X8,X)),$.uuidv6=(X)=>$.check(QQ(X8,X)),$.uuidv7=(X)=>$.check(BQ(X8,X)),$.nanoid=(X)=>$.check(RQ(X_,X)),$.guid=(X)=>$.check(u7(zB,X)),$.cuid=(X)=>$.check(TQ(G_,X)),$.cuid2=(X)=>$.check(IQ(E_,X)),$.ulid=(X)=>$.check(jQ(J_,X)),$.base64=(X)=>$.check(CQ(N_,X)),$.base64url=(X)=>$.check(vQ(H_,X)),$.xid=(X)=>$.check(PQ(W_,X)),$.ksuid=(X)=>$.check(qQ(Y_,X)),$.ipv4=(X)=>$.check(SQ(A_,X)),$.ipv6=(X)=>$.check(ZQ(D_,X)),$.cidrv4=(X)=>$.check(bQ(U_,X)),$.cidrv6=(X)=>$.check(kQ(O_,X)),$.e164=(X)=>$.check(_Q(L_,X)),$.datetime=(X)=>$.check(a7(X)),$.date=(X)=>$.check(e7(X)),$.time=(X)=>$.check($Y(X)),$.duration=(X)=>$.check(wY(X))});g0=P("ZodStringFormat",($,w)=>{v0.init($,w),KB.init($,w)}),ev=P("ZodEmail",($,w)=>{Kz.init($,w),g0.init($,w)}),zB=P("ZodGUID",($,w)=>{Qz.init($,w),g0.init($,w)}),X8=P("ZodUUID",($,w)=>{Bz.init($,w),g0.init($,w)}),$_=P("ZodURL",($,w)=>{Vz.init($,w),g0.init($,w)}),w_=P("ZodEmoji",($,w)=>{Rz.init($,w),g0.init($,w)}),X_=P("ZodNanoID",($,w)=>{Tz.init($,w),g0.init($,w)}),G_=P("ZodCUID",($,w)=>{Iz.init($,w),g0.init($,w)}),E_=P("ZodCUID2",($,w)=>{jz.init($,w),g0.init($,w)}),J_=P("ZodULID",($,w)=>{Pz.init($,w),g0.init($,w)}),W_=P("ZodXID",($,w)=>{qz.init($,w),g0.init($,w)}),Y_=P("ZodKSUID",($,w)=>{Sz.init($,w),g0.init($,w)}),A_=P("ZodIPv4",($,w)=>{vz.init($,w),g0.init($,w)}),D_=P("ZodIPv6",($,w)=>{_z.init($,w),g0.init($,w)}),U_=P("ZodCIDRv4",($,w)=>{fz.init($,w),g0.init($,w)}),O_=P("ZodCIDRv6",($,w)=>{xz.init($,w),g0.init($,w)}),N_=P("ZodBase64",($,w)=>{gz.init($,w),g0.init($,w)}),H_=P("ZodBase64URL",($,w)=>{hz.init($,w),g0.init($,w)}),L_=P("ZodE164",($,w)=>{uz.init($,w),g0.init($,w)}),F_=P("ZodJWT",($,w)=>{cz.init($,w),g0.init($,w)}),VB=P("ZodNumber",($,w)=>{x7.init($,w),o0.init($,w),$.gt=(G,E)=>$.check(lJ(G,E)),$.gte=(G,E)=>$.check(WE(G,E)),$.min=(G,E)=>$.check(WE(G,E)),$.lt=(G,E)=>$.check(dJ(G,E)),$.lte=(G,E)=>$.check(JE(G,E)),$.max=(G,E)=>$.check(JE(G,E)),$.int=(G)=>$.check(QB(G)),$.safe=(G)=>$.check(QB(G)),$.positive=(G)=>$.check(lJ(0,G)),$.nonnegative=(G)=>$.check(WE(0,G)),$.negative=(G)=>$.check(dJ(0,G)),$.nonpositive=(G)=>$.check(JE(0,G)),$.multipleOf=(G,E)=>$.check(sJ(G,E)),$.step=(G,E)=>$.check(sJ(G,E)),$.finite=()=>$;let X=$._zod.bag;$.minValue=Math.max(X.minimum??Number.NEGATIVE_INFINITY,X.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,$.maxValue=Math.min(X.maximum??Number.POSITIVE_INFINITY,X.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,$.isInt=(X.format??"").includes("int")||Number.isSafeInteger(X.multipleOf??0.5),$.isFinite=!0,$.format=X.format??null});M_=P("ZodNumberFormat",($,w)=>{mz.init($,w),VB.init($,w)});z_=P("ZodBoolean",($,w)=>{nz.init($,w),o0.init($,w)});Q_=P("ZodNull",($,w)=>{pz.init($,w),o0.init($,w)});B_=P("ZodUnknown",($,w)=>{rz.init($,w),o0.init($,w)});K_=P("ZodNever",($,w)=>{iz.init($,w),o0.init($,w)});R_=P("ZodArray",($,w)=>{oz.init($,w),o0.init($,w),$.element=w.element,$.min=(X,G)=>$.check(RG(X,G)),$.nonempty=(X)=>$.check(RG(1,X)),$.max=(X,G)=>$.check(aJ(X,G)),$.length=(X,G)=>$.check(eJ(X,G)),$.unwrap=()=>$.element});RB=P("ZodObject",($,w)=>{tz.init($,w),o0.init($,w),z0.defineLazy($,"shape",()=>w.shape),$.keyof=()=>p$(Object.keys($._zod.def.shape)),$.catchall=(X)=>$.clone({...$._zod.def,catchall:X}),$.passthrough=()=>$.clone({...$._zod.def,catchall:h0()}),$.loose=()=>$.clone({...$._zod.def,catchall:h0()}),$.strict=()=>$.clone({...$._zod.def,catchall:V_()}),$.strip=()=>$.clone({...$._zod.def,catchall:void 0}),$.extend=(X)=>{return z0.extend($,X)},$.merge=(X)=>z0.merge($,X),$.pick=(X)=>z0.pick($,X),$.omit=(X)=>z0.omit($,X),$.partial=(...X)=>z0.partial(jB,$,X[0]),$.required=(...X)=>z0.required(PB,$,X[0])});TB=P("ZodUnion",($,w)=>{y7.init($,w),o0.init($,w),$.options=w.options});T_=P("ZodDiscriminatedUnion",($,w)=>{TB.init($,w),dz.init($,w)});I_=P("ZodIntersection",($,w)=>{lz.init($,w),o0.init($,w)});j_=P("ZodRecord",($,w)=>{sz.init($,w),o0.init($,w),$.keyType=w.keyType,$.valueType=w.valueType});WY=P("ZodEnum",($,w)=>{az.init($,w),o0.init($,w),$.enum=w.entries,$.options=Object.values(w.entries);let X=new Set(Object.keys(w.entries));$.extract=(G,E)=>{let J={};for(let W of G)if(X.has(W))J[W]=w.entries[W];else throw Error(`Key ${W} not found in enum`);return new WY({...w,checks:[],...z0.normalizeParams(E),entries:J})},$.exclude=(G,E)=>{let J={...w.entries};for(let W of G)if(X.has(W))delete J[W];else throw Error(`Key ${W} not found in enum`);return new WY({...w,checks:[],...z0.normalizeParams(E),entries:J})}});P_=P("ZodLiteral",($,w)=>{ez.init($,w),o0.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]}})});q_=P("ZodTransform",($,w)=>{$Q.init($,w),o0.init($,w),$._zod.parse=(X,G)=>{X.addIssue=(J)=>{if(typeof J==="string")X.issues.push(z0.issue(J,X.value,w));else{let W=J;if(W.fatal)W.continue=!1;W.code??(W.code="custom"),W.input??(W.input=X.value),W.inst??(W.inst=$),W.continue??(W.continue=!0),X.issues.push(z0.issue(W))}};let E=w.transform(X.value,X);if(E instanceof Promise)return E.then((J)=>{return X.value=J,X});return X.value=E,X}});jB=P("ZodOptional",($,w)=>{wQ.init($,w),o0.init($,w),$.unwrap=()=>$._zod.def.innerType});S_=P("ZodNullable",($,w)=>{XQ.init($,w),o0.init($,w),$.unwrap=()=>$._zod.def.innerType});Z_=P("ZodDefault",($,w)=>{GQ.init($,w),o0.init($,w),$.unwrap=()=>$._zod.def.innerType,$.removeDefault=$.unwrap});k_=P("ZodPrefault",($,w)=>{EQ.init($,w),o0.init($,w),$.unwrap=()=>$._zod.def.innerType});PB=P("ZodNonOptional",($,w)=>{JQ.init($,w),o0.init($,w),$.unwrap=()=>$._zod.def.innerType});__=P("ZodCatch",($,w)=>{WQ.init($,w),o0.init($,w),$.unwrap=()=>$._zod.def.innerType,$.removeCatch=$.unwrap});x_=P("ZodPipe",($,w)=>{YQ.init($,w),o0.init($,w),$.in=w.in,$.out=w.out});y_=P("ZodReadonly",($,w)=>{AQ.init($,w),o0.init($,w)});qB=P("ZodCustom",($,w)=>{DQ.init($,w),o0.init($,w)})});var ZB=()=>{};var bB=()=>{};var kB=B(()=>{U1();U1();OQ();tJ();XY();bB();GY();s7();EY();JY();ZB();D1(g7())});var CB=B(()=>{kB()});var vB=B(()=>{CB()});var OY="2025-11-25",_B,uw="io.modelcontextprotocol/related-task",J8="2.0",L$,fB,xB,y60,p_,r_,NY,X1,DE,yB=($)=>DE.safeParse($).success,F$,O1,N1,M$,W8,gB,HY=($)=>gB.safeParse($).success,hB,uB=($)=>hB.safeParse($).success,LY,UE=($)=>LY.safeParse($).success,D0,FY,cB=($)=>FY.safeParse($).success,mB,g60,Y8,i_,A8,o_,OE,jG,nB,t_,d_,l_,s_,a_,e_,MY,$f,wf,zY,D8,Xf,Gf,U8,Ef,NE,HE,Jf,LE,PG,Wf,FE,O8,N8,H8,h60,L8,F8,M8,pB,rB,iB,QY,oB,ME,qG,tB,Yf,Af,Df,Uf,Of,BY,Nf,Hf,Lf,Ff,Mf,zf,Qf,Bf,Kf,Vf,Rf,Tf,If,jf,Pf,qf,KY,VY,RY,Sf,Zf,bf,TY,kf,Cf,vf,_f,ff,dB,IY,xf,z8,u60,yf,zE,gf,c60,QE,hf,jY,uf,cf,mf,nf,pf,rf,of,E8,tf,df,lf,BE,PY,sf,af,ef,$x,wx,Xx,Gx,Ex,Jx,Wx,Yx,Ax,Dx,Ux,Ox,Nx,Hx,Lx,SG,Fx,Mx,zx,Qx,Bx,Kx,Vx,qY,Rx,m60,n60,p60,r60,i60,o60,G0,lB;var ZG=B(()=>{vB();_B=[OY,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],L$=SB(($)=>$!==null&&(typeof $==="object"||typeof $==="function")),fB=Z0([j(),T0().int()]),xB=j(),y60=k$({ttl:Z0([T0(),AY()]).optional(),pollInterval:T0().optional()}),p_=h({ttl:T0().optional()}),r_=h({taskId:j()}),NY=k$({progressToken:fB.optional(),[uw]:r_.optional()}),X1=h({_meta:NY.optional()}),DE=X1.extend({task:p_.optional()}),F$=h({method:j(),params:X1.loose().optional()}),O1=h({_meta:NY.optional()}),N1=h({method:j(),params:O1.loose().optional()}),M$=k$({_meta:NY.optional()}),W8=Z0([j(),T0().int()]),gB=h({jsonrpc:n(J8),id:W8,...F$.shape}).strict(),hB=h({jsonrpc:n(J8),...N1.shape}).strict(),LY=h({jsonrpc:n(J8),id:W8,result:M$}).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"})(D0||(D0={}));FY=h({jsonrpc:n(J8),id:W8.optional(),error:h({code:T0().int(),message:j(),data:h0().optional()})}).strict(),mB=Z0([gB,hB,LY,FY]),g60=Z0([LY,FY]),Y8=M$.strict(),i_=O1.extend({requestId:W8.optional(),reason:j().optional()}),A8=N1.extend({method:n("notifications/cancelled"),params:i_}),o_=h({src:j(),mimeType:j().optional(),sizes:U0(j()).optional(),theme:p$(["light","dark"]).optional()}),OE=h({icons:U0(o_).optional()}),jG=h({name:j(),title:j().optional()}),nB=jG.extend({...jG.shape,...OE.shape,version:j(),websiteUrl:j().optional(),description:j().optional()}),t_=G8(h({applyDefaults:U$().optional()}),u0(j(),h0())),d_=UY(($)=>{if($&&typeof $==="object"&&!Array.isArray($)){if(Object.keys($).length===0)return{form:{}}}return $},G8(h({form:t_.optional(),url:L$.optional()}),u0(j(),h0()).optional())),l_=k$({list:L$.optional(),cancel:L$.optional(),requests:k$({sampling:k$({createMessage:L$.optional()}).optional(),elicitation:k$({create:L$.optional()}).optional()}).optional()}),s_=k$({list:L$.optional(),cancel:L$.optional(),requests:k$({tools:k$({call:L$.optional()}).optional()}).optional()}),a_=h({experimental:u0(j(),L$).optional(),sampling:h({context:L$.optional(),tools:L$.optional()}).optional(),elicitation:d_.optional(),roots:h({listChanged:U$().optional()}).optional(),tasks:l_.optional()}),e_=X1.extend({protocolVersion:j(),capabilities:a_,clientInfo:nB}),MY=F$.extend({method:n("initialize"),params:e_}),$f=h({experimental:u0(j(),L$).optional(),logging:L$.optional(),completions:L$.optional(),prompts:h({listChanged:U$().optional()}).optional(),resources:h({subscribe:U$().optional(),listChanged:U$().optional()}).optional(),tools:h({listChanged:U$().optional()}).optional(),tasks:s_.optional()}),wf=M$.extend({protocolVersion:j(),capabilities:$f,serverInfo:nB,instructions:j().optional()}),zY=N1.extend({method:n("notifications/initialized"),params:O1.optional()}),D8=F$.extend({method:n("ping"),params:X1.optional()}),Xf=h({progress:T0(),total:i0(T0()),message:i0(j())}),Gf=h({...O1.shape,...Xf.shape,progressToken:fB}),U8=N1.extend({method:n("notifications/progress"),params:Gf}),Ef=X1.extend({cursor:xB.optional()}),NE=F$.extend({params:Ef.optional()}),HE=M$.extend({nextCursor:xB.optional()}),Jf=p$(["working","input_required","completed","failed","cancelled"]),LE=h({taskId:j(),status:Jf,ttl:Z0([T0(),AY()]),createdAt:j(),lastUpdatedAt:j(),pollInterval:i0(T0()),statusMessage:i0(j())}),PG=M$.extend({task:LE}),Wf=O1.merge(LE),FE=N1.extend({method:n("notifications/tasks/status"),params:Wf}),O8=F$.extend({method:n("tasks/get"),params:X1.extend({taskId:j()})}),N8=M$.merge(LE),H8=F$.extend({method:n("tasks/result"),params:X1.extend({taskId:j()})}),h60=M$.loose(),L8=NE.extend({method:n("tasks/list")}),F8=HE.extend({tasks:U0(LE)}),M8=F$.extend({method:n("tasks/cancel"),params:X1.extend({taskId:j()})}),pB=M$.merge(LE),rB=h({uri:j(),mimeType:i0(j()),_meta:u0(j(),h0()).optional()}),iB=rB.extend({text:j()}),QY=j().refine(($)=>{try{return atob($),!0}catch{return!1}},{message:"Invalid Base64 string"}),oB=rB.extend({blob:QY}),ME=p$(["user","assistant"]),qG=h({audience:U0(ME).optional(),priority:T0().min(0).max(1).optional(),lastModified:YE.datetime({offset:!0}).optional()}),tB=h({...jG.shape,...OE.shape,uri:j(),description:i0(j()),mimeType:i0(j()),annotations:qG.optional(),_meta:i0(k$({}))}),Yf=h({...jG.shape,...OE.shape,uriTemplate:j(),description:i0(j()),mimeType:i0(j()),annotations:qG.optional(),_meta:i0(k$({}))}),Af=NE.extend({method:n("resources/list")}),Df=HE.extend({resources:U0(tB)}),Uf=NE.extend({method:n("resources/templates/list")}),Of=HE.extend({resourceTemplates:U0(Yf)}),BY=X1.extend({uri:j()}),Nf=BY,Hf=F$.extend({method:n("resources/read"),params:Nf}),Lf=M$.extend({contents:U0(Z0([iB,oB]))}),Ff=N1.extend({method:n("notifications/resources/list_changed"),params:O1.optional()}),Mf=BY,zf=F$.extend({method:n("resources/subscribe"),params:Mf}),Qf=BY,Bf=F$.extend({method:n("resources/unsubscribe"),params:Qf}),Kf=O1.extend({uri:j()}),Vf=N1.extend({method:n("notifications/resources/updated"),params:Kf}),Rf=h({name:j(),description:i0(j()),required:i0(U$())}),Tf=h({...jG.shape,...OE.shape,description:i0(j()),arguments:i0(U0(Rf)),_meta:i0(k$({}))}),If=NE.extend({method:n("prompts/list")}),jf=HE.extend({prompts:U0(Tf)}),Pf=X1.extend({name:j(),arguments:u0(j(),j()).optional()}),qf=F$.extend({method:n("prompts/get"),params:Pf}),KY=h({type:n("text"),text:j(),annotations:qG.optional(),_meta:u0(j(),h0()).optional()}),VY=h({type:n("image"),data:QY,mimeType:j(),annotations:qG.optional(),_meta:u0(j(),h0()).optional()}),RY=h({type:n("audio"),data:QY,mimeType:j(),annotations:qG.optional(),_meta:u0(j(),h0()).optional()}),Sf=h({type:n("tool_use"),name:j(),id:j(),input:u0(j(),h0()),_meta:u0(j(),h0()).optional()}),Zf=h({type:n("resource"),resource:Z0([iB,oB]),annotations:qG.optional(),_meta:u0(j(),h0()).optional()}),bf=tB.extend({type:n("resource_link")}),TY=Z0([KY,VY,RY,bf,Zf]),kf=h({role:ME,content:TY}),Cf=M$.extend({description:j().optional(),messages:U0(kf)}),vf=N1.extend({method:n("notifications/prompts/list_changed"),params:O1.optional()}),_f=h({title:j().optional(),readOnlyHint:U$().optional(),destructiveHint:U$().optional(),idempotentHint:U$().optional(),openWorldHint:U$().optional()}),ff=h({taskSupport:p$(["required","optional","forbidden"]).optional()}),dB=h({...jG.shape,...OE.shape,description:j().optional(),inputSchema:h({type:n("object"),properties:u0(j(),L$).optional(),required:U0(j()).optional()}).catchall(h0()),outputSchema:h({type:n("object"),properties:u0(j(),L$).optional(),required:U0(j()).optional()}).catchall(h0()).optional(),annotations:_f.optional(),execution:ff.optional(),_meta:u0(j(),h0()).optional()}),IY=NE.extend({method:n("tools/list")}),xf=HE.extend({tools:U0(dB)}),z8=M$.extend({content:U0(TY).default([]),structuredContent:u0(j(),h0()).optional(),isError:U$().optional()}),u60=z8.or(M$.extend({toolResult:h0()})),yf=DE.extend({name:j(),arguments:u0(j(),h0()).optional()}),zE=F$.extend({method:n("tools/call"),params:yf}),gf=N1.extend({method:n("notifications/tools/list_changed"),params:O1.optional()}),c60=h({autoRefresh:U$().default(!0),debounceMs:T0().int().nonnegative().default(300)}),QE=p$(["debug","info","notice","warning","error","critical","alert","emergency"]),hf=X1.extend({level:QE}),jY=F$.extend({method:n("logging/setLevel"),params:hf}),uf=O1.extend({level:QE,logger:j().optional(),data:h0()}),cf=N1.extend({method:n("notifications/message"),params:uf}),mf=h({name:j().optional()}),nf=h({hints:U0(mf).optional(),costPriority:T0().min(0).max(1).optional(),speedPriority:T0().min(0).max(1).optional(),intelligencePriority:T0().min(0).max(1).optional()}),pf=h({mode:p$(["auto","required","none"]).optional()}),rf=h({type:n("tool_result"),toolUseId:j().describe("The unique identifier for the corresponding tool call."),content:U0(TY).default([]),structuredContent:h({}).loose().optional(),isError:U$().optional(),_meta:u0(j(),h0()).optional()}),of=DY("type",[KY,VY,RY]),E8=DY("type",[KY,VY,RY,Sf,rf]),tf=h({role:ME,content:Z0([E8,U0(E8)]),_meta:u0(j(),h0()).optional()}),df=DE.extend({messages:U0(tf),modelPreferences:nf.optional(),systemPrompt:j().optional(),includeContext:p$(["none","thisServer","allServers"]).optional(),temperature:T0().optional(),maxTokens:T0().int(),stopSequences:U0(j()).optional(),metadata:L$.optional(),tools:U0(dB).optional(),toolChoice:pf.optional()}),lf=F$.extend({method:n("sampling/createMessage"),params:df}),BE=M$.extend({model:j(),stopReason:i0(p$(["endTurn","stopSequence","maxTokens"]).or(j())),role:ME,content:of}),PY=M$.extend({model:j(),stopReason:i0(p$(["endTurn","stopSequence","maxTokens","toolUse"]).or(j())),role:ME,content:Z0([E8,U0(E8)])}),sf=h({type:n("boolean"),title:j().optional(),description:j().optional(),default:U$().optional()}),af=h({type:n("string"),title:j().optional(),description:j().optional(),minLength:T0().optional(),maxLength:T0().optional(),format:p$(["email","uri","date","date-time"]).optional(),default:j().optional()}),ef=h({type:p$(["number","integer"]),title:j().optional(),description:j().optional(),minimum:T0().optional(),maximum:T0().optional(),default:T0().optional()}),$x=h({type:n("string"),title:j().optional(),description:j().optional(),enum:U0(j()),default:j().optional()}),wx=h({type:n("string"),title:j().optional(),description:j().optional(),oneOf:U0(h({const:j(),title:j()})),default:j().optional()}),Xx=h({type:n("string"),title:j().optional(),description:j().optional(),enum:U0(j()),enumNames:U0(j()).optional(),default:j().optional()}),Gx=Z0([$x,wx]),Ex=h({type:n("array"),title:j().optional(),description:j().optional(),minItems:T0().optional(),maxItems:T0().optional(),items:h({type:n("string"),enum:U0(j())}),default:U0(j()).optional()}),Jx=h({type:n("array"),title:j().optional(),description:j().optional(),minItems:T0().optional(),maxItems:T0().optional(),items:h({anyOf:U0(h({const:j(),title:j()}))}),default:U0(j()).optional()}),Wx=Z0([Ex,Jx]),Yx=Z0([Xx,Gx,Wx]),Ax=Z0([Yx,sf,af,ef]),Dx=DE.extend({mode:n("form").optional(),message:j(),requestedSchema:h({type:n("object"),properties:u0(j(),Ax),required:U0(j()).optional()})}),Ux=DE.extend({mode:n("url"),message:j(),elicitationId:j(),url:j().url()}),Ox=Z0([Dx,Ux]),Nx=F$.extend({method:n("elicitation/create"),params:Ox}),Hx=O1.extend({elicitationId:j()}),Lx=N1.extend({method:n("notifications/elicitation/complete"),params:Hx}),SG=M$.extend({action:p$(["accept","decline","cancel"]),content:UY(($)=>$===null?void 0:$,u0(j(),Z0([j(),T0(),U$(),U0(j())])).optional())}),Fx=h({type:n("ref/resource"),uri:j()}),Mx=h({type:n("ref/prompt"),name:j()}),zx=X1.extend({ref:Z0([Mx,Fx]),argument:h({name:j(),value:j()}),context:h({arguments:u0(j(),j()).optional()}).optional()}),Qx=F$.extend({method:n("completion/complete"),params:zx}),Bx=M$.extend({completion:k$({values:U0(j()).max(100),total:i0(T0().int()),hasMore:i0(U$())})}),Kx=h({uri:j().startsWith("file://"),name:j().optional(),_meta:u0(j(),h0()).optional()}),Vx=F$.extend({method:n("roots/list"),params:X1.optional()}),qY=M$.extend({roots:U0(Kx)}),Rx=N1.extend({method:n("notifications/roots/list_changed"),params:O1.optional()}),m60=Z0([D8,MY,Qx,jY,qf,If,Af,Uf,Hf,zf,Bf,zE,IY,O8,H8,L8,M8]),n60=Z0([A8,U8,zY,Rx,FE]),p60=Z0([Y8,BE,PY,SG,qY,N8,F8,PG]),r60=Z0([D8,lf,Nx,Vx,O8,H8,L8,M8]),i60=Z0([A8,U8,cf,Vf,Ff,gf,vf,FE,Lx]),o60=Z0([Y8,wf,Bx,Cf,jf,Df,Of,Lf,z8,xf,N8,F8,PG]);G0=class G0 extends Error{constructor($,w,X){super(`MCP error ${$}: ${w}`);this.code=$,this.data=X,this.name="McpError"}static fromError($,w,X){if($===D0.UrlElicitationRequired&&X){let G=X;if(G.elicitations)return new lB(G.elicitations,w)}return new G0($,w,X)}};lB=class lB extends G0{constructor($,w=`URL elicitation${$.length>1?"s":""} required`){super(D0.UrlElicitationRequired,w,{elicitations:$})}get elicitations(){return this.data?.elicitations??[]}}});function cw($){return $==="completed"||$==="failed"||$==="cancelled"}var Tx;var Q8=B(()=>{Tx=Symbol("Let zodToJsonSchema decide on which parser to use")});var SY=B(()=>{Q8()});var H1=()=>{};var ZY=B(()=>{X$()});var bY=()=>{};var B8=B(()=>{X$()});var kY=B(()=>{X$()});var CY=()=>{};var vY=B(()=>{X$()});var _Y=B(()=>{X$();H1()});var fY=B(()=>{X$()});var PE0;var K8=B(()=>{PE0=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});var V8=B(()=>{X$();K8();B8();H1()});var xY=B(()=>{X$();V8();H1()});var yY=B(()=>{H1()});var R8=B(()=>{X$()});var gY=B(()=>{X$();R8()});var hY=()=>{};var uY=B(()=>{X$()});var cY=B(()=>{X$();H1()});var mY=B(()=>{X$()});var nY=B(()=>{X$()});var pY=B(()=>{X$()});var rY=B(()=>{X$()});var iY=B(()=>{H1()});var oY=B(()=>{H1()});var tY=B(()=>{X$()});var dY=B(()=>{H1();ZY();bY();B8();kY();CY();vY();_Y();fY();xY();yY();gY();hY();uY();cY();mY();nY();V8();pY();K8();rY();iY();R8();oY();tY()});var X$=B(()=>{Q8();dY();H1()});var sB=()=>{};var lY=B(()=>{X$();SY();H1()});var aB=B(()=>{lY();Q8();SY();X$();sB();H1();ZY();bY();B8();kY();CY();vY();_Y();fY();xY();yY();gY();hY();uY();cY();mY();nY();tY();V8();pY();K8();rY();iY();R8();oY();dY();lY()});function sY($){let X=$8($)?.method;if(!X)throw Error("Schema is missing a method literal");let G=YB(X);if(typeof G!=="string")throw Error("Schema method literal must be a string");return G}function aY($,w){let X=hw($,w);if(!X.success)throw X.error;return X.data}var eB=B(()=>{w8();aB()});class eY{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(A8,(w)=>{this._oncancel(w)}),this.setNotificationHandler(U8,(w)=>{this._onprogress(w)}),this.setRequestHandler(D8,(w)=>({})),this._taskStore=$?.taskStore,this._taskMessageQueue=$?.taskMessageQueue,this._taskStore)this.setRequestHandler(O8,async(w,X)=>{let G=await this._taskStore.getTask(w.params.taskId,X.sessionId);if(!G)throw new G0(D0.InvalidParams,"Failed to retrieve task: Task not found");return{...G}}),this.setRequestHandler(H8,async(w,X)=>{let G=async()=>{let E=w.params.taskId;if(this._taskMessageQueue){let W;while(W=await this._taskMessageQueue.dequeue(E,X.sessionId)){if(W.type==="response"||W.type==="error"){let Y=W.message,A=Y.id,D=this._requestResolvers.get(A);if(D)if(this._requestResolvers.delete(A),W.type==="response")D(Y);else{let U=Y,N=new G0(U.error.code,U.error.message,U.error.data);D(N)}else{let U=W.type==="response"?"Response":"Error";this._onerror(Error(`${U} handler missing for request ${A}`))}continue}await this._transport?.send(W.message,{relatedRequestId:X.requestId})}}let J=await this._taskStore.getTask(E,X.sessionId);if(!J)throw new G0(D0.InvalidParams,`Task not found: ${E}`);if(!cw(J.status))return await this._waitForTaskUpdate(E,X.signal),await G();if(cw(J.status)){let W=await this._taskStore.getTaskResult(E,X.sessionId);return this._clearTaskQueue(E),{...W,_meta:{...W._meta,[uw]:{taskId:E}}}}return await G()};return await G()}),this.setRequestHandler(L8,async(w,X)=>{try{let{tasks:G,nextCursor:E}=await this._taskStore.listTasks(w.params?.cursor,X.sessionId);return{tasks:G,nextCursor:E,_meta:{}}}catch(G){throw new G0(D0.InvalidParams,`Failed to list tasks: ${G instanceof Error?G.message:String(G)}`)}}),this.setRequestHandler(M8,async(w,X)=>{try{let G=await this._taskStore.getTask(w.params.taskId,X.sessionId);if(!G)throw new G0(D0.InvalidParams,`Task not found: ${w.params.taskId}`);if(cw(G.status))throw new G0(D0.InvalidParams,`Cannot cancel task in terminal status: ${G.status}`);await this._taskStore.updateTaskStatus(w.params.taskId,"cancelled","Client cancelled task execution.",X.sessionId),this._clearTaskQueue(w.params.taskId);let E=await this._taskStore.getTask(w.params.taskId,X.sessionId);if(!E)throw new G0(D0.InvalidParams,`Task not found after cancellation: ${w.params.taskId}`);return{_meta:{},...E}}catch(G){if(G instanceof G0)throw G;throw new G0(D0.InvalidRequest,`Failed to cancel task: ${G instanceof Error?G.message:String(G)}`)}})}async _oncancel($){if(!$.params.requestId)return;this._requestHandlerAbortControllers.get($.params.requestId)?.abort($.params.reason)}_setupTimeout($,w,X,G,E=!1){this._timeoutInfo.set($,{timeoutId:setTimeout(G,w),startTime:Date.now(),timeout:w,maxTotalTimeout:X,resetTimeoutOnProgress:E,onTimeout:G})}_resetTimeout($){let w=this._timeoutInfo.get($);if(!w)return!1;let X=Date.now()-w.startTime;if(w.maxTotalTimeout&&X>=w.maxTotalTimeout)throw this._timeoutInfo.delete($),G0.fromError(D0.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:w.maxTotalTimeout,totalElapsed:X});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 X=this.transport?.onerror;this._transport.onerror=(E)=>{X?.(E),this._onerror(E)};let G=this._transport?.onmessage;this._transport.onmessage=(E,J)=>{if(G?.(E,J),UE(E)||cB(E))this._onresponse(E);else if(HY(E))this._onrequest(E,J);else if(uB(E))this._onnotification(E);else this._onerror(Error(`Unknown message type: ${JSON.stringify(E)}`))},await this._transport.start()}_onclose(){let $=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let X of this._requestHandlerAbortControllers.values())X.abort();this._requestHandlerAbortControllers.clear();let w=G0.fromError(D0.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let X of $.values())X(w)}_onerror($){this.onerror?.($)}_onnotification($){let w=this._notificationHandlers.get($.method)??this.fallbackNotificationHandler;if(w===void 0)return;Promise.resolve().then(()=>w($)).catch((X)=>this._onerror(Error(`Uncaught error in notification handler: ${X}`)))}_onrequest($,w){let X=this._requestHandlers.get($.method)??this.fallbackRequestHandler,G=this._transport,E=$.params?._meta?.[uw]?.taskId;if(X===void 0){let D={jsonrpc:"2.0",id:$.id,error:{code:D0.MethodNotFound,message:"Method not found"}};if(E&&this._taskMessageQueue)this._enqueueTaskMessage(E,{type:"error",message:D,timestamp:Date.now()},G?.sessionId).catch((U)=>this._onerror(Error(`Failed to enqueue error response: ${U}`)));else G?.send(D).catch((U)=>this._onerror(Error(`Failed to send an error response: ${U}`)));return}let J=new AbortController;this._requestHandlerAbortControllers.set($.id,J);let W=yB($.params)?$.params.task:void 0,Y=this._taskStore?this.requestTaskStore($,G?.sessionId):void 0,A={signal:J.signal,sessionId:G?.sessionId,_meta:$.params?._meta,sendNotification:async(D)=>{if(J.signal.aborted)return;let U={relatedRequestId:$.id};if(E)U.relatedTask={taskId:E};await this.notification(D,U)},sendRequest:async(D,U,N)=>{if(J.signal.aborted)throw new G0(D0.ConnectionClosed,"Request was cancelled");let H={...N,relatedRequestId:$.id};if(E&&!H.relatedTask)H.relatedTask={taskId:E};let L=H.relatedTask?.taskId??E;if(L&&Y)await Y.updateTaskStatus(L,"input_required");return await this.request(D,U,H)},authInfo:w?.authInfo,requestId:$.id,requestInfo:w?.requestInfo,taskId:E,taskStore:Y,taskRequestedTtl:W?.ttl,closeSSEStream:w?.closeSSEStream,closeStandaloneSSEStream:w?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(W)this.assertTaskHandlerCapability($.method)}).then(()=>X($,A)).then(async(D)=>{if(J.signal.aborted)return;let U={result:D,jsonrpc:"2.0",id:$.id};if(E&&this._taskMessageQueue)await this._enqueueTaskMessage(E,{type:"response",message:U,timestamp:Date.now()},G?.sessionId);else await G?.send(U)},async(D)=>{if(J.signal.aborted)return;let U={jsonrpc:"2.0",id:$.id,error:{code:Number.isSafeInteger(D.code)?D.code:D0.InternalError,message:D.message??"Internal error",...D.data!==void 0&&{data:D.data}}};if(E&&this._taskMessageQueue)await this._enqueueTaskMessage(E,{type:"error",message:U,timestamp:Date.now()},G?.sessionId);else await G?.send(U)}).catch((D)=>this._onerror(Error(`Failed to send response: ${D}`))).finally(()=>{this._requestHandlerAbortControllers.delete($.id)})}_onprogress($){let{progressToken:w,...X}=$.params,G=Number(w),E=this._progressHandlers.get(G);if(!E){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify($)}`));return}let J=this._responseHandlers.get(G),W=this._timeoutInfo.get(G);if(W&&J&&W.resetTimeoutOnProgress)try{this._resetTimeout(G)}catch(Y){this._responseHandlers.delete(G),this._progressHandlers.delete(G),this._cleanupTimeout(G),J(Y);return}E(X)}_onresponse($){let w=Number($.id),X=this._requestResolvers.get(w);if(X){if(this._requestResolvers.delete(w),UE($))X($);else{let J=new G0($.error.code,$.error.message,$.error.data);X(J)}return}let G=this._responseHandlers.get(w);if(G===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify($)}`));return}this._responseHandlers.delete(w),this._cleanupTimeout(w);let E=!1;if(UE($)&&$.result&&typeof $.result==="object"){let J=$.result;if(J.task&&typeof J.task==="object"){let W=J.task;if(typeof W.taskId==="string")E=!0,this._taskProgressTokens.set(W.taskId,w)}}if(!E)this._progressHandlers.delete(w);if(UE($))G($);else{let J=G0.fromError($.error.code,$.error.message,$.error.data);G(J)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream($,w,X){let{task:G}=X??{};if(!G){try{yield{type:"result",result:await this.request($,w,X)}}catch(J){yield{type:"error",error:J instanceof G0?J:new G0(D0.InternalError,String(J))}}return}let E;try{let J=await this.request($,PG,X);if(J.task)E=J.task.taskId,yield{type:"taskCreated",task:J.task};else throw new G0(D0.InternalError,"Task creation did not return a task");while(!0){let W=await this.getTask({taskId:E},X);if(yield{type:"taskStatus",task:W},cw(W.status)){if(W.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:E},w,X)};else if(W.status==="failed")yield{type:"error",error:new G0(D0.InternalError,`Task ${E} failed`)};else if(W.status==="cancelled")yield{type:"error",error:new G0(D0.InternalError,`Task ${E} was cancelled`)};return}if(W.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:E},w,X)};return}let Y=W.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((A)=>setTimeout(A,Y)),X?.signal?.throwIfAborted()}}catch(J){yield{type:"error",error:J instanceof G0?J:new G0(D0.InternalError,String(J))}}}request($,w,X){let{relatedRequestId:G,resumptionToken:E,onresumptiontoken:J,task:W,relatedTask:Y}=X??{};return new Promise((A,D)=>{let U=(Q)=>{D(Q)};if(!this._transport){U(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod($.method),W)this.assertTaskCapability($.method)}catch(Q){U(Q);return}X?.signal?.throwIfAborted();let N=this._requestMessageId++,H={...$,jsonrpc:"2.0",id:N};if(X?.onprogress)this._progressHandlers.set(N,X.onprogress),H.params={...$.params,_meta:{...$.params?._meta||{},progressToken:N}};if(W)H.params={...H.params,task:W};if(Y)H.params={...H.params,_meta:{...H.params?._meta||{},[uw]:Y}};let L=(Q)=>{this._responseHandlers.delete(N),this._progressHandlers.delete(N),this._cleanupTimeout(N),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:N,reason:String(Q)}},{relatedRequestId:G,resumptionToken:E,onresumptiontoken:J}).catch((T)=>this._onerror(Error(`Failed to send cancellation: ${T}`)));let R=Q instanceof G0?Q:new G0(D0.RequestTimeout,String(Q));D(R)};this._responseHandlers.set(N,(Q)=>{if(X?.signal?.aborted)return;if(Q instanceof Error)return D(Q);try{let R=hw(w,Q.result);if(!R.success)D(R.error);else A(R.data)}catch(R){D(R)}}),X?.signal?.addEventListener("abort",()=>{L(X?.signal?.reason)});let F=X?.timeout??Zx,M=()=>L(G0.fromError(D0.RequestTimeout,"Request timed out",{timeout:F}));this._setupTimeout(N,F,X?.maxTotalTimeout,M,X?.resetTimeoutOnProgress??!1);let z=Y?.taskId;if(z){let Q=(R)=>{let T=this._responseHandlers.get(N);if(T)T(R);else this._onerror(Error(`Response handler missing for side-channeled request ${N}`))};this._requestResolvers.set(N,Q),this._enqueueTaskMessage(z,{type:"request",message:H,timestamp:Date.now()}).catch((R)=>{this._cleanupTimeout(N),D(R)})}else this._transport.send(H,{relatedRequestId:G,resumptionToken:E,onresumptiontoken:J}).catch((Q)=>{this._cleanupTimeout(N),D(Q)})})}async getTask($,w){return this.request({method:"tasks/get",params:$},N8,w)}async getTaskResult($,w,X){return this.request({method:"tasks/result",params:$},w,X)}async listTasks($,w){return this.request({method:"tasks/list",params:$},F8,w)}async cancelTask($,w){return this.request({method:"tasks/cancel",params:$},pB,w)}async notification($,w){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability($.method);let X=w?.relatedTask?.taskId;if(X){let W={...$,jsonrpc:"2.0",params:{...$.params,_meta:{...$.params?._meta||{},[uw]:w.relatedTask}}};await this._enqueueTaskMessage(X,{type:"notification",message:W,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 W={...$,jsonrpc:"2.0"};if(w?.relatedTask)W={...W,params:{...W.params,_meta:{...W.params?._meta||{},[uw]:w.relatedTask}}};this._transport?.send(W,w).catch((Y)=>this._onerror(Y))});return}let J={...$,jsonrpc:"2.0"};if(w?.relatedTask)J={...J,params:{...J.params,_meta:{...J.params?._meta||{},[uw]:w.relatedTask}}};await this._transport.send(J,w)}setRequestHandler($,w){let X=sY($);this.assertRequestHandlerCapability(X),this._requestHandlers.set(X,(G,E)=>{let J=aY($,G);return Promise.resolve(w(J,E))})}removeRequestHandler($){this._requestHandlers.delete($)}assertCanSetRequestHandler($){if(this._requestHandlers.has($))throw Error(`A request handler for ${$} already exists, which would be overridden`)}setNotificationHandler($,w){let X=sY($);this._notificationHandlers.set(X,(G)=>{let E=aY($,G);return Promise.resolve(w(E))})}removeNotificationHandler($){this._notificationHandlers.delete($)}_cleanupTaskProgressHandler($){let w=this._taskProgressTokens.get($);if(w!==void 0)this._progressHandlers.delete(w),this._taskProgressTokens.delete($)}async _enqueueTaskMessage($,w,X){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let G=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue($,w,X,G)}async _clearTaskQueue($,w){if(this._taskMessageQueue){let X=await this._taskMessageQueue.dequeueAll($,w);for(let G of X)if(G.type==="request"&&HY(G.message)){let E=G.message.id,J=this._requestResolvers.get(E);if(J)J(new G0(D0.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(E);else this._onerror(Error(`Resolver missing for request ${E} during task ${$} cleanup`))}}}async _waitForTaskUpdate($,w){let X=this._options?.defaultTaskPollInterval??1000;try{let G=await this._taskStore?.getTask($);if(G?.pollInterval)X=G.pollInterval}catch{}return new Promise((G,E)=>{if(w.aborted){E(new G0(D0.InvalidRequest,"Request cancelled"));return}let J=setTimeout(G,X);w.addEventListener("abort",()=>{clearTimeout(J),E(new G0(D0.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore($,w){let X=this._taskStore;if(!X)throw Error("No task store configured");return{createTask:async(G)=>{if(!$)throw Error("No request provided");return await X.createTask(G,$.id,{method:$.method,params:$.params},w)},getTask:async(G)=>{let E=await X.getTask(G,w);if(!E)throw new G0(D0.InvalidParams,"Failed to retrieve task: Task not found");return E},storeTaskResult:async(G,E,J)=>{await X.storeTaskResult(G,E,J,w);let W=await X.getTask(G,w);if(W){let Y=FE.parse({method:"notifications/tasks/status",params:W});if(await this.notification(Y),cw(W.status))this._cleanupTaskProgressHandler(G)}},getTaskResult:(G)=>{return X.getTaskResult(G,w)},updateTaskStatus:async(G,E,J)=>{let W=await X.getTask(G,w);if(!W)throw new G0(D0.InvalidParams,`Task "${G}" not found - it may have been cleaned up`);if(cw(W.status))throw new G0(D0.InvalidParams,`Cannot update task "${G}" from terminal status "${W.status}" to "${E}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await X.updateTaskStatus(G,E,J,w);let Y=await X.getTask(G,w);if(Y){let A=FE.parse({method:"notifications/tasks/status",params:Y});if(await this.notification(A),cw(Y.status))this._cleanupTaskProgressHandler(G)}},listTasks:(G)=>{return X.listTasks(G,w)}}}}function $K($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function wK($,w){let X={...$};for(let G in w){let E=G,J=w[E];if(J===void 0)continue;let W=X[E];if($K(W)&&$K(J))X[E]={...W,...J};else X[E]=J}return X}var Zx=60000;var XK=B(()=>{w8();ZG();eB()});var RE=b((JK)=>{Object.defineProperty(JK,"__esModule",{value:!0});JK.regexpCode=JK.getEsmExportName=JK.getProperty=JK.safeStringify=JK.stringify=JK.strConcat=JK.addCodeArg=JK.str=JK._=JK.nil=JK._Code=JK.Name=JK.IDENTIFIER=JK._CodeOrName=void 0;class T8{}JK._CodeOrName=T8;JK.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class bG extends T8{constructor($){super();if(!JK.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}}}JK.Name=bG;class C1 extends T8{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,X)=>`${w}${X}`,"")}get names(){var $;return($=this._names)!==null&&$!==void 0?$:this._names=this._items.reduce((w,X)=>{if(X instanceof bG)w[X.str]=(w[X.str]||0)+1;return w},{})}}JK._Code=C1;JK.nil=new C1("");function GK($,...w){let X=[$[0]],G=0;while(G<w.length)wA(X,w[G]),X.push($[++G]);return new C1(X)}JK._=GK;var $A=new C1("+");function EK($,...w){let X=[VE($[0])],G=0;while(G<w.length)X.push($A),wA(X,w[G]),X.push($A,VE($[++G]));return bx(X),new C1(X)}JK.str=EK;function wA($,w){if(w instanceof C1)$.push(...w._items);else if(w instanceof bG)$.push(w);else $.push(vx(w))}JK.addCodeArg=wA;function bx($){let w=1;while(w<$.length-1){if($[w]===$A){let X=kx($[w-1],$[w+1]);if(X!==void 0){$.splice(w-1,3,X);continue}$[w++]="+"}w++}}function kx($,w){if(w==='""')return $;if($==='""')return w;if(typeof $=="string"){if(w instanceof bG||$[$.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 bG))return`"${$}${w.slice(1)}`;return}function Cx($,w){return w.emptyStr()?$:$.emptyStr()?w:EK`${$}${w}`}JK.strConcat=Cx;function vx($){return typeof $=="number"||typeof $=="boolean"||$===null?$:VE(Array.isArray($)?$.join(","):$)}function _x($){return new C1(VE($))}JK.stringify=_x;function VE($){return JSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}JK.safeStringify=VE;function fx($){return typeof $=="string"&&JK.IDENTIFIER.test($)?new C1(`.${$}`):GK`[${$}]`}JK.getProperty=fx;function xx($){if(typeof $=="string"&&JK.IDENTIFIER.test($))return new C1(`${$}`);throw Error(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}JK.getEsmExportName=xx;function yx($){return new C1($.toString())}JK.regexpCode=yx});var JA=b((DK)=>{Object.defineProperty(DK,"__esModule",{value:!0});DK.ValueScope=DK.ValueScopeName=DK.Scope=DK.varKinds=DK.UsedValueState=void 0;var r$=RE();class YK extends Error{constructor($){super(`CodeGen: "code" for ${$} not defined`);this.value=$.value}}var j8;(function($){$[$.Started=0]="Started",$[$.Completed=1]="Completed"})(j8||(DK.UsedValueState=j8={}));DK.varKinds={const:new r$.Name("const"),let:new r$.Name("let"),var:new r$.Name("var")};class GA{constructor({prefixes:$,parent:w}={}){this._names={},this._prefixes=$,this._parent=w}toName($){return $ instanceof r$.Name?$:this.name($)}name($){return new r$.Name(this._newName($))}_newName($){let w=this._names[$]||this._nameGroup($);return`${$}${w.index++}`}_nameGroup($){var w,X;if(((X=(w=this._parent)===null||w===void 0?void 0:w._prefixes)===null||X===void 0?void 0:X.has($))||this._prefixes&&!this._prefixes.has($))throw Error(`CodeGen: prefix "${$}" is not allowed in this scope`);return this._names[$]={prefix:$,index:0}}}DK.Scope=GA;class EA extends r$.Name{constructor($,w){super(w);this.prefix=$}setValue($,{property:w,itemIndex:X}){this.value=$,this.scopePath=r$._`.${new r$.Name(w)}[${X}]`}}DK.ValueScopeName=EA;var lx=r$._`\n`;class AK extends GA{constructor($){super($);this._values={},this._scope=$.scope,this.opts={...$,_n:$.lines?lx:r$.nil}}get(){return this._scope}name($){return new EA($,this._newName($))}value($,w){var X;if(w.ref===void 0)throw Error("CodeGen: ref must be passed in value");let G=this.toName($),{prefix:E}=G,J=(X=w.key)!==null&&X!==void 0?X:w.ref,W=this._values[E];if(W){let D=W.get(J);if(D)return D}else W=this._values[E]=new Map;W.set(J,G);let Y=this._scope[E]||(this._scope[E]=[]),A=Y.length;return Y[A]=w.ref,G.setValue(w,{property:E,itemIndex:A}),G}getValue($,w){let X=this._values[$];if(!X)return;return X.get(w)}scopeRefs($,w=this._values){return this._reduceValues(w,(X)=>{if(X.scopePath===void 0)throw Error(`CodeGen: name "${X}" has no value`);return r$._`${$}${X.scopePath}`})}scopeCode($=this._values,w,X){return this._reduceValues($,(G)=>{if(G.value===void 0)throw Error(`CodeGen: name "${G}" has no value`);return G.value.code},w,X)}_reduceValues($,w,X={},G){let E=r$.nil;for(let J in $){let W=$[J];if(!W)continue;let Y=X[J]=X[J]||new Map;W.forEach((A)=>{if(Y.has(A))return;Y.set(A,j8.Started);let D=w(A);if(D){let U=this.opts.es5?DK.varKinds.var:DK.varKinds.const;E=r$._`${E}${U} ${A} = ${D};${this.opts._n}`}else if(D=G===null||G===void 0?void 0:G(A))E=r$._`${E}${D}${this.opts._n}`;else throw new YK(A);Y.set(A,j8.Completed)})}return E}}DK.ValueScope=AK});var W0=b((i$)=>{Object.defineProperty(i$,"__esModule",{value:!0});i$.or=i$.and=i$.not=i$.CodeGen=i$.operators=i$.varKinds=i$.ValueScopeName=i$.ValueScope=i$.Scope=i$.Name=i$.regexpCode=i$.stringify=i$.getProperty=i$.nil=i$.strConcat=i$.str=i$._=void 0;var O0=RE(),v1=JA(),mw=RE();Object.defineProperty(i$,"_",{enumerable:!0,get:function(){return mw._}});Object.defineProperty(i$,"str",{enumerable:!0,get:function(){return mw.str}});Object.defineProperty(i$,"strConcat",{enumerable:!0,get:function(){return mw.strConcat}});Object.defineProperty(i$,"nil",{enumerable:!0,get:function(){return mw.nil}});Object.defineProperty(i$,"getProperty",{enumerable:!0,get:function(){return mw.getProperty}});Object.defineProperty(i$,"stringify",{enumerable:!0,get:function(){return mw.stringify}});Object.defineProperty(i$,"regexpCode",{enumerable:!0,get:function(){return mw.regexpCode}});Object.defineProperty(i$,"Name",{enumerable:!0,get:function(){return mw.Name}});var k8=JA();Object.defineProperty(i$,"Scope",{enumerable:!0,get:function(){return k8.Scope}});Object.defineProperty(i$,"ValueScope",{enumerable:!0,get:function(){return k8.ValueScope}});Object.defineProperty(i$,"ValueScopeName",{enumerable:!0,get:function(){return k8.ValueScopeName}});Object.defineProperty(i$,"varKinds",{enumerable:!0,get:function(){return k8.varKinds}});i$.operators={GT:new O0._Code(">"),GTE:new O0._Code(">="),LT:new O0._Code("<"),LTE:new O0._Code("<="),EQ:new O0._Code("==="),NEQ:new O0._Code("!=="),NOT:new O0._Code("!"),OR:new O0._Code("||"),AND:new O0._Code("&&"),ADD:new O0._Code("+")};class nw{optimizeNodes(){return this}optimizeNames($,w){return this}}class OK extends nw{constructor($,w,X){super();this.varKind=$,this.name=w,this.rhs=X}render({es5:$,_n:w}){let X=$?v1.varKinds.var:this.varKind,G=this.rhs===void 0?"":` = ${this.rhs}`;return`${X} ${this.name}${G};`+w}optimizeNames($,w){if(!$[this.name.str])return;if(this.rhs)this.rhs=CG(this.rhs,$,w);return this}get names(){return this.rhs instanceof O0._CodeOrName?this.rhs.names:{}}}class AA extends nw{constructor($,w,X){super();this.lhs=$,this.rhs=w,this.sideEffects=X}render({_n:$}){return`${this.lhs} = ${this.rhs};`+$}optimizeNames($,w){if(this.lhs instanceof O0.Name&&!$[this.lhs.str]&&!this.sideEffects)return;return this.rhs=CG(this.rhs,$,w),this}get names(){let $=this.lhs instanceof O0.Name?{}:{...this.lhs.names};return b8($,this.rhs)}}class NK extends AA{constructor($,w,X,G){super($,X,G);this.op=w}render({_n:$}){return`${this.lhs} ${this.op}= ${this.rhs};`+$}}class HK extends nw{constructor($){super();this.label=$,this.names={}}render({_n:$}){return`${this.label}:`+$}}class LK extends nw{constructor($){super();this.label=$,this.names={}}render({_n:$}){return`break${this.label?` ${this.label}`:""};`+$}}class FK extends nw{constructor($){super();this.error=$}render({_n:$}){return`throw ${this.error};`+$}get names(){return this.error.names}}class MK extends nw{constructor($){super();this.code=$}render({_n:$}){return`${this.code};`+$}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames($,w){return this.code=CG(this.code,$,w),this}get names(){return this.code instanceof O0._CodeOrName?this.code.names:{}}}class C8 extends nw{constructor($=[]){super();this.nodes=$}render($){return this.nodes.reduce((w,X)=>w+X.render($),"")}optimizeNodes(){let{nodes:$}=this,w=$.length;while(w--){let X=$[w].optimizeNodes();if(Array.isArray(X))$.splice(w,1,...X);else if(X)$[w]=X;else $.splice(w,1)}return $.length>0?this:void 0}optimizeNames($,w){let{nodes:X}=this,G=X.length;while(G--){let E=X[G];if(E.optimizeNames($,w))continue;$y($,E.names),X.splice(G,1)}return X.length>0?this:void 0}get names(){return this.nodes.reduce(($,w)=>QX($,w.names),{})}}class pw extends C8{render($){return"{"+$._n+super.render($)+"}"+$._n}}class zK extends C8{}class TE extends pw{}TE.kind="else";class Fw extends pw{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 X=w.optimizeNodes();w=this.else=Array.isArray(X)?new TE(X):X}if(w){if($===!1)return w instanceof Fw?w:w.nodes;if(this.nodes.length)return this;return new Fw(RK($),w instanceof Fw?[w]:w.nodes)}if($===!1||!this.nodes.length)return;return this}optimizeNames($,w){var X;if(this.else=(X=this.else)===null||X===void 0?void 0:X.optimizeNames($,w),!(super.optimizeNames($,w)||this.else))return;return this.condition=CG(this.condition,$,w),this}get names(){let $=super.names;if(b8($,this.condition),this.else)QX($,this.else.names);return $}}Fw.kind="if";class kG extends pw{}kG.kind="for";class QK extends kG{constructor($){super();this.iteration=$}render($){return`for(${this.iteration})`+super.render($)}optimizeNames($,w){if(!super.optimizeNames($,w))return;return this.iteration=CG(this.iteration,$,w),this}get names(){return QX(super.names,this.iteration.names)}}class BK extends kG{constructor($,w,X,G){super();this.varKind=$,this.name=w,this.from=X,this.to=G}render($){let w=$.es5?v1.varKinds.var:this.varKind,{name:X,from:G,to:E}=this;return`for(${w} ${X}=${G}; ${X}<${E}; ${X}++)`+super.render($)}get names(){let $=b8(super.names,this.from);return b8($,this.to)}}class WA extends kG{constructor($,w,X,G){super();this.loop=$,this.varKind=w,this.name=X,this.iterable=G}render($){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render($)}optimizeNames($,w){if(!super.optimizeNames($,w))return;return this.iterable=CG(this.iterable,$,w),this}get names(){return QX(super.names,this.iterable.names)}}class P8 extends pw{constructor($,w,X){super();this.name=$,this.args=w,this.async=X}render($){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render($)}}P8.kind="func";class q8 extends C8{render($){return"return "+super.render($)}}q8.kind="return";class KK extends pw{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 X,G;return super.optimizeNames($,w),(X=this.catch)===null||X===void 0||X.optimizeNames($,w),(G=this.finally)===null||G===void 0||G.optimizeNames($,w),this}get names(){let $=super.names;if(this.catch)QX($,this.catch.names);if(this.finally)QX($,this.finally.names);return $}}class S8 extends pw{constructor($){super();this.error=$}render($){return`catch(${this.error})`+super.render($)}}S8.kind="catch";class Z8 extends pw{render($){return"finally"+super.render($)}}Z8.kind="finally";class VK{constructor($,w={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...w,_n:w.lines?`
|
|
492
|
-
`:""},this._extScope=$,this._scope=new v1.Scope({parent:$}),this._nodes=[new zK]}toString(){return this._root.render(this.opts)}name($){return this._scope.name($)}scopeName($){return this._extScope.name($)}scopeValue($,w){let X=this._extScope.value($,w);return(this._values[X.prefix]||(this._values[X.prefix]=new Set)).add(X),X}getScopeValue($,w){return this._extScope.getValue($,w)}scopeRefs($){return this._extScope.scopeRefs($,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def($,w,X,G){let E=this._scope.toName(w);if(X!==void 0&&G)this._constants[E.str]=X;return this._leafNode(new OK($,E,X)),E}const($,w,X){return this._def(v1.varKinds.const,$,w,X)}let($,w,X){return this._def(v1.varKinds.let,$,w,X)}var($,w,X){return this._def(v1.varKinds.var,$,w,X)}assign($,w,X){return this._leafNode(new AA($,w,X))}add($,w){return this._leafNode(new NK($,i$.operators.ADD,w))}code($){if(typeof $=="function")$();else if($!==O0.nil)this._leafNode(new MK($));return this}object(...$){let w=["{"];for(let[X,G]of $){if(w.length>1)w.push(",");if(w.push(X),X!==G||this.opts.es5)w.push(":"),(0,O0.addCodeArg)(w,G)}return w.push("}"),new O0._Code(w)}if($,w,X){if(this._blockNode(new Fw($)),w&&X)this.code(w).else().code(X).endIf();else if(w)this.code(w).endIf();else if(X)throw Error('CodeGen: "else" body without "then" body');return this}elseIf($){return this._elseNode(new Fw($))}else(){return this._elseNode(new TE)}endIf(){return this._endBlockNode(Fw,TE)}_for($,w){if(this._blockNode($),w)this.code(w).endFor();return this}for($,w){return this._for(new QK($),w)}forRange($,w,X,G,E=this.opts.es5?v1.varKinds.var:v1.varKinds.let){let J=this._scope.toName($);return this._for(new BK(E,J,w,X),()=>G(J))}forOf($,w,X,G=v1.varKinds.const){let E=this._scope.toName($);if(this.opts.es5){let J=w instanceof O0.Name?w:this.var("_arr",w);return this.forRange("_i",0,O0._`${J}.length`,(W)=>{this.var(E,O0._`${J}[${W}]`),X(E)})}return this._for(new WA("of",G,E,w),()=>X(E))}forIn($,w,X,G=this.opts.es5?v1.varKinds.var:v1.varKinds.const){if(this.opts.ownProperties)return this.forOf($,O0._`Object.keys(${w})`,X);let E=this._scope.toName($);return this._for(new WA("in",G,E,w),()=>X(E))}endFor(){return this._endBlockNode(kG)}label($){return this._leafNode(new HK($))}break($){return this._leafNode(new LK($))}return($){let w=new q8;if(this._blockNode(w),this.code($),w.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(q8)}try($,w,X){if(!w&&!X)throw Error('CodeGen: "try" without "catch" and "finally"');let G=new KK;if(this._blockNode(G),this.code($),w){let E=this.name("e");this._currNode=G.catch=new S8(E),w(E)}if(X)this._currNode=G.finally=new Z8,this.code(X);return this._endBlockNode(S8,Z8)}throw($){return this._leafNode(new FK($))}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 X=this._nodes.length-w;if(X<0||$!==void 0&&X!==$)throw Error(`CodeGen: wrong number of nodes: ${X} vs ${$} expected`);return this._nodes.length=w,this}func($,w=O0.nil,X,G){if(this._blockNode(new P8($,w,X)),G)this.code(G).endFunc();return this}endFunc(){return this._endBlockNode(P8)}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 X=this._currNode;if(X instanceof $||w&&X 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 Fw))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]=$}}i$.CodeGen=VK;function QX($,w){for(let X in w)$[X]=($[X]||0)+(w[X]||0);return $}function b8($,w){return w instanceof O0._CodeOrName?QX($,w.names):$}function CG($,w,X){if($ instanceof O0.Name)return G($);if(!E($))return $;return new O0._Code($._items.reduce((J,W)=>{if(W instanceof O0.Name)W=G(W);if(W instanceof O0._Code)J.push(...W._items);else J.push(W);return J},[]));function G(J){let W=X[J.str];if(W===void 0||w[J.str]!==1)return J;return delete w[J.str],W}function E(J){return J instanceof O0._Code&&J._items.some((W)=>W instanceof O0.Name&&w[W.str]===1&&X[W.str]!==void 0)}}function $y($,w){for(let X in w)$[X]=($[X]||0)-(w[X]||0)}function RK($){return typeof $=="boolean"||typeof $=="number"||$===null?!$:O0._`!${YA($)}`}i$.not=RK;var wy=TK(i$.operators.AND);function Xy(...$){return $.reduce(wy)}i$.and=Xy;var Gy=TK(i$.operators.OR);function Ey(...$){return $.reduce(Gy)}i$.or=Ey;function TK($){return(w,X)=>w===O0.nil?X:X===O0.nil?w:O0._`${YA(w)} ${$} ${YA(X)}`}function YA($){return $ instanceof O0.Name?$:O0._`(${$})`}});var N0=b((CK)=>{Object.defineProperty(CK,"__esModule",{value:!0});CK.checkStrictMode=CK.getErrorPath=CK.Type=CK.useFunc=CK.setEvaluated=CK.evaluatedPropsToName=CK.mergeEvaluated=CK.eachItem=CK.unescapeJsonPointer=CK.escapeJsonPointer=CK.escapeFragment=CK.unescapeFragment=CK.schemaRefOrVal=CK.schemaHasRulesButRef=CK.schemaHasRules=CK.checkUnknownRules=CK.alwaysValidSchema=CK.toHash=void 0;var j0=W0(),Ay=RE();function Dy($){let w={};for(let X of $)w[X]=!0;return w}CK.toHash=Dy;function Uy($,w){if(typeof w=="boolean")return w;if(Object.keys(w).length===0)return!0;return qK($,w),!SK(w,$.self.RULES.all)}CK.alwaysValidSchema=Uy;function qK($,w=$.schema){let{opts:X,self:G}=$;if(!X.strictSchema)return;if(typeof w==="boolean")return;let E=G.RULES.keywords;for(let J in w)if(!E[J])kK($,`unknown keyword: "${J}"`)}CK.checkUnknownRules=qK;function SK($,w){if(typeof $=="boolean")return!$;for(let X in $)if(w[X])return!0;return!1}CK.schemaHasRules=SK;function Oy($,w){if(typeof $=="boolean")return!$;for(let X in $)if(X!=="$ref"&&w.all[X])return!0;return!1}CK.schemaHasRulesButRef=Oy;function Ny({topSchemaRef:$,schemaPath:w},X,G,E){if(!E){if(typeof X=="number"||typeof X=="boolean")return X;if(typeof X=="string")return j0._`${X}`}return j0._`${$}${w}${(0,j0.getProperty)(G)}`}CK.schemaRefOrVal=Ny;function Hy($){return ZK(decodeURIComponent($))}CK.unescapeFragment=Hy;function Ly($){return encodeURIComponent(UA($))}CK.escapeFragment=Ly;function UA($){if(typeof $=="number")return`${$}`;return $.replace(/~/g,"~0").replace(/\//g,"~1")}CK.escapeJsonPointer=UA;function ZK($){return $.replace(/~1/g,"/").replace(/~0/g,"~")}CK.unescapeJsonPointer=ZK;function Fy($,w){if(Array.isArray($))for(let X of $)w(X);else w($)}CK.eachItem=Fy;function jK({mergeNames:$,mergeToName:w,mergeValues:X,resultToName:G}){return(E,J,W,Y)=>{let A=W===void 0?J:W instanceof j0.Name?(J instanceof j0.Name?$(E,J,W):w(E,J,W),W):J instanceof j0.Name?(w(E,W,J),J):X(J,W);return Y===j0.Name&&!(A instanceof j0.Name)?G(E,A):A}}CK.mergeEvaluated={props:jK({mergeNames:($,w,X)=>$.if(j0._`${X} !== true && ${w} !== undefined`,()=>{$.if(j0._`${w} === true`,()=>$.assign(X,!0),()=>$.assign(X,j0._`${X} || {}`).code(j0._`Object.assign(${X}, ${w})`))}),mergeToName:($,w,X)=>$.if(j0._`${X} !== true`,()=>{if(w===!0)$.assign(X,!0);else $.assign(X,j0._`${X} || {}`),OA($,X,w)}),mergeValues:($,w)=>$===!0?!0:{...$,...w},resultToName:bK}),items:jK({mergeNames:($,w,X)=>$.if(j0._`${X} !== true && ${w} !== undefined`,()=>$.assign(X,j0._`${w} === true ? true : ${X} > ${w} ? ${X} : ${w}`)),mergeToName:($,w,X)=>$.if(j0._`${X} !== true`,()=>$.assign(X,w===!0?!0:j0._`${X} > ${w} ? ${X} : ${w}`)),mergeValues:($,w)=>$===!0?!0:Math.max($,w),resultToName:($,w)=>$.var("items",w)})};function bK($,w){if(w===!0)return $.var("props",!0);let X=$.var("props",j0._`{}`);if(w!==void 0)OA($,X,w);return X}CK.evaluatedPropsToName=bK;function OA($,w,X){Object.keys(X).forEach((G)=>$.assign(j0._`${w}${(0,j0.getProperty)(G)}`,!0))}CK.setEvaluated=OA;var PK={};function My($,w){return $.scopeValue("func",{ref:w,code:PK[w.code]||(PK[w.code]=new Ay._Code(w.code))})}CK.useFunc=My;var DA;(function($){$[$.Num=0]="Num",$[$.Str=1]="Str"})(DA||(CK.Type=DA={}));function zy($,w,X){if($ instanceof j0.Name){let G=w===DA.Num;return X?G?j0._`"[" + ${$} + "]"`:j0._`"['" + ${$} + "']"`:G?j0._`"/" + ${$}`:j0._`"/" + ${$}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return X?(0,j0.getProperty)($).toString():"/"+UA($)}CK.getErrorPath=zy;function kK($,w,X=$.opts.strictSchema){if(!X)return;if(w=`strict mode: ${w}`,X===!0)throw Error(w);$.self.logger.warn(w)}CK.checkStrictMode=kK});var Mw=b((_K)=>{Object.defineProperty(_K,"__esModule",{value:!0});var P$=W0(),fy={data:new P$.Name("data"),valCxt:new P$.Name("valCxt"),instancePath:new P$.Name("instancePath"),parentData:new P$.Name("parentData"),parentDataProperty:new P$.Name("parentDataProperty"),rootData:new P$.Name("rootData"),dynamicAnchors:new P$.Name("dynamicAnchors"),vErrors:new P$.Name("vErrors"),errors:new P$.Name("errors"),this:new P$.Name("this"),self:new P$.Name("self"),scope:new P$.Name("scope"),json:new P$.Name("json"),jsonPos:new P$.Name("jsonPos"),jsonLen:new P$.Name("jsonLen"),jsonPart:new P$.Name("jsonPart")};_K.default=fy});var IE=b((gK)=>{Object.defineProperty(gK,"__esModule",{value:!0});gK.extendErrors=gK.resetErrorsCount=gK.reportExtraError=gK.reportError=gK.keyword$DataError=gK.keywordError=void 0;var H0=W0(),_8=N0(),C$=Mw();gK.keywordError={message:({keyword:$})=>H0.str`must pass "${$}" keyword validation`};gK.keyword$DataError={message:({keyword:$,schemaType:w})=>w?H0.str`"${$}" keyword must be ${w} ($data)`:H0.str`"${$}" keyword is invalid ($data)`};function yy($,w=gK.keywordError,X,G){let{it:E}=$,{gen:J,compositeRule:W,allErrors:Y}=E,A=yK($,w,X);if(G!==null&&G!==void 0?G:W||Y)fK(J,A);else xK(E,H0._`[${A}]`)}gK.reportError=yy;function gy($,w=gK.keywordError,X){let{it:G}=$,{gen:E,compositeRule:J,allErrors:W}=G,Y=yK($,w,X);if(fK(E,Y),!(J||W))xK(G,C$.default.vErrors)}gK.reportExtraError=gy;function hy($,w){$.assign(C$.default.errors,w),$.if(H0._`${C$.default.vErrors} !== null`,()=>$.if(w,()=>$.assign(H0._`${C$.default.vErrors}.length`,w),()=>$.assign(C$.default.vErrors,null)))}gK.resetErrorsCount=hy;function uy({gen:$,keyword:w,schemaValue:X,data:G,errsCount:E,it:J}){if(E===void 0)throw Error("ajv implementation error");let W=$.name("err");$.forRange("i",E,C$.default.errors,(Y)=>{if($.const(W,H0._`${C$.default.vErrors}[${Y}]`),$.if(H0._`${W}.instancePath === undefined`,()=>$.assign(H0._`${W}.instancePath`,(0,H0.strConcat)(C$.default.instancePath,J.errorPath))),$.assign(H0._`${W}.schemaPath`,H0.str`${J.errSchemaPath}/${w}`),J.opts.verbose)$.assign(H0._`${W}.schema`,X),$.assign(H0._`${W}.data`,G)})}gK.extendErrors=uy;function fK($,w){let X=$.const("err",w);$.if(H0._`${C$.default.vErrors} === null`,()=>$.assign(C$.default.vErrors,H0._`[${X}]`),H0._`${C$.default.vErrors}.push(${X})`),$.code(H0._`${C$.default.errors}++`)}function xK($,w){let{gen:X,validateName:G,schemaEnv:E}=$;if(E.$async)X.throw(H0._`new ${$.ValidationError}(${w})`);else X.assign(H0._`${G}.errors`,w),X.return(!1)}var BX={keyword:new H0.Name("keyword"),schemaPath:new H0.Name("schemaPath"),params:new H0.Name("params"),propertyName:new H0.Name("propertyName"),message:new H0.Name("message"),schema:new H0.Name("schema"),parentSchema:new H0.Name("parentSchema")};function yK($,w,X){let{createErrors:G}=$.it;if(G===!1)return H0._`{}`;return cy($,w,X)}function cy($,w,X={}){let{gen:G,it:E}=$,J=[my(E,X),ny($,X)];return py($,w,J),G.object(...J)}function my({errorPath:$},{instancePath:w}){let X=w?H0.str`${$}${(0,_8.getErrorPath)(w,_8.Type.Str)}`:$;return[C$.default.instancePath,(0,H0.strConcat)(C$.default.instancePath,X)]}function ny({keyword:$,it:{errSchemaPath:w}},{schemaPath:X,parentSchema:G}){let E=G?w:H0.str`${w}/${$}`;if(X)E=H0.str`${E}${(0,_8.getErrorPath)(X,_8.Type.Str)}`;return[BX.schemaPath,E]}function py($,{params:w,message:X},G){let{keyword:E,data:J,schemaValue:W,it:Y}=$,{opts:A,propertyName:D,topSchemaRef:U,schemaPath:N}=Y;if(G.push([BX.keyword,E],[BX.params,typeof w=="function"?w($):w||H0._`{}`]),A.messages)G.push([BX.message,typeof X=="function"?X($):X]);if(A.verbose)G.push([BX.schema,W],[BX.parentSchema,H0._`${U}${N}`],[C$.default.data,J]);if(D)G.push([BX.propertyName,D])}});var nK=b((cK)=>{Object.defineProperty(cK,"__esModule",{value:!0});cK.boolOrEmptySchema=cK.topBoolOrEmptySchema=void 0;var dy=IE(),ly=W0(),sy=Mw(),ay={message:"boolean schema is false"};function ey($){let{gen:w,schema:X,validateName:G}=$;if(X===!1)uK($,!1);else if(typeof X=="object"&&X.$async===!0)w.return(sy.default.data);else w.assign(ly._`${G}.errors`,null),w.return(!0)}cK.topBoolOrEmptySchema=ey;function $g($,w){let{gen:X,schema:G}=$;if(G===!1)X.var(w,!1),uK($);else X.var(w,!0)}cK.boolOrEmptySchema=$g;function uK($,w){let{gen:X,data:G}=$,E={gen:X,keyword:"false schema",data:G,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:$};(0,dy.reportError)(E,ay,void 0,w)}});var HA=b((pK)=>{Object.defineProperty(pK,"__esModule",{value:!0});pK.getRules=pK.isJSONType=void 0;var Xg=["string","number","integer","boolean","null","object","array"],Gg=new Set(Xg);function Eg($){return typeof $=="string"&&Gg.has($)}pK.isJSONType=Eg;function Jg(){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:{}}}pK.getRules=Jg});var LA=b((tK)=>{Object.defineProperty(tK,"__esModule",{value:!0});tK.shouldUseRule=tK.shouldUseGroup=tK.schemaHasRulesForType=void 0;function Yg({schema:$,self:w},X){let G=w.RULES.types[X];return G&&G!==!0&&iK($,G)}tK.schemaHasRulesForType=Yg;function iK($,w){return w.rules.some((X)=>oK($,X))}tK.shouldUseGroup=iK;function oK($,w){var X;return $[w.keyword]!==void 0||((X=w.definition.implements)===null||X===void 0?void 0:X.some((G)=>$[G]!==void 0))}tK.shouldUseRule=oK});var jE=b((eK)=>{Object.defineProperty(eK,"__esModule",{value:!0});eK.reportTypeError=eK.checkDataTypes=eK.checkDataType=eK.coerceAndCheckDataType=eK.getJSONTypes=eK.getSchemaTypes=eK.DataType=void 0;var Ug=HA(),Og=LA(),Ng=IE(),E0=W0(),lK=N0(),vG;(function($){$[$.Correct=0]="Correct",$[$.Wrong=1]="Wrong"})(vG||(eK.DataType=vG={}));function Hg($){let w=sK($.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}eK.getSchemaTypes=Hg;function sK($){let w=Array.isArray($)?$:$?[$]:[];if(w.every(Ug.isJSONType))return w;throw Error("type must be JSONType or JSONType[]: "+w.join(","))}eK.getJSONTypes=sK;function Lg($,w){let{gen:X,data:G,opts:E}=$,J=Fg(w,E.coerceTypes),W=w.length>0&&!(J.length===0&&w.length===1&&(0,Og.schemaHasRulesForType)($,w[0]));if(W){let Y=MA(w,G,E.strictNumbers,vG.Wrong);X.if(Y,()=>{if(J.length)Mg($,w,J);else zA($)})}return W}eK.coerceAndCheckDataType=Lg;var aK=new Set(["string","number","integer","boolean","null"]);function Fg($,w){return w?$.filter((X)=>aK.has(X)||w==="array"&&X==="array"):[]}function Mg($,w,X){let{gen:G,data:E,opts:J}=$,W=G.let("dataType",E0._`typeof ${E}`),Y=G.let("coerced",E0._`undefined`);if(J.coerceTypes==="array")G.if(E0._`${W} == 'object' && Array.isArray(${E}) && ${E}.length == 1`,()=>G.assign(E,E0._`${E}[0]`).assign(W,E0._`typeof ${E}`).if(MA(w,E,J.strictNumbers),()=>G.assign(Y,E)));G.if(E0._`${Y} !== undefined`);for(let D of X)if(aK.has(D)||D==="array"&&J.coerceTypes==="array")A(D);G.else(),zA($),G.endIf(),G.if(E0._`${Y} !== undefined`,()=>{G.assign(E,Y),zg($,Y)});function A(D){switch(D){case"string":G.elseIf(E0._`${W} == "number" || ${W} == "boolean"`).assign(Y,E0._`"" + ${E}`).elseIf(E0._`${E} === null`).assign(Y,E0._`""`);return;case"number":G.elseIf(E0._`${W} == "boolean" || ${E} === null
|
|
493
|
-
|| (${
|
|
494
|
-
|| (${
|
|
495
|
-
|| ${W} === "boolean" || ${E} === null`).assign(Y,E0._`[${E}]`)}}}function zg({gen:$,parentData:w,parentDataProperty:X},G){$.if(E0._`${w} !== undefined`,()=>$.assign(E0._`${w}[${X}]`,G))}function FA($,w,X,G=vG.Correct){let E=G===vG.Correct?E0.operators.EQ:E0.operators.NEQ,J;switch($){case"null":return E0._`${w} ${E} null`;case"array":J=E0._`Array.isArray(${w})`;break;case"object":J=E0._`${w} && typeof ${w} == "object" && !Array.isArray(${w})`;break;case"integer":J=W(E0._`!(${w} % 1) && !isNaN(${w})`);break;case"number":J=W();break;default:return E0._`typeof ${w} ${E} ${$}`}return G===vG.Correct?J:(0,E0.not)(J);function W(Y=E0.nil){return(0,E0.and)(E0._`typeof ${w} == "number"`,Y,X?E0._`isFinite(${w})`:E0.nil)}}eK.checkDataType=FA;function MA($,w,X,G){if($.length===1)return FA($[0],w,X,G);let E,J=(0,lK.toHash)($);if(J.array&&J.object){let W=E0._`typeof ${w} != "object"`;E=J.null?W:E0._`!${w} || ${W}`,delete J.null,delete J.array,delete J.object}else E=E0.nil;if(J.number)delete J.integer;for(let W in J)E=(0,E0.and)(E,FA(W,w,X,G));return E}eK.checkDataTypes=MA;var Qg={message:({schema:$})=>`must be ${$}`,params:({schema:$,schemaValue:w})=>typeof $=="string"?E0._`{type: ${$}}`:E0._`{type: ${w}}`};function zA($){let w=Bg($);(0,Ng.reportError)(w,Qg)}eK.reportTypeError=zA;function Bg($){let{gen:w,data:X,schema:G}=$,E=(0,lK.schemaRefOrVal)($,G,"type");return{gen:w,keyword:"type",data:X,schema:G.type,schemaCode:E,schemaValue:E,parentSchema:G,params:{},it:$}}});var EV=b((XV)=>{Object.defineProperty(XV,"__esModule",{value:!0});XV.assignDefaults=void 0;var _G=W0(),Pg=N0();function qg($,w){let{properties:X,items:G}=$.schema;if(w==="object"&&X)for(let E in X)wV($,E,X[E].default);else if(w==="array"&&Array.isArray(G))G.forEach((E,J)=>wV($,J,E.default))}XV.assignDefaults=qg;function wV($,w,X){let{gen:G,compositeRule:E,data:J,opts:W}=$;if(X===void 0)return;let Y=_G._`${J}${(0,_G.getProperty)(w)}`;if(E){(0,Pg.checkStrictMode)($,`default is ignored for: ${Y}`);return}let A=_G._`${Y} === undefined`;if(W.useDefaults==="empty")A=_G._`${A} || ${Y} === null || ${Y} === ""`;G.if(A,_G._`${Y} = ${(0,_G.stringify)(X)}`)}});var L1=b((YV)=>{Object.defineProperty(YV,"__esModule",{value:!0});YV.validateUnion=YV.validateArray=YV.usePattern=YV.callValidateCode=YV.schemaProperties=YV.allSchemaProperties=YV.noPropertyInData=YV.propertyInData=YV.isOwnProperty=YV.hasPropFunc=YV.reportMissingProp=YV.checkMissingProp=YV.checkReportMissingProp=void 0;var _0=W0(),QA=N0(),rw=Mw(),Sg=N0();function Zg($,w){let{gen:X,data:G,it:E}=$;X.if(KA(X,G,w,E.opts.ownProperties),()=>{$.setParams({missingProperty:_0._`${w}`},!0),$.error()})}YV.checkReportMissingProp=Zg;function bg({gen:$,data:w,it:{opts:X}},G,E){return(0,_0.or)(...G.map((J)=>(0,_0.and)(KA($,w,J,X.ownProperties),_0._`${E} = ${J}`)))}YV.checkMissingProp=bg;function kg($,w){$.setParams({missingProperty:w},!0),$.error()}YV.reportMissingProp=kg;function JV($){return $.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:_0._`Object.prototype.hasOwnProperty`})}YV.hasPropFunc=JV;function BA($,w,X){return _0._`${JV($)}.call(${w}, ${X})`}YV.isOwnProperty=BA;function Cg($,w,X,G){let E=_0._`${w}${(0,_0.getProperty)(X)} !== undefined`;return G?_0._`${E} && ${BA($,w,X)}`:E}YV.propertyInData=Cg;function KA($,w,X,G){let E=_0._`${w}${(0,_0.getProperty)(X)} === undefined`;return G?(0,_0.or)(E,(0,_0.not)(BA($,w,X))):E}YV.noPropertyInData=KA;function WV($){return $?Object.keys($).filter((w)=>w!=="__proto__"):[]}YV.allSchemaProperties=WV;function vg($,w){return WV(w).filter((X)=>!(0,QA.alwaysValidSchema)($,w[X]))}YV.schemaProperties=vg;function _g({schemaCode:$,data:w,it:{gen:X,topSchemaRef:G,schemaPath:E,errorPath:J},it:W},Y,A,D){let U=D?_0._`${$}, ${w}, ${G}${E}`:w,N=[[rw.default.instancePath,(0,_0.strConcat)(rw.default.instancePath,J)],[rw.default.parentData,W.parentData],[rw.default.parentDataProperty,W.parentDataProperty],[rw.default.rootData,rw.default.rootData]];if(W.opts.dynamicRef)N.push([rw.default.dynamicAnchors,rw.default.dynamicAnchors]);let H=_0._`${U}, ${X.object(...N)}`;return A!==_0.nil?_0._`${Y}.call(${A}, ${H})`:_0._`${Y}(${H})`}YV.callValidateCode=_g;var fg=_0._`new RegExp`;function xg({gen:$,it:{opts:w}},X){let G=w.unicodeRegExp?"u":"",{regExp:E}=w.code,J=E(X,G);return $.scopeValue("pattern",{key:J.toString(),ref:J,code:_0._`${E.code==="new RegExp"?fg:(0,Sg.useFunc)($,E)}(${X}, ${G})`})}YV.usePattern=xg;function yg($){let{gen:w,data:X,keyword:G,it:E}=$,J=w.name("valid");if(E.allErrors){let Y=w.let("valid",!0);return W(()=>w.assign(Y,!1)),Y}return w.var(J,!0),W(()=>w.break()),J;function W(Y){let A=w.const("len",_0._`${X}.length`);w.forRange("i",0,A,(D)=>{$.subschema({keyword:G,dataProp:D,dataPropType:QA.Type.Num},J),w.if((0,_0.not)(J),Y)})}}YV.validateArray=yg;function gg($){let{gen:w,schema:X,keyword:G,it:E}=$;if(!Array.isArray(X))throw Error("ajv implementation error");if(X.some((A)=>(0,QA.alwaysValidSchema)(E,A))&&!E.opts.unevaluated)return;let W=w.let("valid",!1),Y=w.name("_valid");w.block(()=>X.forEach((A,D)=>{let U=$.subschema({keyword:G,schemaProp:D,compositeRule:!0},Y);if(w.assign(W,_0._`${W} || ${Y}`),!$.mergeValidEvaluated(U,Y))w.if((0,_0.not)(W))})),$.result(W,()=>$.reset(),()=>$.error(!0))}YV.validateUnion=gg});var HV=b((OV)=>{Object.defineProperty(OV,"__esModule",{value:!0});OV.validateKeywordUsage=OV.validSchemaType=OV.funcKeywordCode=OV.macroKeywordCode=void 0;var v$=W0(),KX=Mw(),sg=L1(),ag=IE();function eg($,w){let{gen:X,keyword:G,schema:E,parentSchema:J,it:W}=$,Y=w.macro.call(W.self,E,J,W),A=UV(X,G,Y);if(W.opts.validateSchema!==!1)W.self.validateSchema(Y,!0);let D=X.name("valid");$.subschema({schema:Y,schemaPath:v$.nil,errSchemaPath:`${W.errSchemaPath}/${G}`,topSchemaRef:A,compositeRule:!0},D),$.pass(D,()=>$.error(!0))}OV.macroKeywordCode=eg;function $h($,w){var X;let{gen:G,keyword:E,schema:J,parentSchema:W,$data:Y,it:A}=$;Xh(A,w);let D=!Y&&w.compile?w.compile.call(A.self,J,W,A):w.validate,U=UV(G,E,D),N=G.let("valid");$.block$data(N,H),$.ok((X=w.valid)!==null&&X!==void 0?X:N);function H(){if(w.errors===!1){if(M(),w.modifying)DV($);z(()=>$.error())}else{let Q=w.async?L():F();if(w.modifying)DV($);z(()=>wh($,Q))}}function L(){let Q=G.let("ruleErrs",null);return G.try(()=>M(v$._`await `),(R)=>G.assign(N,!1).if(v$._`${R} instanceof ${A.ValidationError}`,()=>G.assign(Q,v$._`${R}.errors`),()=>G.throw(R))),Q}function F(){let Q=v$._`${U}.errors`;return G.assign(Q,null),M(v$.nil),Q}function M(Q=w.async?v$._`await `:v$.nil){let R=A.opts.passContext?KX.default.this:KX.default.self,T=!(("compile"in w)&&!Y||w.schema===!1);G.assign(N,v$._`${Q}${(0,sg.callValidateCode)($,U,R,T)}`,w.modifying)}function z(Q){var R;G.if((0,v$.not)((R=w.valid)!==null&&R!==void 0?R:N),Q)}}OV.funcKeywordCode=$h;function DV($){let{gen:w,data:X,it:G}=$;w.if(G.parentData,()=>w.assign(X,v$._`${G.parentData}[${G.parentDataProperty}]`))}function wh($,w){let{gen:X}=$;X.if(v$._`Array.isArray(${w})`,()=>{X.assign(KX.default.vErrors,v$._`${KX.default.vErrors} === null ? ${w} : ${KX.default.vErrors}.concat(${w})`).assign(KX.default.errors,v$._`${KX.default.vErrors}.length`),(0,ag.extendErrors)($)},()=>$.error())}function Xh({schemaEnv:$},w){if(w.async&&!$.$async)throw Error("async keyword in sync schema")}function UV($,w,X){if(X===void 0)throw Error(`keyword "${w}" failed to compile`);return $.scopeValue("keyword",typeof X=="function"?{ref:X}:{ref:X,code:(0,v$.stringify)(X)})}function Gh($,w,X=!1){return!w.length||w.some((G)=>G==="array"?Array.isArray($):G==="object"?$&&typeof $=="object"&&!Array.isArray($):typeof $==G||X&&typeof $>"u")}OV.validSchemaType=Gh;function Eh({schema:$,opts:w,self:X,errSchemaPath:G},E,J){if(Array.isArray(E.keyword)?!E.keyword.includes(J):E.keyword!==J)throw Error("ajv implementation error");let W=E.dependencies;if(W===null||W===void 0?void 0:W.some((Y)=>!Object.prototype.hasOwnProperty.call($,Y)))throw Error(`parent schema must have dependencies of ${J}: ${W.join(",")}`);if(E.validateSchema){if(!E.validateSchema($[J])){let A=`keyword "${J}" value is invalid at path "${G}": `+X.errorsText(E.validateSchema.errors);if(w.validateSchema==="log")X.logger.error(A);else throw Error(A)}}}OV.validateKeywordUsage=Eh});var zV=b((FV)=>{Object.defineProperty(FV,"__esModule",{value:!0});FV.extendSubschemaMode=FV.extendSubschemaData=FV.getSubschema=void 0;var l1=W0(),LV=N0();function Ah($,{keyword:w,schemaProp:X,schema:G,schemaPath:E,errSchemaPath:J,topSchemaRef:W}){if(w!==void 0&&G!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(w!==void 0){let Y=$.schema[w];return X===void 0?{schema:Y,schemaPath:l1._`${$.schemaPath}${(0,l1.getProperty)(w)}`,errSchemaPath:`${$.errSchemaPath}/${w}`}:{schema:Y[X],schemaPath:l1._`${$.schemaPath}${(0,l1.getProperty)(w)}${(0,l1.getProperty)(X)}`,errSchemaPath:`${$.errSchemaPath}/${w}/${(0,LV.escapeFragment)(X)}`}}if(G!==void 0){if(E===void 0||J===void 0||W===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:G,schemaPath:E,topSchemaRef:W,errSchemaPath:J}}throw Error('either "keyword" or "schema" must be passed')}FV.getSubschema=Ah;function Dh($,w,{dataProp:X,dataPropType:G,data:E,dataTypes:J,propertyName:W}){if(E!==void 0&&X!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:Y}=w;if(X!==void 0){let{errorPath:D,dataPathArr:U,opts:N}=w,H=Y.let("data",l1._`${w.data}${(0,l1.getProperty)(X)}`,!0);A(H),$.errorPath=l1.str`${D}${(0,LV.getErrorPath)(X,G,N.jsPropertySyntax)}`,$.parentDataProperty=l1._`${X}`,$.dataPathArr=[...U,$.parentDataProperty]}if(E!==void 0){let D=E instanceof l1.Name?E:Y.let("data",E,!0);if(A(D),W!==void 0)$.propertyName=W}if(J)$.dataTypes=J;function A(D){$.data=D,$.dataLevel=w.dataLevel+1,$.dataTypes=[],w.definedProperties=new Set,$.parentData=w.data,$.dataNames=[...w.dataNames,D]}}FV.extendSubschemaData=Dh;function Uh($,{jtdDiscriminator:w,jtdMetadata:X,compositeRule:G,createErrors:E,allErrors:J}){if(G!==void 0)$.compositeRule=G;if(E!==void 0)$.createErrors=E;if(J!==void 0)$.allErrors=J;$.jtdDiscriminator=w,$.jtdMetadata=X}FV.extendSubschemaMode=Uh});var VA=b((l80,QV)=>{QV.exports=function $(w,X){if(w===X)return!0;if(w&&X&&typeof w=="object"&&typeof X=="object"){if(w.constructor!==X.constructor)return!1;var G,E,J;if(Array.isArray(w)){if(G=w.length,G!=X.length)return!1;for(E=G;E--!==0;)if(!$(w[E],X[E]))return!1;return!0}if(w.constructor===RegExp)return w.source===X.source&&w.flags===X.flags;if(w.valueOf!==Object.prototype.valueOf)return w.valueOf()===X.valueOf();if(w.toString!==Object.prototype.toString)return w.toString()===X.toString();if(J=Object.keys(w),G=J.length,G!==Object.keys(X).length)return!1;for(E=G;E--!==0;)if(!Object.prototype.hasOwnProperty.call(X,J[E]))return!1;for(E=G;E--!==0;){var W=J[E];if(!$(w[W],X[W]))return!1}return!0}return w!==w&&X!==X}});var KV=b((s80,BV)=>{var iw=BV.exports=function($,w,X){if(typeof w=="function")X=w,w={};X=w.cb||X;var G=typeof X=="function"?X:X.pre||function(){},E=X.post||function(){};f8(w,G,E,$,"",$)};iw.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};iw.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};iw.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};iw.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 f8($,w,X,G,E,J,W,Y,A,D){if(G&&typeof G=="object"&&!Array.isArray(G)){w(G,E,J,W,Y,A,D);for(var U in G){var N=G[U];if(Array.isArray(N)){if(U in iw.arrayKeywords)for(var H=0;H<N.length;H++)f8($,w,X,N[H],E+"/"+U+"/"+H,J,E,U,G,H)}else if(U in iw.propsKeywords){if(N&&typeof N=="object")for(var L in N)f8($,w,X,N[L],E+"/"+U+"/"+Hh(L),J,E,U,G,L)}else if(U in iw.keywords||$.allKeys&&!(U in iw.skipKeywords))f8($,w,X,N,E+"/"+U,J,E,U,G)}X(G,E,J,W,Y,A,D)}}function Hh($){return $.replace(/~/g,"~0").replace(/\//g,"~1")}});var PE=b((IV)=>{Object.defineProperty(IV,"__esModule",{value:!0});IV.getSchemaRefs=IV.resolveUrl=IV.normalizeId=IV._getFullPath=IV.getFullPath=IV.inlineRef=void 0;var Lh=N0(),Fh=VA(),Mh=KV(),zh=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Qh($,w=!0){if(typeof $=="boolean")return!0;if(w===!0)return!RA($);if(!w)return!1;return VV($)<=w}IV.inlineRef=Qh;var Bh=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function RA($){for(let w in $){if(Bh.has(w))return!0;let X=$[w];if(Array.isArray(X)&&X.some(RA))return!0;if(typeof X=="object"&&RA(X))return!0}return!1}function VV($){let w=0;for(let X in $){if(X==="$ref")return 1/0;if(w++,zh.has(X))continue;if(typeof $[X]=="object")(0,Lh.eachItem)($[X],(G)=>w+=VV(G));if(w===1/0)return 1/0}return w}function RV($,w="",X){if(X!==!1)w=fG(w);let G=$.parse(w);return TV($,G)}IV.getFullPath=RV;function TV($,w){return $.serialize(w).split("#")[0]+"#"}IV._getFullPath=TV;var Kh=/#\/?$/;function fG($){return $?$.replace(Kh,""):""}IV.normalizeId=fG;function Vh($,w,X){return X=fG(X),$.resolve(w,X)}IV.resolveUrl=Vh;var Rh=/^[a-z_][-a-z0-9._]*$/i;function Th($,w){if(typeof $=="boolean")return{};let{schemaId:X,uriResolver:G}=this.opts,E=fG($[X]||w),J={"":E},W=RV(G,E,!1),Y={},A=new Set;return Mh($,{allKeys:!0},(N,H,L,F)=>{if(F===void 0)return;let M=W+H,z=J[F];if(typeof N[X]=="string")z=Q.call(this,N[X]);R.call(this,N.$anchor),R.call(this,N.$dynamicAnchor),J[H]=z;function Q(T){let v=this.opts.uriResolver.resolve;if(T=fG(z?v(z,T):T),A.has(T))throw U(T);A.add(T);let f=this.refs[T];if(typeof f=="string")f=this.refs[f];if(typeof f=="object")D(N,f.schema,T);else if(T!==fG(M))if(T[0]==="#")D(N,Y[T],T),Y[T]=N;else this.refs[T]=M;return T}function R(T){if(typeof T=="string"){if(!Rh.test(T))throw Error(`invalid anchor "${T}"`);Q.call(this,`#${T}`)}}}),Y;function D(N,H,L){if(H!==void 0&&!Fh(N,H))throw U(L)}function U(N){return Error(`reference "${N}" resolves to more than one schema`)}}IV.getSchemaRefs=Th});var ZE=b((uV)=>{Object.defineProperty(uV,"__esModule",{value:!0});uV.getData=uV.KeywordCxt=uV.validateFunctionCode=void 0;var bV=nK(),PV=jE(),IA=LA(),x8=jE(),Zh=EV(),SE=HV(),TA=zV(),p=W0(),s=Mw(),bh=PE(),zw=N0(),qE=IE();function kh($){if(vV($)){if(_V($),CV($)){_h($);return}}kV($,()=>(0,bV.topBoolOrEmptySchema)($))}uV.validateFunctionCode=kh;function kV({gen:$,validateName:w,schema:X,schemaEnv:G,opts:E},J){if(E.code.es5)$.func(w,p._`${s.default.data}, ${s.default.valCxt}`,G.$async,()=>{$.code(p._`"use strict"; ${qV(X,E)}`),vh($,E),$.code(J)});else $.func(w,p._`${s.default.data}, ${Ch(E)}`,G.$async,()=>$.code(qV(X,E)).code(J))}function Ch($){return p._`{${s.default.instancePath}="", ${s.default.parentData}, ${s.default.parentDataProperty}, ${s.default.rootData}=${s.default.data}${$.dynamicRef?p._`, ${s.default.dynamicAnchors}={}`:p.nil}}={}`}function vh($,w){$.if(s.default.valCxt,()=>{if($.var(s.default.instancePath,p._`${s.default.valCxt}.${s.default.instancePath}`),$.var(s.default.parentData,p._`${s.default.valCxt}.${s.default.parentData}`),$.var(s.default.parentDataProperty,p._`${s.default.valCxt}.${s.default.parentDataProperty}`),$.var(s.default.rootData,p._`${s.default.valCxt}.${s.default.rootData}`),w.dynamicRef)$.var(s.default.dynamicAnchors,p._`${s.default.valCxt}.${s.default.dynamicAnchors}`)},()=>{if($.var(s.default.instancePath,p._`""`),$.var(s.default.parentData,p._`undefined`),$.var(s.default.parentDataProperty,p._`undefined`),$.var(s.default.rootData,s.default.data),w.dynamicRef)$.var(s.default.dynamicAnchors,p._`{}`)})}function _h($){let{schema:w,opts:X,gen:G}=$;kV($,()=>{if(X.$comment&&w.$comment)xV($);if(hh($),G.let(s.default.vErrors,null),G.let(s.default.errors,0),X.unevaluated)fh($);fV($),mh($)});return}function fh($){let{gen:w,validateName:X}=$;$.evaluated=w.const("evaluated",p._`${X}.evaluated`),w.if(p._`${$.evaluated}.dynamicProps`,()=>w.assign(p._`${$.evaluated}.props`,p._`undefined`)),w.if(p._`${$.evaluated}.dynamicItems`,()=>w.assign(p._`${$.evaluated}.items`,p._`undefined`))}function qV($,w){let X=typeof $=="object"&&$[w.schemaId];return X&&(w.code.source||w.code.process)?p._`/*# sourceURL=${X} */`:p.nil}function xh($,w){if(vV($)){if(_V($),CV($)){yh($,w);return}}(0,bV.boolOrEmptySchema)($,w)}function CV({schema:$,self:w}){if(typeof $=="boolean")return!$;for(let X in $)if(w.RULES.all[X])return!0;return!1}function vV($){return typeof $.schema!="boolean"}function yh($,w){let{schema:X,gen:G,opts:E}=$;if(E.$comment&&X.$comment)xV($);uh($),ch($);let J=G.const("_errs",s.default.errors);fV($,J),G.var(w,p._`${J} === ${s.default.errors}`)}function _V($){(0,zw.checkUnknownRules)($),gh($)}function fV($,w){if($.opts.jtd)return SV($,[],!1,w);let X=(0,PV.getSchemaTypes)($.schema),G=(0,PV.coerceAndCheckDataType)($,X);SV($,X,!G,w)}function gh($){let{schema:w,errSchemaPath:X,opts:G,self:E}=$;if(w.$ref&&G.ignoreKeywordsWithRef&&(0,zw.schemaHasRulesButRef)(w,E.RULES))E.logger.warn(`$ref: keywords ignored in schema at path "${X}"`)}function hh($){let{schema:w,opts:X}=$;if(w.default!==void 0&&X.useDefaults&&X.strictSchema)(0,zw.checkStrictMode)($,"default is ignored in the schema root")}function uh($){let w=$.schema[$.opts.schemaId];if(w)$.baseId=(0,bh.resolveUrl)($.opts.uriResolver,$.baseId,w)}function ch($){if($.schema.$async&&!$.schemaEnv.$async)throw Error("async schema in sync schema")}function xV({gen:$,schemaEnv:w,schema:X,errSchemaPath:G,opts:E}){let J=X.$comment;if(E.$comment===!0)$.code(p._`${s.default.self}.logger.log(${J})`);else if(typeof E.$comment=="function"){let W=p.str`${G}/$comment`,Y=$.scopeValue("root",{ref:w.root});$.code(p._`${s.default.self}.opts.$comment(${J}, ${W}, ${Y}.schema)`)}}function mh($){let{gen:w,schemaEnv:X,validateName:G,ValidationError:E,opts:J}=$;if(X.$async)w.if(p._`${s.default.errors} === 0`,()=>w.return(s.default.data),()=>w.throw(p._`new ${E}(${s.default.vErrors})`));else{if(w.assign(p._`${G}.errors`,s.default.vErrors),J.unevaluated)nh($);w.return(p._`${s.default.errors} === 0`)}}function nh({gen:$,evaluated:w,props:X,items:G}){if(X instanceof p.Name)$.assign(p._`${w}.props`,X);if(G instanceof p.Name)$.assign(p._`${w}.items`,G)}function SV($,w,X,G){let{gen:E,schema:J,data:W,allErrors:Y,opts:A,self:D}=$,{RULES:U}=D;if(J.$ref&&(A.ignoreKeywordsWithRef||!(0,zw.schemaHasRulesButRef)(J,U))){E.block(()=>gV($,"$ref",U.all.$ref.definition));return}if(!A.jtd)ph($,w);E.block(()=>{for(let H of U.rules)N(H);N(U.post)});function N(H){if(!(0,IA.shouldUseGroup)(J,H))return;if(H.type){if(E.if((0,x8.checkDataType)(H.type,W,A.strictNumbers)),ZV($,H),w.length===1&&w[0]===H.type&&X)E.else(),(0,x8.reportTypeError)($);E.endIf()}else ZV($,H);if(!Y)E.if(p._`${s.default.errors} === ${G||0}`)}}function ZV($,w){let{gen:X,schema:G,opts:{useDefaults:E}}=$;if(E)(0,Zh.assignDefaults)($,w.type);X.block(()=>{for(let J of w.rules)if((0,IA.shouldUseRule)(G,J))gV($,J.keyword,J.definition,w.type)})}function ph($,w){if($.schemaEnv.meta||!$.opts.strictTypes)return;if(rh($,w),!$.opts.allowUnionTypes)ih($,w);oh($,$.dataTypes)}function rh($,w){if(!w.length)return;if(!$.dataTypes.length){$.dataTypes=w;return}w.forEach((X)=>{if(!yV($.dataTypes,X))jA($,`type "${X}" not allowed by context "${$.dataTypes.join(",")}"`)}),dh($,w)}function ih($,w){if(w.length>1&&!(w.length===2&&w.includes("null")))jA($,"use allowUnionTypes to allow union type keyword")}function oh($,w){let X=$.self.RULES.all;for(let G in X){let E=X[G];if(typeof E=="object"&&(0,IA.shouldUseRule)($.schema,E)){let{type:J}=E.definition;if(J.length&&!J.some((W)=>th(w,W)))jA($,`missing type "${J.join(",")}" for keyword "${G}"`)}}}function th($,w){return $.includes(w)||w==="number"&&$.includes("integer")}function yV($,w){return $.includes(w)||w==="integer"&&$.includes("number")}function dh($,w){let X=[];for(let G of $.dataTypes)if(yV(w,G))X.push(G);else if(w.includes("integer")&&G==="number")X.push("integer");$.dataTypes=X}function jA($,w){let X=$.schemaEnv.baseId+$.errSchemaPath;w+=` at "${X}" (strictTypes)`,(0,zw.checkStrictMode)($,w,$.opts.strictTypes)}class PA{constructor($,w,X){if((0,SE.validateKeywordUsage)($,w,X),this.gen=$.gen,this.allErrors=$.allErrors,this.keyword=X,this.data=$.data,this.schema=$.schema[X],this.$data=w.$data&&$.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,zw.schemaRefOrVal)($,this.schema,X,this.$data),this.schemaType=w.schemaType,this.parentSchema=$.schema,this.params={},this.it=$,this.def=w,this.$data)this.schemaCode=$.gen.const("vSchema",hV(this.$data,$));else if(this.schemaCode=this.schemaValue,!(0,SE.validSchemaType)(this.schema,w.schemaType,w.allowUndefined))throw Error(`${X} value must be ${JSON.stringify(w.schemaType)}`);if("code"in w?w.trackErrors:w.errors!==!1)this.errsCount=$.gen.const("_errs",s.default.errors)}result($,w,X){this.failResult((0,p.not)($),w,X)}failResult($,w,X){if(this.gen.if($),X)X();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,p.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(p._`${w} !== undefined && (${(0,p.or)(this.invalid$data(),$)})`)}error($,w,X){if(w){this.setParams(w),this._error($,X),this.setParams({});return}this._error($,X)}_error($,w){($?qE.reportExtraError:qE.reportError)(this,this.def.error,w)}$dataError(){(0,qE.reportError)(this,this.def.$dataError||qE.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,qE.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,X=p.nil){this.gen.block(()=>{this.check$data($,X),w()})}check$data($=p.nil,w=p.nil){if(!this.$data)return;let{gen:X,schemaCode:G,schemaType:E,def:J}=this;if(X.if((0,p.or)(p._`${G} === undefined`,w)),$!==p.nil)X.assign($,!0);if(E.length||J.validateSchema){if(X.elseIf(this.invalid$data()),this.$dataError(),$!==p.nil)X.assign($,!1)}X.else()}invalid$data(){let{gen:$,schemaCode:w,schemaType:X,def:G,it:E}=this;return(0,p.or)(J(),W());function J(){if(X.length){if(!(w instanceof p.Name))throw Error("ajv implementation error");let Y=Array.isArray(X)?X:[X];return p._`${(0,x8.checkDataTypes)(Y,w,E.opts.strictNumbers,x8.DataType.Wrong)}`}return p.nil}function W(){if(G.validateSchema){let Y=$.scopeValue("validate$data",{ref:G.validateSchema});return p._`!${Y}(${w})`}return p.nil}}subschema($,w){let X=(0,TA.getSubschema)(this.it,$);(0,TA.extendSubschemaData)(X,this.it,$),(0,TA.extendSubschemaMode)(X,$);let G={...this.it,...X,items:void 0,props:void 0};return xh(G,w),G}mergeEvaluated($,w){let{it:X,gen:G}=this;if(!X.opts.unevaluated)return;if(X.props!==!0&&$.props!==void 0)X.props=zw.mergeEvaluated.props(G,$.props,X.props,w);if(X.items!==!0&&$.items!==void 0)X.items=zw.mergeEvaluated.items(G,$.items,X.items,w)}mergeValidEvaluated($,w){let{it:X,gen:G}=this;if(X.opts.unevaluated&&(X.props!==!0||X.items!==!0))return G.if(w,()=>this.mergeEvaluated($,p.Name)),!0}}uV.KeywordCxt=PA;function gV($,w,X,G){let E=new PA($,X,w);if("code"in X)X.code(E,G);else if(E.$data&&X.validate)(0,SE.funcKeywordCode)(E,X);else if("macro"in X)(0,SE.macroKeywordCode)(E,X);else if(X.compile||X.validate)(0,SE.funcKeywordCode)(E,X)}var lh=/^\/(?:[^~]|~0|~1)*$/,sh=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function hV($,{dataLevel:w,dataNames:X,dataPathArr:G}){let E,J;if($==="")return s.default.rootData;if($[0]==="/"){if(!lh.test($))throw Error(`Invalid JSON-pointer: ${$}`);E=$,J=s.default.rootData}else{let D=sh.exec($);if(!D)throw Error(`Invalid JSON-pointer: ${$}`);let U=+D[1];if(E=D[2],E==="#"){if(U>=w)throw Error(A("property/index",U));return G[w-U]}if(U>w)throw Error(A("data",U));if(J=X[w-U],!E)return J}let W=J,Y=E.split("/");for(let D of Y)if(D)J=p._`${J}${(0,p.getProperty)((0,zw.unescapeJsonPointer)(D))}`,W=p._`${W} && ${J}`;return W;function A(D,U){return`Cannot access ${D} ${U} levels up, current level is ${w}`}}uV.getData=hV});var y8=b((nV)=>{Object.defineProperty(nV,"__esModule",{value:!0});class mV extends Error{constructor($){super("validation failed");this.errors=$,this.ajv=this.validation=!0}}nV.default=mV});var bE=b((rV)=>{Object.defineProperty(rV,"__esModule",{value:!0});var qA=PE();class pV extends Error{constructor($,w,X,G){super(G||`can't resolve reference ${X} from id ${w}`);this.missingRef=(0,qA.resolveUrl)($,w,X),this.missingSchema=(0,qA.normalizeId)((0,qA.getFullPath)($,this.missingRef))}}rV.default=pV});var h8=b((tV)=>{Object.defineProperty(tV,"__esModule",{value:!0});tV.resolveSchema=tV.getCompilingSchema=tV.resolveRef=tV.compileSchema=tV.SchemaEnv=void 0;var _1=W0(),Xu=y8(),VX=Mw(),f1=PE(),iV=N0(),Gu=ZE();class kE{constructor($){var w;this.refs={},this.dynamicAnchors={};let X;if(typeof $.schema=="object")X=$.schema;this.schema=$.schema,this.schemaId=$.schemaId,this.root=$.root||this,this.baseId=(w=$.baseId)!==null&&w!==void 0?w:(0,f1.normalizeId)(X===null||X===void 0?void 0:X[$.schemaId||"$id"]),this.schemaPath=$.schemaPath,this.localRefs=$.localRefs,this.meta=$.meta,this.$async=X===null||X===void 0?void 0:X.$async,this.refs={}}}tV.SchemaEnv=kE;function ZA($){let w=oV.call(this,$);if(w)return w;let X=(0,f1.getFullPath)(this.opts.uriResolver,$.root.baseId),{es5:G,lines:E}=this.opts.code,{ownProperties:J}=this.opts,W=new _1.CodeGen(this.scope,{es5:G,lines:E,ownProperties:J}),Y;if($.$async)Y=W.scopeValue("Error",{ref:Xu.default,code:_1._`require("ajv/dist/runtime/validation_error").default`});let A=W.scopeName("validate");$.validateName=A;let D={gen:W,allErrors:this.opts.allErrors,data:VX.default.data,parentData:VX.default.parentData,parentDataProperty:VX.default.parentDataProperty,dataNames:[VX.default.data],dataPathArr:[_1.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:W.scopeValue("schema",this.opts.code.source===!0?{ref:$.schema,code:(0,_1.stringify)($.schema)}:{ref:$.schema}),validateName:A,ValidationError:Y,schema:$.schema,schemaEnv:$,rootId:X,baseId:$.baseId||X,schemaPath:_1.nil,errSchemaPath:$.schemaPath||(this.opts.jtd?"":"#"),errorPath:_1._`""`,opts:this.opts,self:this},U;try{this._compilations.add($),(0,Gu.validateFunctionCode)(D),W.optimize(this.opts.code.optimize);let N=W.toString();if(U=`${W.scopeRefs(VX.default.scope)}return ${N}`,this.opts.code.process)U=this.opts.code.process(U,$);let L=Function(`${VX.default.self}`,`${VX.default.scope}`,U)(this,this.scope.get());if(this.scope.value(A,{ref:L}),L.errors=null,L.schema=$.schema,L.schemaEnv=$,$.$async)L.$async=!0;if(this.opts.code.source===!0)L.source={validateName:A,validateCode:N,scopeValues:W._values};if(this.opts.unevaluated){let{props:F,items:M}=D;if(L.evaluated={props:F instanceof _1.Name?void 0:F,items:M instanceof _1.Name?void 0:M,dynamicProps:F instanceof _1.Name,dynamicItems:M instanceof _1.Name},L.source)L.source.evaluated=(0,_1.stringify)(L.evaluated)}return $.validate=L,$}catch(N){if(delete $.validate,delete $.validateName,U)this.logger.error("Error compiling schema, function code:",U);throw N}finally{this._compilations.delete($)}}tV.compileSchema=ZA;function Eu($,w,X){var G;X=(0,f1.resolveUrl)(this.opts.uriResolver,w,X);let E=$.refs[X];if(E)return E;let J=Yu.call(this,$,X);if(J===void 0){let W=(G=$.localRefs)===null||G===void 0?void 0:G[X],{schemaId:Y}=this.opts;if(W)J=new kE({schema:W,schemaId:Y,root:$,baseId:w})}if(J===void 0)return;return $.refs[X]=Ju.call(this,J)}tV.resolveRef=Eu;function Ju($){if((0,f1.inlineRef)($.schema,this.opts.inlineRefs))return $.schema;return $.validate?$:ZA.call(this,$)}function oV($){for(let w of this._compilations)if(Wu(w,$))return w}tV.getCompilingSchema=oV;function Wu($,w){return $.schema===w.schema&&$.root===w.root&&$.baseId===w.baseId}function Yu($,w){let X;while(typeof(X=this.refs[w])=="string")w=X;return X||this.schemas[w]||g8.call(this,$,w)}function g8($,w){let X=this.opts.uriResolver.parse(w),G=(0,f1._getFullPath)(this.opts.uriResolver,X),E=(0,f1.getFullPath)(this.opts.uriResolver,$.baseId,void 0);if(Object.keys($.schema).length>0&&G===E)return SA.call(this,X,$);let J=(0,f1.normalizeId)(G),W=this.refs[J]||this.schemas[J];if(typeof W=="string"){let Y=g8.call(this,$,W);if(typeof(Y===null||Y===void 0?void 0:Y.schema)!=="object")return;return SA.call(this,X,Y)}if(typeof(W===null||W===void 0?void 0:W.schema)!=="object")return;if(!W.validate)ZA.call(this,W);if(J===(0,f1.normalizeId)(w)){let{schema:Y}=W,{schemaId:A}=this.opts,D=Y[A];if(D)E=(0,f1.resolveUrl)(this.opts.uriResolver,E,D);return new kE({schema:Y,schemaId:A,root:$,baseId:E})}return SA.call(this,X,W)}tV.resolveSchema=g8;var Au=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function SA($,{baseId:w,schema:X,root:G}){var E;if(((E=$.fragment)===null||E===void 0?void 0:E[0])!=="/")return;for(let Y of $.fragment.slice(1).split("/")){if(typeof X==="boolean")return;let A=X[(0,iV.unescapeFragment)(Y)];if(A===void 0)return;X=A;let D=typeof X==="object"&&X[this.opts.schemaId];if(!Au.has(Y)&&D)w=(0,f1.resolveUrl)(this.opts.uriResolver,w,D)}let J;if(typeof X!="boolean"&&X.$ref&&!(0,iV.schemaHasRulesButRef)(X,this.RULES)){let Y=(0,f1.resolveUrl)(this.opts.uriResolver,w,X.$ref);J=g8.call(this,G,Y)}let{schemaId:W}=this.opts;if(J=J||new kE({schema:X,schemaId:W,root:G,baseId:w}),J.schema!==J.root.schema)return J;return}});var lV=b((G50,Hu)=>{Hu.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 kA=b((E50,$R)=>{var Lu=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),aV=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 bA($){let w="",X=0,G=0;for(G=0;G<$.length;G++){if(X=$[G].charCodeAt(0),X===48)continue;if(!(X>=48&&X<=57||X>=65&&X<=70||X>=97&&X<=102))return"";w+=$[G];break}for(G+=1;G<$.length;G++){if(X=$[G].charCodeAt(0),!(X>=48&&X<=57||X>=65&&X<=70||X>=97&&X<=102))return"";w+=$[G]}return w}var Fu=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function sV($){return $.length=0,!0}function Mu($,w,X){if($.length){let G=bA($);if(G!=="")w.push(G);else return X.error=!0,!1;$.length=0}return!0}function zu($){let w=0,X={error:!1,address:"",zone:""},G=[],E=[],J=!1,W=!1,Y=Mu;for(let A=0;A<$.length;A++){let D=$[A];if(D==="["||D==="]")continue;if(D===":"){if(J===!0)W=!0;if(!Y(E,G,X))break;if(++w>7){X.error=!0;break}if(A>0&&$[A-1]===":")J=!0;G.push(":");continue}else if(D==="%"){if(!Y(E,G,X))break;Y=sV}else{E.push(D);continue}}if(E.length)if(Y===sV)X.zone=E.join("");else if(W)G.push(E.join(""));else G.push(bA(E));return X.address=G.join(""),X}function eV($){if(Qu($,":")<2)return{host:$,isIPV6:!1};let w=zu($);if(!w.error){let{address:X,address:G}=w;if(w.zone)X+="%"+w.zone,G+="%25"+w.zone;return{host:X,isIPV6:!0,escapedHost:G}}else return{host:$,isIPV6:!1}}function Qu($,w){let X=0;for(let G=0;G<$.length;G++)if($[G]===w)X++;return X}function Bu($){let w=$,X=[],G=-1,E=0;while(E=w.length){if(E===1)if(w===".")break;else if(w==="/"){X.push("/");break}else{X.push(w);break}else if(E===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]==="/"){X.push("/");break}}}else if(E===3){if(w==="/.."){if(X.length!==0)X.pop();X.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),X.length!==0)X.pop();continue}}}}if((G=w.indexOf("/",1))===-1){X.push(w);break}else X.push(w.slice(0,G)),w=w.slice(G)}return X.join("")}function Ku($,w){let X=w!==!0?escape:unescape;if($.scheme!==void 0)$.scheme=X($.scheme);if($.userinfo!==void 0)$.userinfo=X($.userinfo);if($.host!==void 0)$.host=X($.host);if($.path!==void 0)$.path=X($.path);if($.query!==void 0)$.query=X($.query);if($.fragment!==void 0)$.fragment=X($.fragment);return $}function Vu($){let w=[];if($.userinfo!==void 0)w.push($.userinfo),w.push("@");if($.host!==void 0){let X=unescape($.host);if(!aV(X)){let G=eV(X);if(G.isIPV6===!0)X=`[${G.escapedHost}]`;else X=$.host}w.push(X)}if(typeof $.port==="number"||typeof $.port==="string")w.push(":"),w.push(String($.port));return w.length?w.join(""):void 0}$R.exports={nonSimpleDomain:Fu,recomposeAuthority:Vu,normalizeComponentEncoding:Ku,removeDotSegments:Bu,isIPv4:aV,isUUID:Lu,normalizeIPv6:eV,stringArrayToHexStripped:bA}});var JR=b((J50,ER)=>{var{isUUID:Ru}=kA(),Tu=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Iu=["http","https","ws","wss","urn","urn:uuid"];function ju($){return Iu.indexOf($)!==-1}function CA($){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 wR($){if(!$.host)$.error=$.error||"HTTP URIs must have a host.";return $}function XR($){let w=String($.scheme).toLowerCase()==="https";if($.port===(w?443:80)||$.port==="")$.port=void 0;if(!$.path)$.path="/";return $}function Pu($){return $.secure=CA($),$.resourceName=($.path||"/")+($.query?"?"+$.query:""),$.path=void 0,$.query=void 0,$}function qu($){if($.port===(CA($)?443:80)||$.port==="")$.port=void 0;if(typeof $.secure==="boolean")$.scheme=$.secure?"wss":"ws",$.secure=void 0;if($.resourceName){let[w,X]=$.resourceName.split("?");$.path=w&&w!=="/"?w:void 0,$.query=X,$.resourceName=void 0}return $.fragment=void 0,$}function Su($,w){if(!$.path)return $.error="URN can not be parsed",$;let X=$.path.match(Tu);if(X){let G=w.scheme||$.scheme||"urn";$.nid=X[1].toLowerCase(),$.nss=X[2];let E=`${G}:${w.nid||$.nid}`,J=vA(E);if($.path=void 0,J)$=J.parse($,w)}else $.error=$.error||"URN can not be parsed.";return $}function Zu($,w){if($.nid===void 0)throw Error("URN without nid cannot be serialized");let X=w.scheme||$.scheme||"urn",G=$.nid.toLowerCase(),E=`${X}:${w.nid||G}`,J=vA(E);if(J)$=J.serialize($,w);let W=$,Y=$.nss;return W.path=`${G||w.nid}:${Y}`,w.skipEscape=!0,W}function bu($,w){let X=$;if(X.uuid=X.nss,X.nss=void 0,!w.tolerant&&(!X.uuid||!Ru(X.uuid)))X.error=X.error||"UUID is not valid.";return X}function ku($){let w=$;return w.nss=($.uuid||"").toLowerCase(),w}var GR={scheme:"http",domainHost:!0,parse:wR,serialize:XR},Cu={scheme:"https",domainHost:GR.domainHost,parse:wR,serialize:XR},u8={scheme:"ws",domainHost:!0,parse:Pu,serialize:qu},vu={scheme:"wss",domainHost:u8.domainHost,parse:u8.parse,serialize:u8.serialize},_u={scheme:"urn",parse:Su,serialize:Zu,skipNormalize:!0},fu={scheme:"urn:uuid",parse:bu,serialize:ku,skipNormalize:!0},c8={http:GR,https:Cu,ws:u8,wss:vu,urn:_u,"urn:uuid":fu};Object.setPrototypeOf(c8,null);function vA($){return $&&(c8[$]||c8[$.toLowerCase()])||void 0}ER.exports={wsIsSecure:CA,SCHEMES:c8,isValidSchemeName:ju,getSchemeHandler:vA}});var AR=b((W50,n8)=>{var{normalizeIPv6:xu,removeDotSegments:CE,recomposeAuthority:yu,normalizeComponentEncoding:m8,isIPv4:gu,nonSimpleDomain:hu}=kA(),{SCHEMES:uu,getSchemeHandler:WR}=JR();function cu($,w){if(typeof $==="string")$=s1(Qw($,w),w);else if(typeof $==="object")$=Qw(s1($,w),w);return $}function mu($,w,X){let G=X?Object.assign({scheme:"null"},X):{scheme:"null"},E=YR(Qw($,G),Qw(w,G),G,!0);return G.skipEscape=!0,s1(E,G)}function YR($,w,X,G){let E={};if(!G)$=Qw(s1($,X),X),w=Qw(s1(w,X),X);if(X=X||{},!X.tolerant&&w.scheme)E.scheme=w.scheme,E.userinfo=w.userinfo,E.host=w.host,E.port=w.port,E.path=CE(w.path||""),E.query=w.query;else{if(w.userinfo!==void 0||w.host!==void 0||w.port!==void 0)E.userinfo=w.userinfo,E.host=w.host,E.port=w.port,E.path=CE(w.path||""),E.query=w.query;else{if(!w.path)if(E.path=$.path,w.query!==void 0)E.query=w.query;else E.query=$.query;else{if(w.path[0]==="/")E.path=CE(w.path);else{if(($.userinfo!==void 0||$.host!==void 0||$.port!==void 0)&&!$.path)E.path="/"+w.path;else if(!$.path)E.path=w.path;else E.path=$.path.slice(0,$.path.lastIndexOf("/")+1)+w.path;E.path=CE(E.path)}E.query=w.query}E.userinfo=$.userinfo,E.host=$.host,E.port=$.port}E.scheme=$.scheme}return E.fragment=w.fragment,E}function nu($,w,X){if(typeof $==="string")$=unescape($),$=s1(m8(Qw($,X),!0),{...X,skipEscape:!0});else if(typeof $==="object")$=s1(m8($,!0),{...X,skipEscape:!0});if(typeof w==="string")w=unescape(w),w=s1(m8(Qw(w,X),!0),{...X,skipEscape:!0});else if(typeof w==="object")w=s1(m8(w,!0),{...X,skipEscape:!0});return $.toLowerCase()===w.toLowerCase()}function s1($,w){let X={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:""},G=Object.assign({},w),E=[],J=WR(G.scheme||X.scheme);if(J&&J.serialize)J.serialize(X,G);if(X.path!==void 0)if(!G.skipEscape){if(X.path=escape(X.path),X.scheme!==void 0)X.path=X.path.split("%3A").join(":")}else X.path=unescape(X.path);if(G.reference!=="suffix"&&X.scheme)E.push(X.scheme,":");let W=yu(X);if(W!==void 0){if(G.reference!=="suffix")E.push("//");if(E.push(W),X.path&&X.path[0]!=="/")E.push("/")}if(X.path!==void 0){let Y=X.path;if(!G.absolutePath&&(!J||!J.absolutePath))Y=CE(Y);if(W===void 0&&Y[0]==="/"&&Y[1]==="/")Y="/%2F"+Y.slice(2);E.push(Y)}if(X.query!==void 0)E.push("?",X.query);if(X.fragment!==void 0)E.push("#",X.fragment);return E.join("")}var pu=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Qw($,w){let X=Object.assign({},w),G={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},E=!1;if(X.reference==="suffix")if(X.scheme)$=X.scheme+":"+$;else $="//"+$;let J=$.match(pu);if(J){if(G.scheme=J[1],G.userinfo=J[3],G.host=J[4],G.port=parseInt(J[5],10),G.path=J[6]||"",G.query=J[7],G.fragment=J[8],isNaN(G.port))G.port=J[5];if(G.host)if(gu(G.host)===!1){let A=xu(G.host);G.host=A.host.toLowerCase(),E=A.isIPV6}else E=!0;if(G.scheme===void 0&&G.userinfo===void 0&&G.host===void 0&&G.port===void 0&&G.query===void 0&&!G.path)G.reference="same-document";else if(G.scheme===void 0)G.reference="relative";else if(G.fragment===void 0)G.reference="absolute";else G.reference="uri";if(X.reference&&X.reference!=="suffix"&&X.reference!==G.reference)G.error=G.error||"URI is not a "+X.reference+" reference.";let W=WR(X.scheme||G.scheme);if(!X.unicodeSupport&&(!W||!W.unicodeSupport)){if(G.host&&(X.domainHost||W&&W.domainHost)&&E===!1&&hu(G.host))try{G.host=URL.domainToASCII(G.host.toLowerCase())}catch(Y){G.error=G.error||"Host's domain name can not be converted to ASCII: "+Y}}if(!W||W&&!W.skipNormalize){if($.indexOf("%")!==-1){if(G.scheme!==void 0)G.scheme=unescape(G.scheme);if(G.host!==void 0)G.host=unescape(G.host)}if(G.path)G.path=escape(unescape(G.path));if(G.fragment)G.fragment=encodeURI(decodeURIComponent(G.fragment))}if(W&&W.parse)W.parse(G,X)}else G.error=G.error||"URI can not be parsed.";return G}var _A={SCHEMES:uu,normalize:cu,resolve:mu,resolveComponent:YR,equal:nu,serialize:s1,parse:Qw};n8.exports=_A;n8.exports.default=_A;n8.exports.fastUri=_A});var OR=b((UR)=>{Object.defineProperty(UR,"__esModule",{value:!0});var DR=AR();DR.code='require("ajv/dist/runtime/uri").default';UR.default=DR});var BR=b((Bw)=>{Object.defineProperty(Bw,"__esModule",{value:!0});Bw.CodeGen=Bw.Name=Bw.nil=Bw.stringify=Bw.str=Bw._=Bw.KeywordCxt=void 0;var iu=ZE();Object.defineProperty(Bw,"KeywordCxt",{enumerable:!0,get:function(){return iu.KeywordCxt}});var xG=W0();Object.defineProperty(Bw,"_",{enumerable:!0,get:function(){return xG._}});Object.defineProperty(Bw,"str",{enumerable:!0,get:function(){return xG.str}});Object.defineProperty(Bw,"stringify",{enumerable:!0,get:function(){return xG.stringify}});Object.defineProperty(Bw,"nil",{enumerable:!0,get:function(){return xG.nil}});Object.defineProperty(Bw,"Name",{enumerable:!0,get:function(){return xG.Name}});Object.defineProperty(Bw,"CodeGen",{enumerable:!0,get:function(){return xG.CodeGen}});var ou=y8(),MR=bE(),tu=HA(),vE=h8(),du=W0(),_E=PE(),p8=jE(),xA=N0(),NR=lV(),lu=OR(),zR=($,w)=>new RegExp($,w);zR.code="new RegExp";var su=["removeAdditional","useDefaults","coerceTypes"],au=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),eu={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."},$c={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},HR=200;function wc($){var w,X,G,E,J,W,Y,A,D,U,N,H,L,F,M,z,Q,R,T,v,f,k,m,F0,b0;let f0=$.strict,c0=(w=$.code)===null||w===void 0?void 0:w.optimize,K0=c0===!0||c0===void 0?1:c0||0,J$=(G=(X=$.code)===null||X===void 0?void 0:X.regExp)!==null&&G!==void 0?G:zR,G1=(E=$.uriResolver)!==null&&E!==void 0?E:lu.default;return{strictSchema:(W=(J=$.strictSchema)!==null&&J!==void 0?J:f0)!==null&&W!==void 0?W:!0,strictNumbers:(A=(Y=$.strictNumbers)!==null&&Y!==void 0?Y:f0)!==null&&A!==void 0?A:!0,strictTypes:(U=(D=$.strictTypes)!==null&&D!==void 0?D:f0)!==null&&U!==void 0?U:"log",strictTuples:(H=(N=$.strictTuples)!==null&&N!==void 0?N:f0)!==null&&H!==void 0?H:"log",strictRequired:(F=(L=$.strictRequired)!==null&&L!==void 0?L:f0)!==null&&F!==void 0?F:!1,code:$.code?{...$.code,optimize:K0,regExp:J$}:{optimize:K0,regExp:J$},loopRequired:(M=$.loopRequired)!==null&&M!==void 0?M:HR,loopEnum:(z=$.loopEnum)!==null&&z!==void 0?z:HR,meta:(Q=$.meta)!==null&&Q!==void 0?Q:!0,messages:(R=$.messages)!==null&&R!==void 0?R:!0,inlineRefs:(T=$.inlineRefs)!==null&&T!==void 0?T:!0,schemaId:(v=$.schemaId)!==null&&v!==void 0?v:"$id",addUsedSchema:(f=$.addUsedSchema)!==null&&f!==void 0?f:!0,validateSchema:(k=$.validateSchema)!==null&&k!==void 0?k:!0,validateFormats:(m=$.validateFormats)!==null&&m!==void 0?m:!0,unicodeRegExp:(F0=$.unicodeRegExp)!==null&&F0!==void 0?F0:!0,int32range:(b0=$.int32range)!==null&&b0!==void 0?b0:!0,uriResolver:G1}}class r8{constructor($={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,$=this.opts={...$,...wc($)};let{es5:w,lines:X}=this.opts.code;this.scope=new du.ValueScope({scope:{},prefixes:au,es5:w,lines:X}),this.logger=Yc($.logger);let G=$.validateFormats;if($.validateFormats=!1,this.RULES=(0,tu.getRules)(),LR.call(this,eu,$,"NOT SUPPORTED"),LR.call(this,$c,$,"DEPRECATED","warn"),this._metaOpts=Jc.call(this),$.formats)Gc.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),$.keywords)Ec.call(this,$.keywords);if(typeof $.meta=="object")this.addMetaSchema($.meta);Xc.call(this),$.validateFormats=G}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:$,meta:w,schemaId:X}=this.opts,G=NR;if(X==="id")G={...NR},G.id=G.$id,delete G.$id;if(w&&$)this.addMetaSchema(G,G[X],!1)}defaultMeta(){let{meta:$,schemaId:w}=this.opts;return this.opts.defaultMeta=typeof $=="object"?$[w]||$:void 0}validate($,w){let X;if(typeof $=="string"){if(X=this.getSchema($),!X)throw Error(`no schema with key or ref "${$}"`)}else X=this.compile($);let G=X(w);if(!("$async"in X))this.errors=X.errors;return G}compile($,w){let X=this._addSchema($,w);return X.validate||this._compileSchemaEnv(X)}compileAsync($,w){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:X}=this.opts;return G.call(this,$,w);async function G(D,U){await E.call(this,D.$schema);let N=this._addSchema(D,U);return N.validate||J.call(this,N)}async function E(D){if(D&&!this.getSchema(D))await G.call(this,{$ref:D},!0)}async function J(D){try{return this._compileSchemaEnv(D)}catch(U){if(!(U instanceof MR.default))throw U;return W.call(this,U),await Y.call(this,U.missingSchema),J.call(this,D)}}function W({missingSchema:D,missingRef:U}){if(this.refs[D])throw Error(`AnySchema ${D} is loaded but ${U} cannot be resolved`)}async function Y(D){let U=await A.call(this,D);if(!this.refs[D])await E.call(this,U.$schema);if(!this.refs[D])this.addSchema(U,D,w)}async function A(D){let U=this._loading[D];if(U)return U;try{return await(this._loading[D]=X(D))}finally{delete this._loading[D]}}}addSchema($,w,X,G=this.opts.validateSchema){if(Array.isArray($)){for(let J of $)this.addSchema(J,void 0,X,G);return this}let E;if(typeof $==="object"){let{schemaId:J}=this.opts;if(E=$[J],E!==void 0&&typeof E!="string")throw Error(`schema ${J} must be string`)}return w=(0,_E.normalizeId)(w||E),this._checkUnique(w),this.schemas[w]=this._addSchema($,X,w,G,!0),this}addMetaSchema($,w,X=this.opts.validateSchema){return this.addSchema($,w,!0,X),this}validateSchema($,w){if(typeof $=="boolean")return!0;let X;if(X=$.$schema,X!==void 0&&typeof X!="string")throw Error("$schema must be a string");if(X=X||this.opts.defaultMeta||this.defaultMeta(),!X)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let G=this.validate(X,$);if(!G&&w){let E="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(E);else throw Error(E)}return G}getSchema($){let w;while(typeof(w=FR.call(this,$))=="string")$=w;if(w===void 0){let{schemaId:X}=this.opts,G=new vE.SchemaEnv({schema:{},schemaId:X});if(w=vE.resolveSchema.call(this,G,$),!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=FR.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 X=$[this.opts.schemaId];if(X)X=(0,_E.normalizeId)(X),delete this.schemas[X],delete this.refs[X];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary($){for(let w of $)this.addKeyword(w);return this}addKeyword($,w){let X;if(typeof $=="string"){if(X=$,typeof w=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),w.keyword=X}else if(typeof $=="object"&&w===void 0){if(w=$,X=w.keyword,Array.isArray(X)&&!X.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(Dc.call(this,X,w),!w)return(0,xA.eachItem)(X,(E)=>fA.call(this,E)),this;Oc.call(this,w);let G={...w,type:(0,p8.getJSONTypes)(w.type),schemaType:(0,p8.getJSONTypes)(w.schemaType)};return(0,xA.eachItem)(X,G.type.length===0?(E)=>fA.call(this,E,G):(E)=>G.type.forEach((J)=>fA.call(this,E,G,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 X of w.rules){let G=X.rules.findIndex((E)=>E.keyword===$);if(G>=0)X.rules.splice(G,1)}return this}addFormat($,w){if(typeof w=="string")w=new RegExp(w);return this.formats[$]=w,this}errorsText($=this.errors,{separator:w=", ",dataVar:X="data"}={}){if(!$||$.length===0)return"No errors";return $.map((G)=>`${X}${G.instancePath} ${G.message}`).reduce((G,E)=>G+w+E)}$dataMetaSchema($,w){let X=this.RULES.all;$=JSON.parse(JSON.stringify($));for(let G of w){let E=G.split("/").slice(1),J=$;for(let W of E)J=J[W];for(let W in X){let Y=X[W];if(typeof Y!="object")continue;let{$data:A}=Y.definition,D=J[W];if(A&&D)J[W]=QR(D)}}return $}_removeAllSchemas($,w){for(let X in $){let G=$[X];if(!w||w.test(X)){if(typeof G=="string")delete $[X];else if(G&&!G.meta)this._cache.delete(G.schema),delete $[X]}}}_addSchema($,w,X,G=this.opts.validateSchema,E=this.opts.addUsedSchema){let J,{schemaId:W}=this.opts;if(typeof $=="object")J=$[W];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof $!="boolean")throw Error("schema must be object or boolean");let Y=this._cache.get($);if(Y!==void 0)return Y;X=(0,_E.normalizeId)(J||X);let A=_E.getSchemaRefs.call(this,$,X);if(Y=new vE.SchemaEnv({schema:$,schemaId:W,meta:w,baseId:X,localRefs:A}),this._cache.set(Y.schema,Y),E&&!X.startsWith("#")){if(X)this._checkUnique(X);this.refs[X]=Y}if(G)this.validateSchema($,!0);return Y}_checkUnique($){if(this.schemas[$]||this.refs[$])throw Error(`schema with key or id "${$}" already exists`)}_compileSchemaEnv($){if($.meta)this._compileMetaSchema($);else vE.compileSchema.call(this,$);if(!$.validate)throw Error("ajv implementation error");return $.validate}_compileMetaSchema($){let w=this.opts;this.opts=this._metaOpts;try{vE.compileSchema.call(this,$)}finally{this.opts=w}}}r8.ValidationError=ou.default;r8.MissingRefError=MR.default;Bw.default=r8;function LR($,w,X,G="error"){for(let E in $){let J=E;if(J in w)this.logger[G](`${X}: option ${E}. ${$[J]}`)}}function FR($){return $=(0,_E.normalizeId)($),this.schemas[$]||this.refs[$]}function Xc(){let $=this.opts.schemas;if(!$)return;if(Array.isArray($))this.addSchema($);else for(let w in $)this.addSchema($[w],w)}function Gc(){for(let $ in this.opts.formats){let w=this.opts.formats[$];if(w)this.addFormat($,w)}}function Ec($){if(Array.isArray($)){this.addVocabulary($);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let w in $){let X=$[w];if(!X.keyword)X.keyword=w;this.addKeyword(X)}}function Jc(){let $={...this.opts};for(let w of su)delete $[w];return $}var Wc={log(){},warn(){},error(){}};function Yc($){if($===!1)return Wc;if($===void 0)return console;if($.log&&$.warn&&$.error)return $;throw Error("logger must implement log, warn and error methods")}var Ac=/^[a-z_$][a-z0-9_$:-]*$/i;function Dc($,w){let{RULES:X}=this;if((0,xA.eachItem)($,(G)=>{if(X.keywords[G])throw Error(`Keyword ${G} is already defined`);if(!Ac.test(G))throw Error(`Keyword ${G} 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 fA($,w,X){var G;let E=w===null||w===void 0?void 0:w.post;if(X&&E)throw Error('keyword with "post" flag cannot have "type"');let{RULES:J}=this,W=E?J.post:J.rules.find(({type:A})=>A===X);if(!W)W={type:X,rules:[]},J.rules.push(W);if(J.keywords[$]=!0,!w)return;let Y={keyword:$,definition:{...w,type:(0,p8.getJSONTypes)(w.type),schemaType:(0,p8.getJSONTypes)(w.schemaType)}};if(w.before)Uc.call(this,W,Y,w.before);else W.rules.push(Y);J.all[$]=Y,(G=w.implements)===null||G===void 0||G.forEach((A)=>this.addKeyword(A))}function Uc($,w,X){let G=$.rules.findIndex((E)=>E.keyword===X);if(G>=0)$.rules.splice(G,0,w);else $.rules.push(w),this.logger.warn(`rule ${X} is not defined`)}function Oc($){let{metaSchema:w}=$;if(w===void 0)return;if($.$data&&this.opts.$data)w=QR(w);$.validateSchema=this.compile(w,!0)}var Nc={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function QR($){return{anyOf:[$,Nc]}}});var VR=b((KR)=>{Object.defineProperty(KR,"__esModule",{value:!0});var Fc={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};KR.default=Fc});var qR=b((jR)=>{Object.defineProperty(jR,"__esModule",{value:!0});jR.callRef=jR.getValidate=void 0;var zc=bE(),RR=L1(),o$=W0(),yG=Mw(),TR=h8(),i8=N0(),Qc={keyword:"$ref",schemaType:"string",code($){let{gen:w,schema:X,it:G}=$,{baseId:E,schemaEnv:J,validateName:W,opts:Y,self:A}=G,{root:D}=J;if((X==="#"||X==="#/")&&E===D.baseId)return N();let U=TR.resolveRef.call(A,D,E,X);if(U===void 0)throw new zc.default(G.opts.uriResolver,E,X);if(U instanceof TR.SchemaEnv)return H(U);return L(U);function N(){if(J===D)return o8($,W,J,J.$async);let F=w.scopeValue("root",{ref:D});return o8($,o$._`${F}.validate`,D,D.$async)}function H(F){let M=IR($,F);o8($,M,F,F.$async)}function L(F){let M=w.scopeValue("schema",Y.code.source===!0?{ref:F,code:(0,o$.stringify)(F)}:{ref:F}),z=w.name("valid"),Q=$.subschema({schema:F,dataTypes:[],schemaPath:o$.nil,topSchemaRef:M,errSchemaPath:X},z);$.mergeEvaluated(Q),$.ok(z)}}};function IR($,w){let{gen:X}=$;return w.validate?X.scopeValue("validate",{ref:w.validate}):o$._`${X.scopeValue("wrapper",{ref:w})}.validate`}jR.getValidate=IR;function o8($,w,X,G){let{gen:E,it:J}=$,{allErrors:W,schemaEnv:Y,opts:A}=J,D=A.passContext?yG.default.this:o$.nil;if(G)U();else N();function U(){if(!Y.$async)throw Error("async schema referenced by sync schema");let F=E.let("valid");E.try(()=>{if(E.code(o$._`await ${(0,RR.callValidateCode)($,w,D)}`),L(w),!W)E.assign(F,!0)},(M)=>{if(E.if(o$._`!(${M} instanceof ${J.ValidationError})`,()=>E.throw(M)),H(M),!W)E.assign(F,!1)}),$.ok(F)}function N(){$.result((0,RR.callValidateCode)($,w,D),()=>L(w),()=>H(w))}function H(F){let M=o$._`${F}.errors`;E.assign(yG.default.vErrors,o$._`${yG.default.vErrors} === null ? ${M} : ${yG.default.vErrors}.concat(${M})`),E.assign(yG.default.errors,o$._`${yG.default.vErrors}.length`)}function L(F){var M;if(!J.opts.unevaluated)return;let z=(M=X===null||X===void 0?void 0:X.validate)===null||M===void 0?void 0:M.evaluated;if(J.props!==!0)if(z&&!z.dynamicProps){if(z.props!==void 0)J.props=i8.mergeEvaluated.props(E,z.props,J.props)}else{let Q=E.var("props",o$._`${F}.evaluated.props`);J.props=i8.mergeEvaluated.props(E,Q,J.props,o$.Name)}if(J.items!==!0)if(z&&!z.dynamicItems){if(z.items!==void 0)J.items=i8.mergeEvaluated.items(E,z.items,J.items)}else{let Q=E.var("items",o$._`${F}.evaluated.items`);J.items=i8.mergeEvaluated.items(E,Q,J.items,o$.Name)}}}jR.callRef=o8;jR.default=Qc});var ZR=b((SR)=>{Object.defineProperty(SR,"__esModule",{value:!0});var Vc=VR(),Rc=qR(),Tc=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Vc.default,Rc.default];SR.default=Tc});var kR=b((bR)=>{Object.defineProperty(bR,"__esModule",{value:!0});var t8=W0(),ow=t8.operators,d8={maximum:{okStr:"<=",ok:ow.LTE,fail:ow.GT},minimum:{okStr:">=",ok:ow.GTE,fail:ow.LT},exclusiveMaximum:{okStr:"<",ok:ow.LT,fail:ow.GTE},exclusiveMinimum:{okStr:">",ok:ow.GT,fail:ow.LTE}},jc={message:({keyword:$,schemaCode:w})=>t8.str`must be ${d8[$].okStr} ${w}`,params:({keyword:$,schemaCode:w})=>t8._`{comparison: ${d8[$].okStr}, limit: ${w}}`},Pc={keyword:Object.keys(d8),type:"number",schemaType:"number",$data:!0,error:jc,code($){let{keyword:w,data:X,schemaCode:G}=$;$.fail$data(t8._`${X} ${d8[w].fail} ${G} || isNaN(${X})`)}};bR.default=Pc});var vR=b((CR)=>{Object.defineProperty(CR,"__esModule",{value:!0});var fE=W0(),Sc={message:({schemaCode:$})=>fE.str`must be multiple of ${$}`,params:({schemaCode:$})=>fE._`{multipleOf: ${$}}`},Zc={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Sc,code($){let{gen:w,data:X,schemaCode:G,it:E}=$,J=E.opts.multipleOfPrecision,W=w.let("res"),Y=J?fE._`Math.abs(Math.round(${W}) - ${W}) > 1e-${J}`:fE._`${W} !== parseInt(${W})`;$.fail$data(fE._`(${G} === 0 || (${W} = ${X}/${G}, ${Y}))`)}};CR.default=Zc});var xR=b((fR)=>{Object.defineProperty(fR,"__esModule",{value:!0});function _R($){let w=$.length,X=0,G=0,E;while(G<w)if(X++,E=$.charCodeAt(G++),E>=55296&&E<=56319&&G<w){if(E=$.charCodeAt(G),(E&64512)===56320)G++}return X}fR.default=_R;_R.code='require("ajv/dist/runtime/ucs2length").default'});var gR=b((yR)=>{Object.defineProperty(yR,"__esModule",{value:!0});var RX=W0(),Cc=N0(),vc=xR(),_c={message({keyword:$,schemaCode:w}){let X=$==="maxLength"?"more":"fewer";return RX.str`must NOT have ${X} than ${w} characters`},params:({schemaCode:$})=>RX._`{limit: ${$}}`},fc={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:_c,code($){let{keyword:w,data:X,schemaCode:G,it:E}=$,J=w==="maxLength"?RX.operators.GT:RX.operators.LT,W=E.opts.unicode===!1?RX._`${X}.length`:RX._`${(0,Cc.useFunc)($.gen,vc.default)}(${X})`;$.fail$data(RX._`${W} ${J} ${G}`)}};yR.default=fc});var uR=b((hR)=>{Object.defineProperty(hR,"__esModule",{value:!0});var yc=L1(),gc=N0(),gG=W0(),hc={message:({schemaCode:$})=>gG.str`must match pattern "${$}"`,params:({schemaCode:$})=>gG._`{pattern: ${$}}`},uc={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:hc,code($){let{gen:w,data:X,$data:G,schema:E,schemaCode:J,it:W}=$,Y=W.opts.unicodeRegExp?"u":"";if(G){let{regExp:A}=W.opts.code,D=A.code==="new RegExp"?gG._`new RegExp`:(0,gc.useFunc)(w,A),U=w.let("valid");w.try(()=>w.assign(U,gG._`${D}(${J}, ${Y}).test(${X})`),()=>w.assign(U,!1)),$.fail$data(gG._`!${U}`)}else{let A=(0,yc.usePattern)($,E);$.fail$data(gG._`!${A}.test(${X})`)}}};hR.default=uc});var mR=b((cR)=>{Object.defineProperty(cR,"__esModule",{value:!0});var xE=W0(),mc={message({keyword:$,schemaCode:w}){let X=$==="maxProperties"?"more":"fewer";return xE.str`must NOT have ${X} than ${w} properties`},params:({schemaCode:$})=>xE._`{limit: ${$}}`},nc={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:mc,code($){let{keyword:w,data:X,schemaCode:G}=$,E=w==="maxProperties"?xE.operators.GT:xE.operators.LT;$.fail$data(xE._`Object.keys(${X}).length ${E} ${G}`)}};cR.default=nc});var pR=b((nR)=>{Object.defineProperty(nR,"__esModule",{value:!0});var yE=L1(),gE=W0(),rc=N0(),ic={message:({params:{missingProperty:$}})=>gE.str`must have required property '${$}'`,params:({params:{missingProperty:$}})=>gE._`{missingProperty: ${$}}`},oc={keyword:"required",type:"object",schemaType:"array",$data:!0,error:ic,code($){let{gen:w,schema:X,schemaCode:G,data:E,$data:J,it:W}=$,{opts:Y}=W;if(!J&&X.length===0)return;let A=X.length>=Y.loopRequired;if(W.allErrors)D();else U();if(Y.strictRequired){let L=$.parentSchema.properties,{definedProperties:F}=$.it;for(let M of X)if((L===null||L===void 0?void 0:L[M])===void 0&&!F.has(M)){let z=W.schemaEnv.baseId+W.errSchemaPath,Q=`required property "${M}" is not defined at "${z}" (strictRequired)`;(0,rc.checkStrictMode)(W,Q,W.opts.strictRequired)}}function D(){if(A||J)$.block$data(gE.nil,N);else for(let L of X)(0,yE.checkReportMissingProp)($,L)}function U(){let L=w.let("missing");if(A||J){let F=w.let("valid",!0);$.block$data(F,()=>H(L,F)),$.ok(F)}else w.if((0,yE.checkMissingProp)($,X,L)),(0,yE.reportMissingProp)($,L),w.else()}function N(){w.forOf("prop",G,(L)=>{$.setParams({missingProperty:L}),w.if((0,yE.noPropertyInData)(w,E,L,Y.ownProperties),()=>$.error())})}function H(L,F){$.setParams({missingProperty:L}),w.forOf(L,G,()=>{w.assign(F,(0,yE.propertyInData)(w,E,L,Y.ownProperties)),w.if((0,gE.not)(F),()=>{$.error(),w.break()})},gE.nil)}}};nR.default=oc});var iR=b((rR)=>{Object.defineProperty(rR,"__esModule",{value:!0});var hE=W0(),dc={message({keyword:$,schemaCode:w}){let X=$==="maxItems"?"more":"fewer";return hE.str`must NOT have ${X} than ${w} items`},params:({schemaCode:$})=>hE._`{limit: ${$}}`},lc={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:dc,code($){let{keyword:w,data:X,schemaCode:G}=$,E=w==="maxItems"?hE.operators.GT:hE.operators.LT;$.fail$data(hE._`${X}.length ${E} ${G}`)}};rR.default=lc});var l8=b((tR)=>{Object.defineProperty(tR,"__esModule",{value:!0});var oR=VA();oR.code='require("ajv/dist/runtime/equal").default';tR.default=oR});var lR=b((dR)=>{Object.defineProperty(dR,"__esModule",{value:!0});var yA=jE(),Q$=W0(),ec=N0(),$m=l8(),wm={message:({params:{i:$,j:w}})=>Q$.str`must NOT have duplicate items (items ## ${w} and ${$} are identical)`,params:({params:{i:$,j:w}})=>Q$._`{i: ${$}, j: ${w}}`},Xm={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:wm,code($){let{gen:w,data:X,$data:G,schema:E,parentSchema:J,schemaCode:W,it:Y}=$;if(!G&&!E)return;let A=w.let("valid"),D=J.items?(0,yA.getSchemaTypes)(J.items):[];$.block$data(A,U,Q$._`${W} === false`),$.ok(A);function U(){let F=w.let("i",Q$._`${X}.length`),M=w.let("j");$.setParams({i:F,j:M}),w.assign(A,!0),w.if(Q$._`${F} > 1`,()=>(N()?H:L)(F,M))}function N(){return D.length>0&&!D.some((F)=>F==="object"||F==="array")}function H(F,M){let z=w.name("item"),Q=(0,yA.checkDataTypes)(D,z,Y.opts.strictNumbers,yA.DataType.Wrong),R=w.const("indices",Q$._`{}`);w.for(Q$._`;${F}--;`,()=>{if(w.let(z,Q$._`${X}[${F}]`),w.if(Q,Q$._`continue`),D.length>1)w.if(Q$._`typeof ${z} == "string"`,Q$._`${z} += "_"`);w.if(Q$._`typeof ${R}[${z}] == "number"`,()=>{w.assign(M,Q$._`${R}[${z}]`),$.error(),w.assign(A,!1).break()}).code(Q$._`${R}[${z}] = ${F}`)})}function L(F,M){let z=(0,ec.useFunc)(w,$m.default),Q=w.name("outer");w.label(Q).for(Q$._`;${F}--;`,()=>w.for(Q$._`${M} = ${F}; ${M}--;`,()=>w.if(Q$._`${z}(${X}[${F}], ${X}[${M}])`,()=>{$.error(),w.assign(A,!1).break(Q)})))}}};dR.default=Xm});var aR=b((sR)=>{Object.defineProperty(sR,"__esModule",{value:!0});var gA=W0(),Em=N0(),Jm=l8(),Wm={message:"must be equal to constant",params:({schemaCode:$})=>gA._`{allowedValue: ${$}}`},Ym={keyword:"const",$data:!0,error:Wm,code($){let{gen:w,data:X,$data:G,schemaCode:E,schema:J}=$;if(G||J&&typeof J=="object")$.fail$data(gA._`!${(0,Em.useFunc)(w,Jm.default)}(${X}, ${E})`);else $.fail(gA._`${J} !== ${X}`)}};sR.default=Ym});var $T=b((eR)=>{Object.defineProperty(eR,"__esModule",{value:!0});var uE=W0(),Dm=N0(),Um=l8(),Om={message:"must be equal to one of the allowed values",params:({schemaCode:$})=>uE._`{allowedValues: ${$}}`},Nm={keyword:"enum",schemaType:"array",$data:!0,error:Om,code($){let{gen:w,data:X,$data:G,schema:E,schemaCode:J,it:W}=$;if(!G&&E.length===0)throw Error("enum must have non-empty array");let Y=E.length>=W.opts.loopEnum,A,D=()=>A!==null&&A!==void 0?A:A=(0,Dm.useFunc)(w,Um.default),U;if(Y||G)U=w.let("valid"),$.block$data(U,N);else{if(!Array.isArray(E))throw Error("ajv implementation error");let L=w.const("vSchema",J);U=(0,uE.or)(...E.map((F,M)=>H(L,M)))}$.pass(U);function N(){w.assign(U,!1),w.forOf("v",J,(L)=>w.if(uE._`${D()}(${X}, ${L})`,()=>w.assign(U,!0).break()))}function H(L,F){let M=E[F];return typeof M==="object"&&M!==null?uE._`${D()}(${X}, ${L}[${F}])`:uE._`${X} === ${M}`}}};eR.default=Nm});var XT=b((wT)=>{Object.defineProperty(wT,"__esModule",{value:!0});var Lm=kR(),Fm=vR(),Mm=gR(),zm=uR(),Qm=mR(),Bm=pR(),Km=iR(),Vm=lR(),Rm=aR(),Tm=$T(),Im=[Lm.default,Fm.default,Mm.default,zm.default,Qm.default,Bm.default,Km.default,Vm.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Rm.default,Tm.default];wT.default=Im});var uA=b((ET)=>{Object.defineProperty(ET,"__esModule",{value:!0});ET.validateAdditionalItems=void 0;var TX=W0(),hA=N0(),Pm={message:({params:{len:$}})=>TX.str`must NOT have more than ${$} items`,params:({params:{len:$}})=>TX._`{limit: ${$}}`},qm={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Pm,code($){let{parentSchema:w,it:X}=$,{items:G}=w;if(!Array.isArray(G)){(0,hA.checkStrictMode)(X,'"additionalItems" is ignored when "items" is not an array of schemas');return}GT($,G)}};function GT($,w){let{gen:X,schema:G,data:E,keyword:J,it:W}=$;W.items=!0;let Y=X.const("len",TX._`${E}.length`);if(G===!1)$.setParams({len:w.length}),$.pass(TX._`${Y} <= ${w.length}`);else if(typeof G=="object"&&!(0,hA.alwaysValidSchema)(W,G)){let D=X.var("valid",TX._`${Y} <= ${w.length}`);X.if((0,TX.not)(D),()=>A(D)),$.ok(D)}function A(D){X.forRange("i",w.length,Y,(U)=>{if($.subschema({keyword:J,dataProp:U,dataPropType:hA.Type.Num},D),!W.allErrors)X.if((0,TX.not)(D),()=>X.break())})}}ET.validateAdditionalItems=GT;ET.default=qm});var cA=b((AT)=>{Object.defineProperty(AT,"__esModule",{value:!0});AT.validateTuple=void 0;var WT=W0(),s8=N0(),Zm=L1(),bm={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code($){let{schema:w,it:X}=$;if(Array.isArray(w))return YT($,"additionalItems",w);if(X.items=!0,(0,s8.alwaysValidSchema)(X,w))return;$.ok((0,Zm.validateArray)($))}};function YT($,w,X=$.schema){let{gen:G,parentSchema:E,data:J,keyword:W,it:Y}=$;if(U(E),Y.opts.unevaluated&&X.length&&Y.items!==!0)Y.items=s8.mergeEvaluated.items(G,X.length,Y.items);let A=G.name("valid"),D=G.const("len",WT._`${J}.length`);X.forEach((N,H)=>{if((0,s8.alwaysValidSchema)(Y,N))return;G.if(WT._`${D} > ${H}`,()=>$.subschema({keyword:W,schemaProp:H,dataProp:H},A)),$.ok(A)});function U(N){let{opts:H,errSchemaPath:L}=Y,F=X.length,M=F===N.minItems&&(F===N.maxItems||N[w]===!1);if(H.strictTuples&&!M){let z=`"${W}" is ${F}-tuple, but minItems or maxItems/${w} are not specified or different at path "${L}"`;(0,s8.checkStrictMode)(Y,z,H.strictTuples)}}}AT.validateTuple=YT;AT.default=bm});var OT=b((UT)=>{Object.defineProperty(UT,"__esModule",{value:!0});var Cm=cA(),vm={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:($)=>(0,Cm.validateTuple)($,"items")};UT.default=vm});var LT=b((HT)=>{Object.defineProperty(HT,"__esModule",{value:!0});var NT=W0(),fm=N0(),xm=L1(),ym=uA(),gm={message:({params:{len:$}})=>NT.str`must NOT have more than ${$} items`,params:({params:{len:$}})=>NT._`{limit: ${$}}`},hm={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:gm,code($){let{schema:w,parentSchema:X,it:G}=$,{prefixItems:E}=X;if(G.items=!0,(0,fm.alwaysValidSchema)(G,w))return;if(E)(0,ym.validateAdditionalItems)($,E);else $.ok((0,xm.validateArray)($))}};HT.default=hm});var MT=b((FT)=>{Object.defineProperty(FT,"__esModule",{value:!0});var F1=W0(),a8=N0(),cm={message:({params:{min:$,max:w}})=>w===void 0?F1.str`must contain at least ${$} valid item(s)`:F1.str`must contain at least ${$} and no more than ${w} valid item(s)`,params:({params:{min:$,max:w}})=>w===void 0?F1._`{minContains: ${$}}`:F1._`{minContains: ${$}, maxContains: ${w}}`},mm={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:cm,code($){let{gen:w,schema:X,parentSchema:G,data:E,it:J}=$,W,Y,{minContains:A,maxContains:D}=G;if(J.opts.next)W=A===void 0?1:A,Y=D;else W=1;let U=w.const("len",F1._`${E}.length`);if($.setParams({min:W,max:Y}),Y===void 0&&W===0){(0,a8.checkStrictMode)(J,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(Y!==void 0&&W>Y){(0,a8.checkStrictMode)(J,'"minContains" > "maxContains" is always invalid'),$.fail();return}if((0,a8.alwaysValidSchema)(J,X)){let M=F1._`${U} >= ${W}`;if(Y!==void 0)M=F1._`${M} && ${U} <= ${Y}`;$.pass(M);return}J.items=!0;let N=w.name("valid");if(Y===void 0&&W===1)L(N,()=>w.if(N,()=>w.break()));else if(W===0){if(w.let(N,!0),Y!==void 0)w.if(F1._`${E}.length > 0`,H)}else w.let(N,!1),H();$.result(N,()=>$.reset());function H(){let M=w.name("_valid"),z=w.let("count",0);L(M,()=>w.if(M,()=>F(z)))}function L(M,z){w.forRange("i",0,U,(Q)=>{$.subschema({keyword:"contains",dataProp:Q,dataPropType:a8.Type.Num,compositeRule:!0},M),z()})}function F(M){if(w.code(F1._`${M}++`),Y===void 0)w.if(F1._`${M} >= ${W}`,()=>w.assign(N,!0).break());else if(w.if(F1._`${M} > ${Y}`,()=>w.assign(N,!1).break()),W===1)w.assign(N,!0);else w.if(F1._`${M} >= ${W}`,()=>w.assign(N,!0))}}};FT.default=mm});var RT=b((BT)=>{Object.defineProperty(BT,"__esModule",{value:!0});BT.validateSchemaDeps=BT.validatePropertyDeps=BT.error=void 0;var mA=W0(),pm=N0(),cE=L1();BT.error={message:({params:{property:$,depsCount:w,deps:X}})=>{let G=w===1?"property":"properties";return mA.str`must have ${G} ${X} when property ${$} is present`},params:({params:{property:$,depsCount:w,deps:X,missingProperty:G}})=>mA._`{property: ${$},
|
|
496
|
-
missingProperty: ${
|
|
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
|
|
572
|
+
|| (${A} == "string" && ${G} && ${G} == +${G})`).assign(D,D0._`+${G}`);return;case"integer":X.elseIf(D0._`${A} === "boolean" || ${G} === null
|
|
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: ${$},
|
|
575
|
+
missingProperty: ${X},
|
|
497
576
|
depsCount: ${w},
|
|
498
|
-
deps: ${X}}`};var rm={keyword:"dependencies",type:"object",schemaType:"object",error:BT.error,code($){let[w,X]=im($);zT($,w),QT($,X)}};function im({schema:$}){let w={},X={};for(let G in $){if(G==="__proto__")continue;let E=Array.isArray($[G])?w:X;E[G]=$[G]}return[w,X]}function zT($,w=$.schema){let{gen:X,data:G,it:E}=$;if(Object.keys(w).length===0)return;let J=X.let("missing");for(let W in w){let Y=w[W];if(Y.length===0)continue;let A=(0,cE.propertyInData)(X,G,W,E.opts.ownProperties);if($.setParams({property:W,depsCount:Y.length,deps:Y.join(", ")}),E.allErrors)X.if(A,()=>{for(let D of Y)(0,cE.checkReportMissingProp)($,D)});else X.if(mA._`${A} && (${(0,cE.checkMissingProp)($,Y,J)})`),(0,cE.reportMissingProp)($,J),X.else()}}BT.validatePropertyDeps=zT;function QT($,w=$.schema){let{gen:X,data:G,keyword:E,it:J}=$,W=X.name("valid");for(let Y in w){if((0,pm.alwaysValidSchema)(J,w[Y]))continue;X.if((0,cE.propertyInData)(X,G,Y,J.opts.ownProperties),()=>{let A=$.subschema({keyword:E,schemaProp:Y},W);$.mergeValidEvaluated(A,W)},()=>X.var(W,!0)),$.ok(W)}}BT.validateSchemaDeps=QT;BT.default=rm});var jT=b((IT)=>{Object.defineProperty(IT,"__esModule",{value:!0});var TT=W0(),dm=N0(),lm={message:"property name must be valid",params:({params:$})=>TT._`{propertyName: ${$.propertyName}}`},sm={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:lm,code($){let{gen:w,schema:X,data:G,it:E}=$;if((0,dm.alwaysValidSchema)(E,X))return;let J=w.name("valid");w.forIn("key",G,(W)=>{$.setParams({propertyName:W}),$.subschema({keyword:"propertyNames",data:W,dataTypes:["string"],propertyName:W,compositeRule:!0},J),w.if((0,TT.not)(J),()=>{if($.error(!0),!E.allErrors)w.break()})}),$.ok(J)}};IT.default=sm});var nA=b((PT)=>{Object.defineProperty(PT,"__esModule",{value:!0});var e8=L1(),x1=W0(),em=Mw(),$5=N0(),$n={message:"must NOT have additional properties",params:({params:$})=>x1._`{additionalProperty: ${$.additionalProperty}}`},wn={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:$n,code($){let{gen:w,schema:X,parentSchema:G,data:E,errsCount:J,it:W}=$;if(!J)throw Error("ajv implementation error");let{allErrors:Y,opts:A}=W;if(W.props=!0,A.removeAdditional!=="all"&&(0,$5.alwaysValidSchema)(W,X))return;let D=(0,e8.allSchemaProperties)(G.properties),U=(0,e8.allSchemaProperties)(G.patternProperties);N(),$.ok(x1._`${J} === ${em.default.errors}`);function N(){w.forIn("key",E,(z)=>{if(!D.length&&!U.length)F(z);else w.if(H(z),()=>F(z))})}function H(z){let Q;if(D.length>8){let R=(0,$5.schemaRefOrVal)(W,G.properties,"properties");Q=(0,e8.isOwnProperty)(w,R,z)}else if(D.length)Q=(0,x1.or)(...D.map((R)=>x1._`${z} === ${R}`));else Q=x1.nil;if(U.length)Q=(0,x1.or)(Q,...U.map((R)=>x1._`${(0,e8.usePattern)($,R)}.test(${z})`));return(0,x1.not)(Q)}function L(z){w.code(x1._`delete ${E}[${z}]`)}function F(z){if(A.removeAdditional==="all"||A.removeAdditional&&X===!1){L(z);return}if(X===!1){if($.setParams({additionalProperty:z}),$.error(),!Y)w.break();return}if(typeof X=="object"&&!(0,$5.alwaysValidSchema)(W,X)){let Q=w.name("valid");if(A.removeAdditional==="failing")M(z,Q,!1),w.if((0,x1.not)(Q),()=>{$.reset(),L(z)});else if(M(z,Q),!Y)w.if((0,x1.not)(Q),()=>w.break())}}function M(z,Q,R){let T={keyword:"additionalProperties",dataProp:z,dataPropType:$5.Type.Str};if(R===!1)Object.assign(T,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(T,Q)}}};PT.default=wn});var bT=b((ZT)=>{Object.defineProperty(ZT,"__esModule",{value:!0});var Gn=ZE(),qT=L1(),pA=N0(),ST=nA(),En={keyword:"properties",type:"object",schemaType:"object",code($){let{gen:w,schema:X,parentSchema:G,data:E,it:J}=$;if(J.opts.removeAdditional==="all"&&G.additionalProperties===void 0)ST.default.code(new Gn.KeywordCxt(J,ST.default,"additionalProperties"));let W=(0,qT.allSchemaProperties)(X);for(let N of W)J.definedProperties.add(N);if(J.opts.unevaluated&&W.length&&J.props!==!0)J.props=pA.mergeEvaluated.props(w,(0,pA.toHash)(W),J.props);let Y=W.filter((N)=>!(0,pA.alwaysValidSchema)(J,X[N]));if(Y.length===0)return;let A=w.name("valid");for(let N of Y){if(D(N))U(N);else{if(w.if((0,qT.propertyInData)(w,E,N,J.opts.ownProperties)),U(N),!J.allErrors)w.else().var(A,!0);w.endIf()}$.it.definedProperties.add(N),$.ok(A)}function D(N){return J.opts.useDefaults&&!J.compositeRule&&X[N].default!==void 0}function U(N){$.subschema({keyword:"properties",schemaProp:N,dataProp:N},A)}}};ZT.default=En});var fT=b((_T)=>{Object.defineProperty(_T,"__esModule",{value:!0});var kT=L1(),w5=W0(),CT=N0(),vT=N0(),Wn={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:w,schema:X,data:G,parentSchema:E,it:J}=$,{opts:W}=J,Y=(0,kT.allSchemaProperties)(X),A=Y.filter((M)=>(0,CT.alwaysValidSchema)(J,X[M]));if(Y.length===0||A.length===Y.length&&(!J.opts.unevaluated||J.props===!0))return;let D=W.strictSchema&&!W.allowMatchingProperties&&E.properties,U=w.name("valid");if(J.props!==!0&&!(J.props instanceof w5.Name))J.props=(0,vT.evaluatedPropsToName)(w,J.props);let{props:N}=J;H();function H(){for(let M of Y){if(D)L(M);if(J.allErrors)F(M);else w.var(U,!0),F(M),w.if(U)}}function L(M){for(let z in D)if(new RegExp(M).test(z))(0,CT.checkStrictMode)(J,`property ${z} matches pattern ${M} (use allowMatchingProperties)`)}function F(M){w.forIn("key",G,(z)=>{w.if(w5._`${(0,kT.usePattern)($,M)}.test(${z})`,()=>{let Q=A.includes(M);if(!Q)$.subschema({keyword:"patternProperties",schemaProp:M,dataProp:z,dataPropType:vT.Type.Str},U);if(J.opts.unevaluated&&N!==!0)w.assign(w5._`${N}[${z}]`,!0);else if(!Q&&!J.allErrors)w.if((0,w5.not)(U),()=>w.break())})})}}};_T.default=Wn});var yT=b((xT)=>{Object.defineProperty(xT,"__esModule",{value:!0});var An=N0(),Dn={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code($){let{gen:w,schema:X,it:G}=$;if((0,An.alwaysValidSchema)(G,X)){$.fail();return}let E=w.name("valid");$.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},E),$.failResult(E,()=>$.reset(),()=>$.error())},error:{message:"must NOT be valid"}};xT.default=Dn});var hT=b((gT)=>{Object.defineProperty(gT,"__esModule",{value:!0});var On=L1(),Nn={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:On.validateUnion,error:{message:"must match a schema in anyOf"}};gT.default=Nn});var cT=b((uT)=>{Object.defineProperty(uT,"__esModule",{value:!0});var X5=W0(),Ln=N0(),Fn={message:"must match exactly one schema in oneOf",params:({params:$})=>X5._`{passingSchemas: ${$.passing}}`},Mn={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Fn,code($){let{gen:w,schema:X,parentSchema:G,it:E}=$;if(!Array.isArray(X))throw Error("ajv implementation error");if(E.opts.discriminator&&G.discriminator)return;let J=X,W=w.let("valid",!1),Y=w.let("passing",null),A=w.name("_valid");$.setParams({passing:Y}),w.block(D),$.result(W,()=>$.reset(),()=>$.error(!0));function D(){J.forEach((U,N)=>{let H;if((0,Ln.alwaysValidSchema)(E,U))w.var(A,!0);else H=$.subschema({keyword:"oneOf",schemaProp:N,compositeRule:!0},A);if(N>0)w.if(X5._`${A} && ${W}`).assign(W,!1).assign(Y,X5._`[${Y}, ${N}]`).else();w.if(A,()=>{if(w.assign(W,!0),w.assign(Y,N),H)$.mergeEvaluated(H,X5.Name)})})}}};uT.default=Mn});var nT=b((mT)=>{Object.defineProperty(mT,"__esModule",{value:!0});var Qn=N0(),Bn={keyword:"allOf",schemaType:"array",code($){let{gen:w,schema:X,it:G}=$;if(!Array.isArray(X))throw Error("ajv implementation error");let E=w.name("valid");X.forEach((J,W)=>{if((0,Qn.alwaysValidSchema)(G,J))return;let Y=$.subschema({keyword:"allOf",schemaProp:W},E);$.ok(E),$.mergeEvaluated(Y)})}};mT.default=Bn});var oT=b((iT)=>{Object.defineProperty(iT,"__esModule",{value:!0});var G5=W0(),rT=N0(),Vn={message:({params:$})=>G5.str`must match "${$.ifClause}" schema`,params:({params:$})=>G5._`{failingKeyword: ${$.ifClause}}`},Rn={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Vn,code($){let{gen:w,parentSchema:X,it:G}=$;if(X.then===void 0&&X.else===void 0)(0,rT.checkStrictMode)(G,'"if" without "then" and "else" is ignored');let E=pT(G,"then"),J=pT(G,"else");if(!E&&!J)return;let W=w.let("valid",!0),Y=w.name("_valid");if(A(),$.reset(),E&&J){let U=w.let("ifClause");$.setParams({ifClause:U}),w.if(Y,D("then",U),D("else",U))}else if(E)w.if(Y,D("then"));else w.if((0,G5.not)(Y),D("else"));$.pass(W,()=>$.error(!0));function A(){let U=$.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},Y);$.mergeEvaluated(U)}function D(U,N){return()=>{let H=$.subschema({keyword:U},Y);if(w.assign(W,Y),$.mergeValidEvaluated(H,W),N)w.assign(N,G5._`${U}`);else $.setParams({ifClause:U})}}}};function pT($,w){let X=$.schema[w];return X!==void 0&&!(0,rT.alwaysValidSchema)($,X)}iT.default=Rn});var dT=b((tT)=>{Object.defineProperty(tT,"__esModule",{value:!0});var In=N0(),jn={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:$,parentSchema:w,it:X}){if(w.if===void 0)(0,In.checkStrictMode)(X,`"${$}" without "if" is ignored`)}};tT.default=jn});var sT=b((lT)=>{Object.defineProperty(lT,"__esModule",{value:!0});var qn=uA(),Sn=OT(),Zn=cA(),bn=LT(),kn=MT(),Cn=RT(),vn=jT(),_n=nA(),fn=bT(),xn=fT(),yn=yT(),gn=hT(),hn=cT(),un=nT(),cn=oT(),mn=dT();function nn($=!1){let w=[yn.default,gn.default,hn.default,un.default,cn.default,mn.default,vn.default,_n.default,Cn.default,fn.default,xn.default];if($)w.push(Sn.default,bn.default);else w.push(qn.default,Zn.default);return w.push(kn.default),w}lT.default=nn});var eT=b((aT)=>{Object.defineProperty(aT,"__esModule",{value:!0});var e0=W0(),rn={message:({schemaCode:$})=>e0.str`must match format "${$}"`,params:({schemaCode:$})=>e0._`{format: ${$}}`},on={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:rn,code($,w){let{gen:X,data:G,$data:E,schema:J,schemaCode:W,it:Y}=$,{opts:A,errSchemaPath:D,schemaEnv:U,self:N}=Y;if(!A.validateFormats)return;if(E)H();else L();function H(){let F=X.scopeValue("formats",{ref:N.formats,code:A.code.formats}),M=X.const("fDef",e0._`${F}[${W}]`),z=X.let("fType"),Q=X.let("format");X.if(e0._`typeof ${M} == "object" && !(${M} instanceof RegExp)`,()=>X.assign(z,e0._`${M}.type || "string"`).assign(Q,e0._`${M}.validate`),()=>X.assign(z,e0._`"string"`).assign(Q,M)),$.fail$data((0,e0.or)(R(),T()));function R(){if(A.strictSchema===!1)return e0.nil;return e0._`${W} && !${Q}`}function T(){let v=U.$async?e0._`(${M}.async ? await ${Q}(${G}) : ${Q}(${G}))`:e0._`${Q}(${G})`,f=e0._`(typeof ${Q} == "function" ? ${v} : ${Q}.test(${G}))`;return e0._`${Q} && ${Q} !== true && ${z} === ${w} && !${f}`}}function L(){let F=N.formats[J];if(!F){R();return}if(F===!0)return;let[M,z,Q]=T(F);if(M===w)$.pass(v());function R(){if(A.strictSchema===!1){N.logger.warn(f());return}throw Error(f());function f(){return`unknown format "${J}" ignored in schema at path "${D}"`}}function T(f){let k=f instanceof RegExp?(0,e0.regexpCode)(f):A.code.formats?e0._`${A.code.formats}${(0,e0.getProperty)(J)}`:void 0,m=X.scopeValue("formats",{key:J,ref:f,code:k});if(typeof f=="object"&&!(f instanceof RegExp))return[f.type||"string",f.validate,e0._`${m}.validate`];return["string",f,m]}function v(){if(typeof F=="object"&&!(F instanceof RegExp)&&F.async){if(!U.$async)throw Error("async format in sync schema");return e0._`await ${Q}(${G})`}return typeof z=="function"?e0._`${Q}(${G})`:e0._`${Q}.test(${G})`}}}};aT.default=on});var wI=b(($I)=>{Object.defineProperty($I,"__esModule",{value:!0});var dn=eT(),ln=[dn.default];$I.default=ln});var EI=b((XI)=>{Object.defineProperty(XI,"__esModule",{value:!0});XI.contentVocabulary=XI.metadataVocabulary=void 0;XI.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];XI.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var YI=b((WI)=>{Object.defineProperty(WI,"__esModule",{value:!0});var en=ZR(),$p=XT(),wp=sT(),Xp=wI(),JI=EI(),Gp=[en.default,$p.default,(0,wp.default)(),Xp.default,JI.metadataVocabulary,JI.contentVocabulary];WI.default=Gp});var OI=b((DI)=>{Object.defineProperty(DI,"__esModule",{value:!0});DI.DiscrError=void 0;var AI;(function($){$.Tag="tag",$.Mapping="mapping"})(AI||(DI.DiscrError=AI={}))});var LI=b((HI)=>{Object.defineProperty(HI,"__esModule",{value:!0});var hG=W0(),rA=OI(),NI=h8(),Jp=bE(),Wp=N0(),Yp={message:({params:{discrError:$,tagName:w}})=>$===rA.DiscrError.Tag?`tag "${w}" must be string`:`value of tag "${w}" must be in oneOf`,params:({params:{discrError:$,tag:w,tagName:X}})=>hG._`{error: ${$}, tag: ${X}, tagValue: ${w}}`},Ap={keyword:"discriminator",type:"object",schemaType:"object",error:Yp,code($){let{gen:w,data:X,schema:G,parentSchema:E,it:J}=$,{oneOf:W}=E;if(!J.opts.discriminator)throw Error("discriminator: requires discriminator option");let Y=G.propertyName;if(typeof Y!="string")throw Error("discriminator: requires propertyName");if(G.mapping)throw Error("discriminator: mapping is not supported");if(!W)throw Error("discriminator: requires oneOf keyword");let A=w.let("valid",!1),D=w.const("tag",hG._`${X}${(0,hG.getProperty)(Y)}`);w.if(hG._`typeof ${D} == "string"`,()=>U(),()=>$.error(!1,{discrError:rA.DiscrError.Tag,tag:D,tagName:Y})),$.ok(A);function U(){let L=H();w.if(!1);for(let F in L)w.elseIf(hG._`${D} === ${F}`),w.assign(A,N(L[F]));w.else(),$.error(!1,{discrError:rA.DiscrError.Mapping,tag:D,tagName:Y}),w.endIf()}function N(L){let F=w.name("valid"),M=$.subschema({keyword:"oneOf",schemaProp:L},F);return $.mergeEvaluated(M,hG.Name),F}function H(){var L;let F={},M=Q(E),z=!0;for(let v=0;v<W.length;v++){let f=W[v];if((f===null||f===void 0?void 0:f.$ref)&&!(0,Wp.schemaHasRulesButRef)(f,J.self.RULES)){let m=f.$ref;if(f=NI.resolveRef.call(J.self,J.schemaEnv.root,J.baseId,m),f instanceof NI.SchemaEnv)f=f.schema;if(f===void 0)throw new Jp.default(J.opts.uriResolver,J.baseId,m)}let k=(L=f===null||f===void 0?void 0:f.properties)===null||L===void 0?void 0:L[Y];if(typeof k!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${Y}"`);z=z&&(M||Q(f)),R(k,v)}if(!z)throw Error(`discriminator: "${Y}" must be required`);return F;function Q({required:v}){return Array.isArray(v)&&v.includes(Y)}function R(v,f){if(v.const)T(v.const,f);else if(v.enum)for(let k of v.enum)T(k,f);else throw Error(`discriminator: "properties/${Y}" must have "const" or "enum"`)}function T(v,f){if(typeof v!="string"||v in F)throw Error(`discriminator: "${Y}" values must be unique strings`);F[v]=f}}}};HI.default=Ap});var FI=b(($90,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 oA=b((t$,iA)=>{Object.defineProperty(t$,"__esModule",{value:!0});t$.MissingRefError=t$.ValidationError=t$.CodeGen=t$.Name=t$.nil=t$.stringify=t$.str=t$._=t$.KeywordCxt=t$.Ajv=void 0;var Op=BR(),Np=YI(),Hp=LI(),MI=FI(),Lp=["/properties"],E5="http://json-schema.org/draft-07/schema";class mE extends Op.default{_addVocabularies(){if(super._addVocabularies(),Np.default.forEach(($)=>this.addVocabulary($)),this.opts.discriminator)this.addKeyword(Hp.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let $=this.opts.$data?this.$dataMetaSchema(MI,Lp):MI;this.addMetaSchema($,E5,!1),this.refs["http://json-schema.org/schema"]=E5}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(E5)?E5:void 0)}}t$.Ajv=mE;iA.exports=t$=mE;iA.exports.Ajv=mE;Object.defineProperty(t$,"__esModule",{value:!0});t$.default=mE;var Fp=ZE();Object.defineProperty(t$,"KeywordCxt",{enumerable:!0,get:function(){return Fp.KeywordCxt}});var uG=W0();Object.defineProperty(t$,"_",{enumerable:!0,get:function(){return uG._}});Object.defineProperty(t$,"str",{enumerable:!0,get:function(){return uG.str}});Object.defineProperty(t$,"stringify",{enumerable:!0,get:function(){return uG.stringify}});Object.defineProperty(t$,"nil",{enumerable:!0,get:function(){return uG.nil}});Object.defineProperty(t$,"Name",{enumerable:!0,get:function(){return uG.Name}});Object.defineProperty(t$,"CodeGen",{enumerable:!0,get:function(){return uG.CodeGen}});var Mp=y8();Object.defineProperty(t$,"ValidationError",{enumerable:!0,get:function(){return Mp.default}});var zp=bE();Object.defineProperty(t$,"MissingRefError",{enumerable:!0,get:function(){return zp.default}})});var PI=b((II)=>{Object.defineProperty(II,"__esModule",{value:!0});II.formatNames=II.fastFormats=II.fullFormats=void 0;function a1($,w){return{validate:$,compare:w}}II.fullFormats={date:a1(KI,sA),time:a1(dA(!0),aA),"date-time":a1(zI(!0),RI),"iso-time":a1(dA(),VI),"iso-date-time":a1(zI(),TI),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:jp,"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:Cp,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:Pp,int32:{type:"number",validate:Zp},int64:{type:"number",validate:bp},float:{type:"number",validate:BI},double:{type:"number",validate:BI},password:!0,binary:!0};II.fastFormats={...II.fullFormats,date:a1(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,sA),time:a1(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,aA),"date-time":a1(/^\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,RI),"iso-time":a1(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,VI),"iso-date-time":a1(/^\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,TI),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};II.formatNames=Object.keys(II.fullFormats);function Kp($){return $%4===0&&($%100!==0||$%400===0)}var Vp=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Rp=[0,31,28,31,30,31,30,31,31,30,31,30,31];function KI($){let w=Vp.exec($);if(!w)return!1;let X=+w[1],G=+w[2],E=+w[3];return G>=1&&G<=12&&E>=1&&E<=(G===2&&Kp(X)?29:Rp[G])}function sA($,w){if(!($&&w))return;if($>w)return 1;if($<w)return-1;return 0}var tA=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function dA($){return function(X){let G=tA.exec(X);if(!G)return!1;let E=+G[1],J=+G[2],W=+G[3],Y=G[4],A=G[5]==="-"?-1:1,D=+(G[6]||0),U=+(G[7]||0);if(D>23||U>59||$&&!Y)return!1;if(E<=23&&J<=59&&W<60)return!0;let N=J-U*A,H=E-D*A-(N<0?1:0);return(H===23||H===-1)&&(N===59||N===-1)&&W<61}}function aA($,w){if(!($&&w))return;let X=new Date("2020-01-01T"+$).valueOf(),G=new Date("2020-01-01T"+w).valueOf();if(!(X&&G))return;return X-G}function VI($,w){if(!($&&w))return;let X=tA.exec($),G=tA.exec(w);if(!(X&&G))return;if($=X[1]+X[2]+X[3],w=G[1]+G[2]+G[3],$>w)return 1;if($<w)return-1;return 0}var lA=/t|\s/i;function zI($){let w=dA($);return function(G){let E=G.split(lA);return E.length===2&&KI(E[0])&&w(E[1])}}function RI($,w){if(!($&&w))return;let X=new Date($).valueOf(),G=new Date(w).valueOf();if(!(X&&G))return;return X-G}function TI($,w){if(!($&&w))return;let[X,G]=$.split(lA),[E,J]=w.split(lA),W=sA(X,E);if(W===void 0)return;return W||aA(G,J)}var Tp=/\/|:/,Ip=/^(?:[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 jp($){return Tp.test($)&&Ip.test($)}var QI=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function Pp($){return QI.lastIndex=0,QI.test($)}var qp=-2147483648,Sp=2147483647;function Zp($){return Number.isInteger($)&&$<=Sp&&$>=qp}function bp($){return Number.isInteger($)}function BI(){return!0}var kp=/[^\\]\\Z/;function Cp($){if(kp.test($))return!1;try{return new RegExp($),!0}catch(w){return!1}}});var SI=b((qI)=>{Object.defineProperty(qI,"__esModule",{value:!0});qI.formatLimitDefinition=void 0;var _p=oA(),y1=W0(),tw=y1.operators,J5={formatMaximum:{okStr:"<=",ok:tw.LTE,fail:tw.GT},formatMinimum:{okStr:">=",ok:tw.GTE,fail:tw.LT},formatExclusiveMaximum:{okStr:"<",ok:tw.LT,fail:tw.GTE},formatExclusiveMinimum:{okStr:">",ok:tw.GT,fail:tw.LTE}},fp={message:({keyword:$,schemaCode:w})=>y1.str`should be ${J5[$].okStr} ${w}`,params:({keyword:$,schemaCode:w})=>y1._`{comparison: ${J5[$].okStr}, limit: ${w}}`};qI.formatLimitDefinition={keyword:Object.keys(J5),type:"string",schemaType:"string",$data:!0,error:fp,code($){let{gen:w,data:X,schemaCode:G,keyword:E,it:J}=$,{opts:W,self:Y}=J;if(!W.validateFormats)return;let A=new _p.KeywordCxt(J,Y.RULES.all.format.definition,"format");if(A.$data)D();else U();function D(){let H=w.scopeValue("formats",{ref:Y.formats,code:W.code.formats}),L=w.const("fmt",y1._`${H}[${A.schemaCode}]`);$.fail$data((0,y1.or)(y1._`typeof ${L} != "object"`,y1._`${L} instanceof RegExp`,y1._`typeof ${L}.compare != "function"`,N(L)))}function U(){let H=A.schema,L=Y.formats[H];if(!L||L===!0)return;if(typeof L!="object"||L instanceof RegExp||typeof L.compare!="function")throw Error(`"${E}": format "${H}" does not define "compare" function`);let F=w.scopeValue("formats",{key:H,ref:L,code:W.code.formats?y1._`${W.code.formats}${(0,y1.getProperty)(H)}`:void 0});$.fail$data(N(F))}function N(H){return y1._`${H}.compare(${X}, ${G}) ${J5[E].fail} 0`}},dependencies:["format"]};var xp=($)=>{return $.addKeyword(qI.formatLimitDefinition),$};qI.default=xp});var CI=b((nE,kI)=>{Object.defineProperty(nE,"__esModule",{value:!0});var cG=PI(),gp=SI(),wD=W0(),ZI=new wD.Name("fullFormats"),hp=new wD.Name("fastFormats"),XD=($,w={keywords:!0})=>{if(Array.isArray(w))return bI($,w,cG.fullFormats,ZI),$;let[X,G]=w.mode==="fast"?[cG.fastFormats,hp]:[cG.fullFormats,ZI],E=w.formats||cG.formatNames;if(bI($,E,X,G),w.keywords)(0,gp.default)($);return $};XD.get=($,w="full")=>{let G=(w==="fast"?cG.fastFormats:cG.fullFormats)[$];if(!G)throw Error(`Unknown format "${$}"`);return G};function bI($,w,X,G){var E,J;(E=(J=$.opts.code).formats)!==null&&E!==void 0||(J.formats=wD._`require("ajv-formats/dist/formats").${G}`);for(let W of w)$.addFormat(W,X[W])}kI.exports=nE=XD;Object.defineProperty(nE,"__esModule",{value:!0});nE.default=XD});function up(){let $=new vI.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return _I.default($),$}class GD{constructor($){this._ajv=$??up()}getValidator($){let w="$id"in $&&typeof $.$id==="string"?this._ajv.getSchema($.$id)??this._ajv.compile($):this._ajv.compile($);return(X)=>{if(w(X))return{valid:!0,data:X,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(w.errors)}}}}var vI,_I;var fI=B(()=>{vI=pE(oA(),1),_I=pE(CI(),1)});class ED{constructor($){this._server=$}requestStream($,w,X){return this._server.requestStream($,w,X)}createMessageStream($,w){let X=this._server.getClientCapabilities();if(($.tools||$.toolChoice)&&!X?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if($.messages.length>0){let G=$.messages[$.messages.length-1],E=Array.isArray(G.content)?G.content:[G.content],J=E.some((D)=>D.type==="tool_result"),W=$.messages.length>1?$.messages[$.messages.length-2]:void 0,Y=W?Array.isArray(W.content)?W.content:[W.content]:[],A=Y.some((D)=>D.type==="tool_use");if(J){if(E.some((D)=>D.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!A)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(A){let D=new Set(Y.filter((N)=>N.type==="tool_use").map((N)=>N.id)),U=new Set(E.filter((N)=>N.type==="tool_result").map((N)=>N.toolUseId));if(D.size!==U.size||![...D].every((N)=>U.has(N)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:$},BE,w)}elicitInputStream($,w){let X=this._server.getClientCapabilities(),G=$.mode??"form";switch(G){case"url":{if(!X?.elicitation?.url)throw Error("Client does not support url elicitation.");break}case"form":{if(!X?.elicitation?.form)throw Error("Client does not support form elicitation.");break}}let E=G==="form"&&$.mode===void 0?{...$,mode:"form"}:$;return this.requestStream({method:"elicitation/create",params:E},SG,w)}async getTask($,w){return this._server.getTask({taskId:$},w)}async getTaskResult($,w,X){return this._server.getTaskResult({taskId:$},w,X)}async listTasks($,w){return this._server.listTasks($?{cursor:$}:void 0,w)}async cancelTask($,w){return this._server.cancelTask({taskId:$},w)}}var xI=B(()=>{ZG()});function yI($,w,X){if(!$)throw Error(`${X} does not support task creation (required for ${w})`);switch(w){case"tools/call":if(!$.tools?.call)throw Error(`${X} does not support task creation for tools/call (required for ${w})`);break;default:break}}function gI($,w,X){if(!$)throw Error(`${X} does not support task creation (required for ${w})`);switch(w){case"sampling/createMessage":if(!$.sampling?.createMessage)throw Error(`${X} does not support task creation for sampling/createMessage (required for ${w})`);break;case"elicitation/create":if(!$.elicitation?.create)throw Error(`${X} does not support task creation for elicitation/create (required for ${w})`);break;default:break}}var JD;var hI=B(()=>{XK();ZG();fI();w8();xI();JD=class JD extends eY{constructor($,w){super(w);if(this._serverInfo=$,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(QE.options.map((X,G)=>[X,G])),this.isMessageIgnored=(X,G)=>{let E=this._loggingLevels.get(G);return E?this.LOG_LEVEL_SEVERITY.get(X)<this.LOG_LEVEL_SEVERITY.get(E):!1},this._capabilities=w?.capabilities??{},this._instructions=w?.instructions,this._jsonSchemaValidator=w?.jsonSchemaValidator??new GD,this.setRequestHandler(MY,(X)=>this._oninitialize(X)),this.setNotificationHandler(zY,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(jY,async(X,G)=>{let E=G.sessionId||G.requestInfo?.headers["mcp-session-id"]||void 0,{level:J}=X.params,W=QE.safeParse(J);if(W.success)this._loggingLevels.set(E,W.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new ED(this)};return this._experimental}registerCapabilities($){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=wK(this._capabilities,$)}setRequestHandler($,w){let G=$8($)?.method;if(!G)throw Error("Schema is missing a method literal");let E;if(IG(G)){let W=G;E=W._zod?.def?.value??W.value}else{let W=G;E=W._def?.value??W.value}if(typeof E!=="string")throw Error("Schema method literal must be a string");if(E==="tools/call"){let W=async(Y,A)=>{let D=hw(zE,Y);if(!D.success){let L=D.error instanceof Error?D.error.message:String(D.error);throw new G0(D0.InvalidParams,`Invalid tools/call request: ${L}`)}let{params:U}=D.data,N=await Promise.resolve(w(Y,A));if(U.task){let L=hw(PG,N);if(!L.success){let F=L.error instanceof Error?L.error.message:String(L.error);throw new G0(D0.InvalidParams,`Invalid task creation result: ${F}`)}return L.data}let H=hw(z8,N);if(!H.success){let L=H.error instanceof Error?H.error.message:String(H.error);throw new G0(D0.InvalidParams,`Invalid tools/call result: ${L}`)}return H.data};return super.setRequestHandler($,W)}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($){gI(this._clientCapabilities?.tasks?.requests,$,"Client")}assertTaskHandlerCapability($){if(!this._capabilities)return;yI(this._capabilities.tasks?.requests,$,"Server")}async _oninitialize($){let w=$.params.protocolVersion;return this._clientCapabilities=$.params.capabilities,this._clientVersion=$.params.clientInfo,{protocolVersion:_B.includes(w)?w:OY,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"},Y8)}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 X=$.messages[$.messages.length-1],G=Array.isArray(X.content)?X.content:[X.content],E=G.some((A)=>A.type==="tool_result"),J=$.messages.length>1?$.messages[$.messages.length-2]:void 0,W=J?Array.isArray(J.content)?J.content:[J.content]:[],Y=W.some((A)=>A.type==="tool_use");if(E){if(G.some((A)=>A.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!Y)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(Y){let A=new Set(W.filter((U)=>U.type==="tool_use").map((U)=>U.id)),D=new Set(G.filter((U)=>U.type==="tool_result").map((U)=>U.toolUseId));if(A.size!==D.size||![...A].every((U)=>D.has(U)))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:$},PY,w);return this.request({method:"sampling/createMessage",params:$},BE,w)}async elicitInput($,w){switch($.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let G=$;return this.request({method:"elicitation/create",params:G},SG,w)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let G=$.mode==="form"?$:{...$,mode:"form"},E=await this.request({method:"elicitation/create",params:G},SG,w);if(E.action==="accept"&&E.content&&G.requestedSchema)try{let W=this._jsonSchemaValidator.getValidator(G.requestedSchema)(E.content);if(!W.valid)throw new G0(D0.InvalidParams,`Elicitation response content does not match requested schema: ${W.errorMessage}`)}catch(J){if(J instanceof G0)throw J;throw new G0(D0.InternalError,`Error validating elicitation response: ${J instanceof Error?J.message:String(J)}`)}return E}}}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:$},qY,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 WD{append($){this._buffer=this._buffer?Buffer.concat([this._buffer,$]):$}readMessage(){if(!this._buffer)return null;let $=this._buffer.indexOf(`
|
|
499
|
-
`);if($===-1)return null;let w=this._buffer.toString("utf8",0,$).replace(/\r$/,"");return this._buffer=this._buffer.subarray($+1),
|
|
500
|
-
`}var cI=B(()=>{ZG()});import mI from"process";class YD{constructor($=mI.stdin,w=mI.stdout){this._stdin=$,this._stdout=w,this._readBuffer=new WD,this._started=!1,this._ondata=(X)=>{this._readBuffer.append(X),this.processReadBuffer()},this._onerror=(X)=>{this.onerror?.(X)}}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 X=uI($);if(this._stdout.write(X))w();else this._stdout.once("drain",w)})}}var nI=B(()=>{cI()});function mG($){let w=$._def,X=w.typeName;if(X==="ZodObject"){let G=w.shape(),E={},J=[];for(let[W,Y]of Object.entries(G)){E[W]=mG(Y);let A=Y._def;if(A.typeName!=="ZodOptional"&&A.typeName!=="ZodDefault")J.push(W)}return{type:"object",properties:E,...J.length?{required:J}:{}}}if(X==="ZodString")return{type:"string"};if(X==="ZodNumber")return{type:"number"};if(X==="ZodBoolean")return{type:"boolean"};if(X==="ZodArray")return{type:"array",items:mG(w.type)};if(X==="ZodEnum")return{type:"string",enum:w.values};if(X==="ZodOptional"||X==="ZodDefault")return mG(w.innerType);if(X==="ZodUnion")return{oneOf:w.options.map(mG)};return{}}function pI(){let $=new JD({name:"orc",version:"0.0.1"},{capabilities:{tools:{}}});return $.setRequestHandler(IY,async()=>({tools:MG.map((w)=>({name:w.name,description:w.description,inputSchema:mG(w.inputSchema)}))})),$.setRequestHandler(zE,async(w)=>{let{name:X,arguments:G}=w.params;AD.debug(`Tool call: ${X}`,G);try{let E=MG.find((Y)=>Y.name===X);if(!E)return{content:[{type:"text",text:`Unknown tool: ${X}`}],isError:!0};let J=E.inputSchema.safeParse(G??{});if(!J.success)return{content:[{type:"text",text:`Invalid args: ${J.error.message}`}],isError:!0};return{content:[{type:"text",text:await o6(X,J.data)}]}}catch(E){return AD.error(`Tool error: ${X}`,E),{content:[{type:"text",text:E instanceof Error?E.message:"Unknown error"}],isError:!0}}}),$}async function mp(){let $=pI(),w=new YD;await $.connect(w),AD.info("MCP server running on stdio")}var AD;var rI=B(()=>{hI();nI();ZG();f$();SJ();AD=P0("mcp")});var iI={};e1(iI,{toolDefinitions:()=>MG,startStdioServer:()=>mp,executeTool:()=>o6,createMcpServer:()=>pI});var oI=B(async()=>{rI();SJ()});d$();import{existsSync as np,statSync as pp}from"fs";var tD=pE(oD(),1),{program:br,createCommand:kr,createArgument:Cr,createOption:vr,CommanderError:_r,InvalidArgumentError:fr,InvalidOptionArgumentError:xr,Command:V$,Argument:yr,Option:gr,Help:hr}=tD.default;d$();HW();import{mkdirSync as Av,readFileSync as Dv,writeFileSync as Uv}from"fs";import{homedir as Ov}from"os";import{join as xJ}from"path";bw();f$();c$();u$();function I$($,w,X,G,E,J,W,Y){return I$.fromTZ(I$.tp($,w,X,G,E,J,W),Y)}I$.fromTZISO=($,w,X)=>I$.fromTZ(Mb($,w),X);I$.fromTZ=function($,w){let X=new Date(Date.UTC($.y,$.m-1,$.d,$.h,$.i,$.s)),G=LW($.tz,X),E=new Date(X.getTime()-G),J=LW($.tz,E);if(J-G===0)return E;{let W=new Date(X.getTime()-J),Y=LW($.tz,W);if(Y-J===0)return W;if(!w&&Y-J>0)return W;if(w)throw Error("Invalid date passed to fromTZ()");return E}};I$.toTZ=function($,w){let X=$.toLocaleString("en-US",{timeZone:w}).replace(/[\u202f]/," "),G=new Date(X);return{y:G.getFullYear(),m:G.getMonth()+1,d:G.getDate(),h:G.getHours(),i:G.getMinutes(),s:G.getSeconds(),tz:w}};I$.tp=($,w,X,G,E,J,W)=>({y:$,m:w,d:X,h:G,i:E,s:J,tz:W});function LW($,w=new Date){let X=w.toLocaleString("en-US",{timeZone:$,timeZoneName:"shortOffset"}).split(" ").slice(-1)[0],G=w.toLocaleString("en-US").replace(/[\u202f]/," ");return Date.parse(`${G} GMT`)-Date.parse(`${G} ${X}`)}function Mb($,w){let X=new Date(Date.parse($));if(isNaN(X))throw Error("minitz: Invalid ISO8601 passed to parser.");let G=$.substring(9);return $.includes("Z")||G.includes("-")||G.includes("+")?I$.tp(X.getUTCFullYear(),X.getUTCMonth()+1,X.getUTCDate(),X.getUTCHours(),X.getUTCMinutes(),X.getUTCSeconds(),"Etc/UTC"):I$.tp(X.getFullYear(),X.getMonth()+1,X.getDate(),X.getHours(),X.getMinutes(),X.getSeconds(),w)}I$.minitz=I$;var FW=32,Z6=31|FW,TL=[1,2,4,8,16],KL=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 Y1(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,Z6),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray($,w,X,G){let E=this[$],J=$==="day"&&this.lastDayOfMonth;if(w===""&&!J)throw TypeError("CronPattern: configuration entry "+$+" ("+w+") is empty, check for trailing spaces.");if(w==="*")return E.fill(G);let W=w.split(",");if(W.length>1)for(let Y=0;Y<W.length;Y++)this.partToArray($,W[Y],X,G);else w.indexOf("-")!==-1&&w.indexOf("/")!==-1?this.handleRangeWithStepping(w,$,X,G):w.indexOf("-")!==-1?this.handleRange(w,$,X,G):w.indexOf("/")!==-1?this.handleStepping(w,$,X,G):w!==""&&this.handleNumber(w,$,X,G)}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,X,G){let E=this.extractNth($,w),J=parseInt(E[0],10)+X;if(isNaN(J))throw TypeError("CronPattern: "+w+" is not a number: '"+$+"'");this.setPart(w,J,E[1]||G)}setPart($,w,X){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,X);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]=X}handleRangeWithStepping($,w,X,G){let E=this.extractNth($,w),J=E[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(J===null)throw TypeError("CronPattern: Syntax error, illegal range with stepping: '"+$+"'");let[,W,Y,A]=J,D=parseInt(W,10)+X,U=parseInt(Y,10)+X,N=parseInt(A,10);if(isNaN(D))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(U))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN(N))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(N===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(N>this[w].length)throw TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[w].length+")");if(D>U)throw TypeError("CronPattern: From value is larger than to value: '"+$+"'");for(let H=D;H<=U;H+=N)this.setPart(w,H,E[1]||G)}extractNth($,w){let X=$,G;if(X.includes("#")){if(w!=="dayOfWeek")throw Error("CronPattern: nth (#) only allowed in day-of-week field");G=X.split("#")[1],X=X.split("#")[0]}return[X,G]}handleRange($,w,X,G){let E=this.extractNth($,w),J=E[0].split("-");if(J.length!==2)throw TypeError("CronPattern: Syntax error, illegal range: '"+$+"'");let W=parseInt(J[0],10)+X,Y=parseInt(J[1],10)+X;if(isNaN(W))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(Y))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(W>Y)throw TypeError("CronPattern: From value is larger than to value: '"+$+"'");for(let A=W;A<=Y;A++)this.setPart(w,A,E[1]||G)}handleStepping($,w,X,G){let E=this.extractNth($,w),J=E[0].split("/");if(J.length!==2)throw TypeError("CronPattern: Syntax error, illegal stepping: '"+$+"'");J[0]===""&&(J[0]="*");let W=0;J[0]!=="*"&&(W=parseInt(J[0],10)+X);let Y=parseInt(J[1],10);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, max steps for part is ("+this[w].length+")");for(let A=W;A<this[w].length;A+=Y)this.setPart(w,A,E[1]||G)}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[$]|FW;else if(w===Z6)this.dayOfWeek[$]=Z6;else if(w<6&&w>0)this.dayOfWeek[$]=this.dayOfWeek[$]|TL[w-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${w}, Type: ${typeof w}`)}},VL=[31,28,31,30,31,30,31,31,30,31,30,31],Dw=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]],Y1=class ${tz;ms;second;minute;hour;day;month;year;constructor(w,X){if(this.tz=X,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,X,G,E){let J=new Date(Date.UTC(w,X,G)).getUTCDay(),W=0;for(let Y=1;Y<=G;Y++)new Date(Date.UTC(w,X,Y)).getUTCDay()===J&&W++;if(E&Z6&&TL[W-1]&E)return!0;if(E&FW){let Y=new Date(Date.UTC(w,X+1,0)).getUTCDate();for(let A=G+1;A<=Y;A++)if(new Date(Date.UTC(w,X,A)).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 X=I$.toTZ(w,this.tz);this.ms=w.getMilliseconds(),this.second=X.s,this.minute=X.i,this.hour=X.h,this.day=X.d,this.month=X.m-1,this.year=X.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>VL[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 X=I$.fromTZISO(w);this.ms=X.getUTCMilliseconds(),this.second=X.getUTCSeconds(),this.minute=X.getUTCMinutes(),this.hour=X.getUTCHours(),this.day=X.getUTCDate(),this.month=X.getUTCMonth(),this.year=X.getUTCFullYear(),this.apply()}else return this.fromDate(I$.fromTZISO(w,this.tz))}findNext(w,X,G,E){let J=this[X],W;G.lastDayOfMonth&&(this.month!==1?W=VL[this.month]:W=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate());let Y=!G.starDOW&&X=="day"?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let A=this[X]+E;A<G[X].length;A++){let D=G[X][A];if(X==="day"&&G.lastDayOfMonth&&A-E==W&&(D=1),X==="day"&&!G.starDOW){let U=G.dayOfWeek[(Y+(A-E-1))%7];if(U&&U&Z6)U=this.isNthWeekdayOfMonth(this.year,this.month,A-E,U)?1:0;else if(U)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${U}`);w.legacyMode&&!G.starDOM?D=D||U:D=D&&U}if(D)return this[X]=A-E,J!==this[X]?2:1}return 3}recurse(w,X,G){let E=this.findNext(X,Dw[G][0],w,Dw[G][2]);if(E>1){let J=G+1;for(;J<Dw.length;)this[Dw[J][0]]=-Dw[J][2],J++;if(E===3)return this[Dw[G][1]]++,this[Dw[G][0]]=-Dw[G][2],this.apply(),this.recurse(w,X,0);if(this.apply())return this.recurse(w,X,G-1)}return G+=1,G>=Dw.length?this:this.year>=3000?null:this.recurse(w,X,G)}increment(w,X,G){return this.second+=X.interval!==void 0&&X.interval>1&&G?X.interval:1,this.ms=0,this.apply(),this.recurse(w,X,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)):I$.fromTZ(I$.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function zb($){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 Y1($.startAt,$.timezone)),$.stopAt&&($.stopAt=new Y1($.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 S6($){return Object.prototype.toString.call($)==="[object Function]"||typeof $=="function"||$ instanceof Function}function Qb($){return S6($)}function Bb($){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer($):$&&typeof $.unref<"u"&&$.unref()}var RL=30000,GJ=[],IL=class{name;options;_states;fn;constructor($,w,X){let G,E;if(S6(w))E=w;else if(typeof w=="object")G=w;else if(w!==void 0)throw Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");if(S6(X))E=X;else if(typeof X=="object")G=X;else if(X!==void 0)throw Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");if(this.name=G?.name,this.options=zb(G),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:G?G.maxRuns:void 0,paused:G?G.paused:!1,pattern:new KL("* * * * *")},$&&($ instanceof Date||typeof $=="string"&&$.indexOf(":")>0)?this._states.once=new Y1($,this.options.timezone||this.options.utcOffset):this._states.pattern=new KL($,this.options.timezone),this.name){if(GJ.find((J)=>J.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");GJ.push(this)}return E!==void 0&&Qb(E)&&(this.fn=E,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 X=[],G=w||this._states.currentRun||void 0;for(;$--&&(G=this.nextRun(G));)X.push(G);return X}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let $=this.nextRun(this._states.currentRun),w=!this._states.paused,X=this.fn!==void 0,G=!this._states.kill;return w&&X&&G&&$!==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 Y1||$ instanceof Date?w.getTime()-$.getTime():w.getTime()-new Y1($).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let $=GJ.indexOf(this);$>=0&&GJ.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(),X=this.nextRun(this._states.currentRun);return w==null||isNaN(w)||X===null?this:(w>RL&&(w=RL),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(X),w),this._states.currentTimeout&&this.options.unref&&Bb(this._states.currentTimeout),this)}async _trigger($){if(this._states.blocking=!0,this._states.currentRun=new Y1(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){S6(this.options.catch)&&this.options.catch(w,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new Y1($,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,X=!this._states.paused&&w.getTime()>=$.getTime(),G=this._states.blocking&&this.options.protect;X&&!G?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):X&&G&&S6(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next($){let w=!!($||this._states.currentRun),X=!1;!$&&this.options.startAt&&this.options.interval&&([$,w]=this._calculatePreviousRun($,w),X=!$),$=new Y1($,this.options.timezone||this.options.utcOffset),this.options.startAt&&$&&$.getTime()<this.options.startAt.getTime()&&($=this.options.startAt);let G=this._states.once||new Y1($,this.options.timezone||this.options.utcOffset);return!X&&G!==this._states.once&&(G=G.increment(this._states.pattern,this.options,w)),this._states.once&&this._states.once.getTime()<=$.getTime()||G===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&G.getTime()>=this.options.stopAt.getTime()?null:G}_calculatePreviousRun($,w){let X=new Y1(void 0,this.options.timezone||this.options.utcOffset),G=$;if(this.options.startAt.getTime()<=X.getTime()){G=this.options.startAt;let E=G.getTime()+this.options.interval*1000;for(;E<=X.getTime();)G=new Y1(G,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),E=G.getTime()+this.options.interval*1000;w=!0}return G===null&&(G=void 0),[G,w]}};g$();bw();var Uw=P0("runner:scheduler"),WG=new Map,Cw=new Map;async function jL(){let w=await g().query.jobs.findMany({where:S(d0.enabled,!0)}),X=new Set(["cron","one-shot","watch","webhook","manual","bridge-msg"]),G=w.filter((E)=>!X.has(E.trigger_type));if(G.length>0)Uw.warn(`${G.length} job(s) have an unsupported trigger type and will not fire: ${G.map((E)=>`${E.name} (${E.trigger_type})`).join(", ")}. Use 'cron' with a 6-field expression (e.g. '*/30 * * * * *') for sub-minute intervals.`);for(let E of w)if(E.trigger_type==="cron"&&E.cron_expr)Kb(E.id,E.name,E.cron_expr);else if(E.trigger_type==="one-shot"&&E.run_at)Vb(E.id,E.name,E.run_at,E.run_count);Uw.info(`Scheduler started. ${WG.size} cron + ${Cw.size} one-shot jobs scheduled.`)}function Kb($,w,X){if(WG.has($))WG.get($)?.stop();let G=new IL(X,async()=>{Uw.info(`Cron trigger: ${w}`);try{await $1({jobId:$,triggerBy:"cron"})}catch(E){Uw.error(`Cron job failed: ${w}`,E)}});WG.set($,G),Uw.info(`Scheduled cron job: ${w} (${X})`)}function Vb($,w,X,G){if(G>0)return;if(Cw.has($))clearTimeout(Cw.get($)),Cw.delete($);let E=Math.max(0,X.getTime()-Date.now()),J=setTimeout(async()=>{Cw.delete($),Uw.info(`One-shot trigger: ${w}`);try{await $1({jobId:$,triggerBy:"one-shot"})}catch(Y){Uw.error(`One-shot job failed: ${w}`,Y)}},E);Cw.set($,J);let W=E<1000?"now":`in ${Math.round(E/1000)}s`;Uw.info(`Scheduled one-shot job: ${w} (${W})`)}function PL(){for(let[,$]of WG)$.stop();WG.clear();for(let[,$]of Cw)clearTimeout($);Cw.clear(),Uw.info("Scheduler stopped.")}f$();c$();u$();import{stat as sb}from"fs";import{stat as ab,readdir as eb}from"fs/promises";import{EventEmitter as $k}from"events";import*as A0 from"path";import{stat as Rb,lstat as qL,readdir as Tb,realpath as Ib}from"fs/promises";import{Readable as jb}from"stream";import{resolve as SL,relative as Pb,join as qb,sep as Sb}from"path";var w1={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},MW={root:".",fileFilter:($)=>!0,directoryFilter:($)=>!0,type:w1.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(MW);var CL="READDIRP_RECURSIVE_ERROR",Zb=new Set(["ENOENT","EPERM","EACCES","ELOOP",CL]),ZL=[w1.DIR_TYPE,w1.EVERYTHING_TYPE,w1.FILE_DIR_TYPE,w1.FILE_TYPE],bb=new Set([w1.DIR_TYPE,w1.EVERYTHING_TYPE,w1.FILE_DIR_TYPE]),kb=new Set([w1.EVERYTHING_TYPE,w1.FILE_DIR_TYPE,w1.FILE_TYPE]),Cb=($)=>Zb.has($.code),vb=process.platform==="win32",bL=($)=>!0,kL=($)=>{if($===void 0)return bL;if(typeof $==="function")return $;if(typeof $==="string"){let w=$.trim();return(X)=>X.basename===w}if(Array.isArray($)){let w=$.map((X)=>X.trim());return(X)=>w.some((G)=>X.basename===G)}return bL};class vL extends jb{constructor($={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:$.highWaterMark});let w={...MW,...$},{root:X,type:G}=w;this._fileFilter=kL(w.fileFilter),this._directoryFilter=kL(w.directoryFilter);let E=w.lstat?qL:Rb;if(vb)this._stat=(J)=>E(J,{bigint:!0});else this._stat=E;this._maxDepth=w.depth??MW.depth,this._wantsDir=G?bb.has(G):!1,this._wantsFile=G?kb.has(G):!1,this._wantsEverything=G===w1.EVERYTHING_TYPE,this._root=SL(X),this._isDirent=!w.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(X,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,X=w&&w.files;if(X&&X.length>0){let{path:G,depth:E}=w,J=X.splice(0,$).map((Y)=>this._formatEntry(Y,G)),W=await Promise.all(J);for(let Y of W){if(!Y)continue;if(this.destroyed)return;let A=await this._getEntryType(Y);if(A==="directory"&&this._directoryFilter(Y)){if(E<=this._maxDepth)this.parents.push(this._exploreDir(Y.fullPath,E+1));if(this._wantsDir)this.push(Y),$--}else if((A==="file"||this._includeAsFile(Y))&&this._fileFilter(Y)){if(this._wantsFile)this.push(Y),$--}}}else{let G=this.parents.pop();if(!G){this.push(null);break}if(this.parent=await G,this.destroyed)return}}}catch(w){this.destroy(w)}finally{this.reading=!1}}async _exploreDir($,w){let X;try{X=await Tb($,this._rdOptions)}catch(G){this._onError(G)}return{files:X,depth:w,path:$}}async _formatEntry($,w){let X,G=this._isDirent?$.name:$;try{let E=SL(qb(w,G));X={path:Pb(this._root,E),fullPath:E,basename:G},X[this._statsProp]=this._isDirent?$:await this._stat(E)}catch(E){this._onError(E);return}return X}_onError($){if(Cb($)&&!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 X=$.fullPath;try{let G=await Ib(X),E=await qL(G);if(E.isFile())return"file";if(E.isDirectory()){let J=G.length;if(X.startsWith(G)&&X.substr(J,1)===Sb){let W=Error(`Circular symlink detected: "${X}" points to "${G}"`);return W.code=CL,this._onError(W)}return"directory"}}catch(G){return this._onError(G),""}}}_includeAsFile($){let w=$&&$[this._statsProp];return w&&this._wantsEverything&&!w.isDirectory()}}function _L($,w={}){let X=w.entryType||w.type;if(X==="both")X=w1.FILE_DIR_TYPE;if(X)w.type=X;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(X&&!ZL.includes(X))throw Error(`readdirp: Invalid type passed. Use one of ${ZL.join(", ")}`);return w.root=$,new vL(w)}import{watchFile as _b,unwatchFile as fL,watch as fb}from"fs";import{open as xb,stat as yL,lstat as yb,realpath as zW}from"fs/promises";import*as y0 from"path";import{type as gb}from"os";var hb="data",KW="end",gL="close",YJ=()=>{};var AJ=process.platform,VW=AJ==="win32",ub=AJ==="darwin",cb=AJ==="linux",mb=AJ==="freebsd",hL=gb()==="OS400",k0={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},q1=k0,nb="watch",pb={lstat:yb,stat:yL},UX="listeners",EJ="errHandlers",YG="rawEmitters",rb=[UX,EJ,YG],ib=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"]),ob=($)=>ib.has(y0.extname($).slice(1).toLowerCase()),BW=($,w)=>{if($ instanceof Set)$.forEach(w);else w($)},b6=($,w,X)=>{let G=$[w];if(!(G instanceof Set))$[w]=G=new Set([G]);G.add(X)},tb=($)=>(w)=>{let X=$[w];if(X instanceof Set)X.clear();else delete $[w]},k6=($,w,X)=>{let G=$[w];if(G instanceof Set)G.delete(X);else if(G===X)delete $[w]},uL=($)=>$ instanceof Set?$.size===0:!$,JJ=new Map;function xL($,w,X,G,E){let J=(W,Y)=>{if(X($),E(W,Y,{watchedPath:$}),Y&&$!==Y)WJ(y0.resolve($,Y),UX,y0.join($,Y))};try{return fb($,{persistent:w.persistent},J)}catch(W){G(W);return}}var WJ=($,w,X,G,E)=>{let J=JJ.get($);if(!J)return;BW(J[w],(W)=>{W(X,G,E)})},db=($,w,X,G)=>{let{listener:E,errHandler:J,rawEmitter:W}=G,Y=JJ.get(w),A;if(!X.persistent){if(A=xL($,X,E,J,W),!A)return;return A.close.bind(A)}if(Y)b6(Y,UX,E),b6(Y,EJ,J),b6(Y,YG,W);else{if(A=xL($,X,WJ.bind(null,w,UX),J,WJ.bind(null,w,YG)),!A)return;A.on(q1.ERROR,async(D)=>{let U=WJ.bind(null,w,EJ);if(Y)Y.watcherUnusable=!0;if(VW&&D.code==="EPERM")try{await(await xb($,"r")).close(),U(D)}catch(N){}else U(D)}),Y={listeners:E,errHandlers:J,rawEmitters:W,watcher:A},JJ.set(w,Y)}return()=>{if(k6(Y,UX,E),k6(Y,EJ,J),k6(Y,YG,W),uL(Y.listeners))Y.watcher.close(),JJ.delete(w),rb.forEach(tb(Y)),Y.watcher=void 0,Object.freeze(Y)}},QW=new Map,lb=($,w,X,G)=>{let{listener:E,rawEmitter:J}=G,W=QW.get(w),Y=W&&W.options;if(Y&&(Y.persistent<X.persistent||Y.interval>X.interval))fL(w),W=void 0;if(W)b6(W,UX,E),b6(W,YG,J);else W={listeners:E,rawEmitters:J,options:X,watcher:_b(w,X,(A,D)=>{BW(W.rawEmitters,(N)=>{N(q1.CHANGE,w,{curr:A,prev:D})});let U=A.mtimeMs;if(A.size!==D.size||U>D.mtimeMs||U===0)BW(W.listeners,(N)=>N($,A))})},QW.set(w,W);return()=>{if(k6(W,UX,E),k6(W,YG,J),uL(W.listeners))QW.delete(w),fL(w),W.options=W.watcher=void 0,Object.freeze(W)}};class RW{constructor($){this.fsw=$,this._boundHandleError=(w)=>$._handleError(w)}_watchWithNodeFs($,w){let X=this.fsw.options,G=y0.dirname($),E=y0.basename($);this.fsw._getWatchedDir(G).add(E);let W=y0.resolve($),Y={persistent:X.persistent};if(!w)w=YJ;let A;if(X.usePolling){let D=X.interval!==X.binaryInterval;Y.interval=D&&ob(E)?X.binaryInterval:X.interval,A=lb($,W,Y,{listener:w,rawEmitter:this.fsw._emitRaw})}else A=db($,W,Y,{listener:w,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return A}_handleFile($,w,X){if(this.fsw.closed)return;let G=y0.dirname($),E=y0.basename($),J=this.fsw._getWatchedDir(G),W=w;if(J.has(E))return;let Y=async(D,U)=>{if(!this.fsw._throttle(nb,$,5))return;if(!U||U.mtimeMs===0)try{let N=await yL($);if(this.fsw.closed)return;let{atimeMs:H,mtimeMs:L}=N;if(!H||H<=L||L!==W.mtimeMs)this.fsw._emit(q1.CHANGE,$,N);if((ub||cb||mb)&&W.ino!==N.ino){this.fsw._closeFile(D),W=N;let F=this._watchWithNodeFs($,Y);if(F)this.fsw._addPathCloser(D,F)}else W=N}catch(N){this.fsw._remove(G,E)}else if(J.has(E)){let{atimeMs:N,mtimeMs:H}=U;if(!N||N<=H||H!==W.mtimeMs)this.fsw._emit(q1.CHANGE,$,U);W=U}},A=this._watchWithNodeFs($,Y);if(!(X&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored($)){if(!this.fsw._throttle(q1.ADD,$,0))return;this.fsw._emit(q1.ADD,$,w)}return A}async _handleSymlink($,w,X,G){if(this.fsw.closed)return;let E=$.fullPath,J=this.fsw._getWatchedDir(w);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let W;try{W=await zW(X)}catch(Y){return this.fsw._emitReady(),!0}if(this.fsw.closed)return;if(J.has(G)){if(this.fsw._symlinkPaths.get(E)!==W)this.fsw._symlinkPaths.set(E,W),this.fsw._emit(q1.CHANGE,X,$.stats)}else J.add(G),this.fsw._symlinkPaths.set(E,W),this.fsw._emit(q1.ADD,X,$.stats);return this.fsw._emitReady(),!0}if(this.fsw._symlinkPaths.has(E))return!0;this.fsw._symlinkPaths.set(E,!0)}_handleRead($,w,X,G,E,J,W){if($=y0.join($,""),W=this.fsw._throttle("readdir",$,1000),!W)return;let Y=this.fsw._getWatchedDir(X.path),A=new Set,D=this.fsw._readdirp($,{fileFilter:(U)=>X.filterPath(U),directoryFilter:(U)=>X.filterDir(U)});if(!D)return;return D.on(hb,async(U)=>{if(this.fsw.closed){D=void 0;return}let N=U.path,H=y0.join($,N);if(A.add(N),U.stats.isSymbolicLink()&&await this._handleSymlink(U,$,H,N))return;if(this.fsw.closed){D=void 0;return}if(N===G||!G&&!Y.has(N))this.fsw._incrReadyCount(),H=y0.join(E,y0.relative(E,H)),this._addToNodeFs(H,w,X,J+1)}).on(q1.ERROR,this._boundHandleError),new Promise((U,N)=>{if(!D)return N();D.once(KW,()=>{if(this.fsw.closed){D=void 0;return}let H=W?W.clear():!1;if(U(void 0),Y.getChildren().filter((L)=>{return L!==$&&!A.has(L)}).forEach((L)=>{this.fsw._remove($,L)}),D=void 0,H)this._handleRead($,!1,X,G,E,J,W)})})}async _handleDir($,w,X,G,E,J,W){let Y=this.fsw._getWatchedDir(y0.dirname($)),A=Y.has(y0.basename($));if(!(X&&this.fsw.options.ignoreInitial)&&!E&&!A)this.fsw._emit(q1.ADD_DIR,$,w);Y.add(y0.basename($)),this.fsw._getWatchedDir($);let D,U,N=this.fsw.options.depth;if((N==null||G<=N)&&!this.fsw._symlinkPaths.has(W)){if(!E){if(await this._handleRead($,X,J,E,$,G,D),this.fsw.closed)return}U=this._watchWithNodeFs($,(H,L)=>{if(L&&L.mtimeMs===0)return;this._handleRead(H,!1,J,E,$,G,D)})}return U}async _addToNodeFs($,w,X,G,E){let J=this.fsw._emitReady;if(this.fsw._isIgnored($)||this.fsw.closed)return J(),!1;let W=this.fsw._getWatchHelpers($);if(X)W.filterPath=(Y)=>X.filterPath(Y),W.filterDir=(Y)=>X.filterDir(Y);try{let Y=await pb[W.statMethod](W.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(W.watchPath,Y))return J(),!1;let A=this.fsw.options.followSymlinks,D;if(Y.isDirectory()){let U=y0.resolve($),N=A?await zW($):$;if(this.fsw.closed)return;if(D=await this._handleDir(W.watchPath,Y,w,G,E,W,N),this.fsw.closed)return;if(U!==N&&N!==void 0)this.fsw._symlinkPaths.set(U,N)}else if(Y.isSymbolicLink()){let U=A?await zW($):$;if(this.fsw.closed)return;let N=y0.dirname(W.watchPath);if(this.fsw._getWatchedDir(N).add(W.watchPath),this.fsw._emit(q1.ADD,W.watchPath,Y),D=await this._handleDir(N,Y,w,G,$,W,U),this.fsw.closed)return;if(U!==void 0)this.fsw._symlinkPaths.set(y0.resolve($),U)}else D=this._handleFile(W.watchPath,Y,w);if(J(),D)this.fsw._addPathCloser($,D);return!1}catch(Y){if(this.fsw._handleError(Y))return J(),$}}}/*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */var TW="/",wk="//",iL=".",Xk="..",Gk="string",Ek=/\\/g,cL=/\/\//,Jk=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Wk=/^\.[/\\]/;function DJ($){return Array.isArray($)?$:[$]}var IW=($)=>typeof $==="object"&&$!==null&&!($ instanceof RegExp);function Yk($){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 X=A0.relative($.path,w);if(!X)return!1;return!X.startsWith("..")&&!A0.isAbsolute(X)}return!1};return()=>!1}function Ak($){if(typeof $!=="string")throw Error("string expected");$=A0.normalize($),$=$.replace(/\\/g,"/");let w=!1;if($.startsWith("//"))w=!0;let X=/\/\//;while($.match(X))$=$.replace(X,"/");if(w)$="/"+$;return $}function mL($,w,X){let G=Ak(w);for(let E=0;E<$.length;E++){let J=$[E];if(J(G,X))return!0}return!1}function Dk($,w){if($==null)throw TypeError("anymatch: specify first argument");let G=DJ($).map((E)=>Yk(E));if(w==null)return(E,J)=>{return mL(G,E,J)};return mL(G,w)}var nL=($)=>{let w=DJ($).flat();if(!w.every((X)=>typeof X===Gk))throw TypeError(`Non-string provided as watch path: ${w}`);return w.map(oL)},pL=($)=>{let w=$.replace(Ek,TW),X=!1;if(w.startsWith(wk))X=!0;while(w.match(cL))w=w.replace(cL,TW);if(X)w=TW+w;return w},oL=($)=>pL(A0.normalize(pL($))),rL=($="")=>(w)=>{if(typeof w==="string")return oL(A0.isAbsolute(w)?w:A0.join($,w));else return w},Uk=($,w)=>{if(A0.isAbsolute($))return $;return A0.join(w,$)},Ok=Object.freeze(new Set);class tL{constructor($,w){this.path=$,this._removeWatcher=w,this.items=new Set}add($){let{items:w}=this;if(!w)return;if($!==iL&&$!==Xk)w.add($)}async remove($){let{items:w}=this;if(!w)return;if(w.delete($),w.size>0)return;let X=this.path;try{await eb(X)}catch(G){if(this._removeWatcher)this._removeWatcher(A0.dirname(X),A0.basename(X))}}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=YJ,this.items=Ok,Object.freeze(this)}}var Nk="stat",Hk="lstat";class dL{constructor($,w,X){this.fsw=X;let G=$;this.path=$=$.replace(Wk,""),this.watchPath=G,this.fullWatchPath=A0.resolve(G),this.dirParts=[],this.dirParts.forEach((E)=>{if(E.length>1)E.pop()}),this.followSymlinks=w,this.statMethod=w?Nk:Hk}entryPath($){return A0.join(this.watchPath,A0.relative(this.watchPath,$.fullPath))}filterPath($){let{stats:w}=$;if(w&&w.isSymbolicLink())return this.filterDir($);let X=this.entryPath($);return this.fsw._isntIgnored(X,w)&&this.fsw._hasReadPermissions(w)}filterDir($){return this.fsw._isntIgnored(this.entryPath($),$.stats)}}class jW extends $k{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,X={stabilityThreshold:2000,pollInterval:100},G={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...$,ignored:$.ignored?DJ($.ignored):DJ([]),awaitWriteFinish:w===!0?X:typeof w==="object"?{...X,...w}:!1};if(hL)G.usePolling=!0;if(G.atomic===void 0)G.atomic=!G.usePolling;let E=process.env.CHOKIDAR_USEPOLLING;if(E!==void 0){let Y=E.toLowerCase();if(Y==="false"||Y==="0")G.usePolling=!1;else if(Y==="true"||Y==="1")G.usePolling=!0;else G.usePolling=!!Y}let J=process.env.CHOKIDAR_INTERVAL;if(J)G.interval=Number.parseInt(J,10);let W=0;this._emitReady=()=>{if(W++,W>=this._readyCount)this._emitReady=YJ,this._readyEmitted=!0,process.nextTick(()=>this.emit(k0.READY))},this._emitRaw=(...Y)=>this.emit(k0.RAW,...Y),this._boundRemove=this._remove.bind(this),this.options=G,this._nodeFsHandler=new RW(this),Object.freeze(G)}_addIgnoredPath($){if(IW($)){for(let w of this._ignoredPaths)if(IW(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(IW(w)&&w.path===$)this._ignoredPaths.delete(w)}}add($,w,X){let{cwd:G}=this.options;this.closed=!1,this._closePromise=void 0;let E=nL($);if(G)E=E.map((J)=>{return Uk(J,G)});if(E.forEach((J)=>{this._removeIgnoredPath(J)}),this._userIgnored=void 0,!this._readyCount)this._readyCount=0;return this._readyCount+=E.length,Promise.all(E.map(async(J)=>{let W=await this._nodeFsHandler._addToNodeFs(J,!X,void 0,0,w);if(W)this._emitReady();return W})).then((J)=>{if(this.closed)return;J.forEach((W)=>{if(W)this.add(A0.dirname(W),A0.basename(w||W))})}),this}unwatch($){if(this.closed)return this;let w=nL($),{cwd:X}=this.options;return w.forEach((G)=>{if(!A0.isAbsolute(G)&&!this._closers.has(G)){if(X)G=A0.join(X,G);G=A0.resolve(G)}if(this._closePath(G),this._addIgnoredPath(G),this._watched.has(G))this._addIgnoredPath({path:G,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((X)=>{let G=X();if(G instanceof Promise)$.push(G)})),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,X)=>{let E=(this.options.cwd?A0.relative(this.options.cwd,X):X)||iL;$[E]=w.getChildren().sort()}),$}emitWithAll($,w){if(this.emit($,...w),$!==k0.ERROR)this.emit(k0.ALL,$,...w)}async _emit($,w,X){if(this.closed)return;let G=this.options;if(VW)w=A0.normalize(w);if(G.cwd)w=A0.relative(G.cwd,w);let E=[w];if(X!=null)E.push(X);let J=G.awaitWriteFinish,W;if(J&&(W=this._pendingWrites.get(w)))return W.lastChange=new Date,this;if(G.atomic){if($===k0.UNLINK)return this._pendingUnlinks.set(w,[$,...E]),setTimeout(()=>{this._pendingUnlinks.forEach((Y,A)=>{this.emit(...Y),this.emit(k0.ALL,...Y),this._pendingUnlinks.delete(A)})},typeof G.atomic==="number"?G.atomic:100),this;if($===k0.ADD&&this._pendingUnlinks.has(w))$=k0.CHANGE,this._pendingUnlinks.delete(w)}if(J&&($===k0.ADD||$===k0.CHANGE)&&this._readyEmitted){let Y=(A,D)=>{if(A)$=k0.ERROR,E[0]=A,this.emitWithAll($,E);else if(D){if(E.length>1)E[1]=D;else E.push(D);this.emitWithAll($,E)}};return this._awaitWriteFinish(w,J.stabilityThreshold,$,Y),this}if($===k0.CHANGE){if(!this._throttle(k0.CHANGE,w,50))return this}if(G.alwaysStat&&X===void 0&&($===k0.ADD||$===k0.ADD_DIR||$===k0.CHANGE)){let Y=G.cwd?A0.join(G.cwd,w):w,A;try{A=await ab(Y)}catch(D){}if(!A||this.closed)return;E.push(A)}return this.emitWithAll($,E),this}_handleError($){let w=$&&$.code;if($&&w!=="ENOENT"&&w!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||w!=="EPERM"&&w!=="EACCES"))this.emit(k0.ERROR,$);return $||this.closed}_throttle($,w,X){if(!this._throttled.has($))this._throttled.set($,new Map);let G=this._throttled.get($);if(!G)throw Error("invalid throttle");let E=G.get(w);if(E)return E.count++,!1;let J,W=()=>{let A=G.get(w),D=A?A.count:0;if(G.delete(w),clearTimeout(J),A)clearTimeout(A.timeoutObject);return D};J=setTimeout(W,X);let Y={timeoutObject:J,clear:W,count:0};return G.set(w,Y),Y}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish($,w,X,G){let E=this.options.awaitWriteFinish;if(typeof E!=="object")return;let J=E.pollInterval,W,Y=$;if(this.options.cwd&&!A0.isAbsolute($))Y=A0.join(this.options.cwd,$);let A=new Date,D=this._pendingWrites;function U(N){sb(Y,(H,L)=>{if(H||!D.has($)){if(H&&H.code!=="ENOENT")G(H);return}let F=Number(new Date);if(N&&L.size!==N.size)D.get($).lastChange=F;let M=D.get($);if(F-M.lastChange>=w)D.delete($),G(void 0,L);else W=setTimeout(U,J,L)})}if(!D.has($))D.set($,{lastChange:A,cancelWait:()=>{return D.delete($),clearTimeout(W),X}}),W=setTimeout(U,J)}_isIgnored($,w){if(this.options.atomic&&Jk.test($))return!0;if(!this._userIgnored){let{cwd:X}=this.options,E=(this.options.ignored||[]).map(rL(X)),W=[...[...this._ignoredPaths].map(rL(X)),...E];this._userIgnored=Dk(W,void 0)}return this._userIgnored($,w)}_isntIgnored($,w){return!this._isIgnored($,w)}_getWatchHelpers($){return new dL($,this.options.followSymlinks,this)}_getWatchedDir($){let w=A0.resolve($);if(!this._watched.has(w))this._watched.set(w,new tL(w,this._boundRemove));return this._watched.get(w)}_hasReadPermissions($){if(this.options.ignorePermissionErrors)return!0;return Boolean(Number($.mode)&256)}_remove($,w,X){let G=A0.join($,w),E=A0.resolve(G);if(X=X!=null?X:this._watched.has(G)||this._watched.has(E),!this._throttle("remove",G,100))return;if(!X&&this._watched.size===1)this.add($,w,!0);this._getWatchedDir(G).getChildren().forEach((N)=>this._remove(G,N));let Y=this._getWatchedDir($),A=Y.has(w);if(Y.remove(w),this._symlinkPaths.has(E))this._symlinkPaths.delete(E);let D=G;if(this.options.cwd)D=A0.relative(this.options.cwd,G);if(this.options.awaitWriteFinish&&this._pendingWrites.has(D)){if(this._pendingWrites.get(D).cancelWait()===k0.ADD)return}this._watched.delete(G),this._watched.delete(E);let U=X?k0.UNLINK_DIR:k0.UNLINK;if(A&&!this._isIgnored(G))this._emit(U,G);this._closePath(G)}_closePath($){this._closeFile($);let w=A0.dirname($);this._getWatchedDir(w).remove(A0.basename($))}_closeFile($){let w=this._closers.get($);if(!w)return;w.forEach((X)=>X()),this._closers.delete($)}_addPathCloser($,w){if(!w)return;let X=this._closers.get($);if(!X)X=[],this._closers.set($,X);X.push(w)}_readdirp($,w){if(this.closed)return;let X={type:k0.ALL,alwaysStat:!0,lstat:!0,...w,depth:0},G=_L($,X);return this._streams.add(G),G.once(gL,()=>{G=void 0}),G.once(KW,()=>{if(G)this._streams.delete(G),G=void 0}),G}}function Lk($,w={}){let X=new jW(w);return X.add($),X}var lL={watch:Lk,FSWatcher:jW};g$();bw();var C6=P0("runner:watcher"),AG=new Map;async function aL(){let w=await g().query.jobs.findMany({where:S(d0.enabled,!0)});for(let X of w)if(X.trigger_type==="watch"&&X.watch_path)Fk(X.id,X.name,X.watch_path);C6.info(`Watchers started. ${AG.size} paths watched.`)}function Fk($,w,X){if(AG.has($))AG.get($)?.close().catch(()=>{});let G=lL.watch(X,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:500,pollInterval:100}});G.on("add",(E)=>sL($,w,E)),G.on("change",(E)=>sL($,w,E)),AG.set($,G),C6.info(`Watching: ${X} \u2192 ${w}`)}async function sL($,w,X){C6.info(`Watch trigger: ${w} (${X})`);try{await $1({jobId:$,triggerBy:"watch",envOverrides:{WATCH_PATH:X}})}catch(G){C6.error(`Watch job failed: ${w}`,G)}}async function eL(){for(let[,$]of AG)await $.close();AG.clear(),C6.info("Watchers stopped.")}d$();async function Mk($,w,X,G,E,J){let W=`${$}${G}`;if(J){let A=new URLSearchParams;for(let[U,N]of Object.entries(J))if(N!==void 0)A.set(U,String(N));let D=A.toString();if(D)W+=`?${D}`}let Y={"Content-Type":"application/json"};if(w)Y.Authorization=`Bearer ${w}`;try{let A=await fetch(W,{method:X,headers:Y,...E!==void 0?{body:JSON.stringify(E)}:{}});if(A.status===204)return{data:null,error:null};let D=await A.json();if(!A.ok){let U=D;return{data:null,error:{error:U.error??"Unknown error",code:U.code??"UNKNOWN"}}}return{data:D,error:null}}catch(A){return{data:null,error:{error:String(A),code:"NETWORK_ERROR"}}}}function r0($){let w=Q0(),X=$?.baseUrl??`http://${w.api.host}:${w.api.port}`,G=$?.secret??w.api.secret,E=(J,W,Y,A)=>Mk(X,G,J,W,Y,A);return{tasks:{list:(J)=>E("GET","/tasks",void 0,J),get:(J)=>E("GET",`/tasks/${J}`),create:(J)=>E("POST","/tasks",J),update:(J,W)=>E("PATCH",`/tasks/${J}`,W),delete:(J)=>E("DELETE",`/tasks/${J}`),addNote:(J,W,Y="human")=>E("POST",`/tasks/${J}/notes`,{content:W,author:Y}),listLinks:(J)=>E("GET",`/tasks/${J}/links`),addLink:(J,W)=>E("POST",`/tasks/${J}/links`,W),deleteLink:(J,W)=>E("DELETE",`/tasks/${J}/links/${W}`)},memories:{list:(J)=>E("GET","/memories",void 0,J),search:(J,W,Y)=>E("GET","/memories/search",void 0,{q:J,scope:W,limit:Y}),create:(J)=>E("POST","/memories",J),delete:(J)=>E("DELETE",`/memories/${J}`)},jobs:{list:(J)=>E("GET","/jobs",void 0,J),get:(J)=>E("GET",`/jobs/${J}`),create:(J)=>E("POST","/jobs",J),trigger:(J)=>E("POST",`/jobs/${J}/trigger`),runs:(J,W)=>E("GET",`/jobs/${J}/runs`,void 0,{limit:W}),runLogs:(J,W,Y)=>E("GET",`/jobs/${J}/runs/${W}/logs`,void 0,Y)},prompts:{list:(J)=>E("GET","/prompts",void 0,J),get:(J)=>E("GET",`/prompts/${J}`),create:(J)=>E("POST","/prompts",J),update:(J,W)=>E("PATCH",`/prompts/${J}`,W),delete:(J)=>E("DELETE",`/prompts/${J}`),render:(J,W)=>E("POST",`/prompts/${J}/render`,{vars:W??{}}),history:(J,W)=>E("GET",`/prompts/${J}/history`,void 0,{limit:W})},projects:{list:(J)=>E("GET","/projects",void 0,J),get:(J)=>E("GET",`/projects/${J}`),create:(J)=>E("POST","/projects",J),update:(J,W)=>E("PATCH",`/projects/${J}`,W),delete:(J)=>E("DELETE",`/projects/${J}`)},sessions:{list:(J)=>E("GET","/sessions",void 0,J),get:(J)=>E("GET",`/sessions/${J}`)},health:{check:()=>E("GET","/health")},gateway:{status:()=>E("GET","/gateway/status"),send:(J)=>E("POST","/gateway/send",J)}}}var xw=process.env.ORC_HOME??xJ(Ov(),".orc"),MX0=xJ(xw,"daemon.log"),QG=xJ(xw,"daemon.pid");function Nv(){Av(xJ(xw,"logs"),{recursive:!0})}function fJ(){try{return Number(Dv(QG,"utf-8").trim())}catch{return null}}function Hv(){Uv(QG,String(process.pid))}function $M(){try{B$("fs").unlinkSync(QG)}catch{}}function wM(){let $=new V$("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=fJ();if(w)try{process.kill(w,0),console.error(`[orc] daemon already running (pid ${w}). Use: orc daemon stop`),process.exit(1)}catch{}let X=Q0();Hv(),await Promise.resolve().then(() => (U7(),D7)),console.log(`[orc] home ${xw}`),console.log(`[orc] db ${X.db.path}`),console.log(`[orc] API http://${X.api.host}:${X.api.port}`),console.log(`[orc] pid ${process.pid} -> ${QG}`),await jL(),await aL(),await DW(),console.log(`[orc] Scheduler + watchers + gateway active. Ctrl+C to stop.
|
|
501
|
-
`);let
|
|
502
|
-
[orc] ${
|
|
503
|
-
`),
|
|
504
|
-
`),process.exit(0)};process.on("SIGINT",()=>void
|
|
505
|
-
`);for(let J of
|
|
506
|
-
`)[0]?.slice(0,60)}`:"";console.log(` \u21B3 session ${F.agent}${F.agent_version?`/${F.agent_version}`:""}${M}`)}}}}),$}function Lv($){return{pending:"\u25CB",running:"\u25D0",success:"\u25CF",failed:"\u2715",cancelled:"\u2298",skipped:"\u21B7"}[$]??"?"}function JM(){let $=new V$("mem").description("Manage memory");return $.command("search <query>").description("Search memories").option("-s, --scope <scope>","Scope filter").option("-l, --limit <n>","Max results","10").action(async(w,X)=>{let G=r0(),{data:E,error:J}=await G.memories.search(w,X.scope,Number(X.limit));if(J)return console.error("Error:",J);let W=E?.results??[];if(W.length===0)return console.log("No memories found.");for(let Y of W){let A=EM(Y.created_at),D=Y.scope?`[${Y.scope}]`:"";console.log(`\u2022 ${Y.content.slice(0,80)} ${D} ${A}`)}}),$.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").action(async(w,X)=>{let G=r0(),{data:E,error:J}=await G.memories.create({content:w,type:X.type,scope:X.scope,source:X.source,importance:X.importance,...X.tags?{tags:X.tags.split(",").map((W)=>W.trim())}:{}});if(J)return console.error("Error:",J);console.log(`Stored: [${E?.id.slice(-6)}] [${X.type}] ${E?.content.slice(0,60)}`)}),$.command("list").description("List recent memories").option("-s, --scope <scope>","Scope filter").option("-l, --limit <n>","Max results","20").action(async(w)=>{let X=r0(),{data:G,error:E}=await X.memories.list({scope:w.scope,limit:Number(w.limit)});if(E)return console.error("Error:",E);let J=G?.memories??[];if(J.length===0)return console.log("No memories found.");for(let W of J){let Y=EM(W.created_at),A=W.scope?`[${W.scope}]`:"";console.log(`\u2022 [${W.id.slice(-6)}] ${W.content.slice(0,70)} ${A} ${Y}`)}}),$}function EM($){let w=Date.now()-new Date($).getTime(),X=Math.floor(w/60000);if(X<60)return`${X}m ago`;let G=Math.floor(X/60);if(G<24)return`${G}h ago`;return`${Math.floor(G/24)}d ago`}d$();function WM($){let w=Date.now()-new Date($).getTime(),X=Math.floor(w/60000);if(X<60)return`${X}m ago`;let G=Math.floor(X/60);if(G<24)return`${G}h ago`;return`${Math.floor(G/24)}d ago`}function O7(){try{let $=Q0();return`http://${$.api.host}:${$.api.port}`}catch{return process.env.ORC_API_BASE??"http://127.0.0.1:7700"}}function N7(){let $={"Content-Type":"application/json"},w=process.env.ORC_API_SECRET??(()=>{try{return Q0().api.secret}catch{return}})();if(w)$.Authorization=`Bearer ${w}`;return $}function YM(){let $=new V$("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 X=new URLSearchParams({limit:w.limit});if(w.agent)X.set("agent",w.agent);let G;try{G=await fetch(`${O7()}/sessions?${X}`,{headers:N7()})}catch{return console.error("Cannot connect to orc API. Is it running? (orc api or orc daemon)")}if(!G.ok)return console.error(`API error: ${G.status}`);let J=(await G.json()).sessions;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 W of J){let Y=W.id.slice(-6),A=W.agent.padEnd(16),D=WM(W.created_at).padEnd(10),U=(W.summary??"\u2014").slice(0,40);console.log(`${Y} ${A} ${D} ${U}`)}}),$.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,X)=>{let G=w;if(w.length<26){let W=await fetch(`${O7()}/sessions?limit=100`,{headers:N7()}).catch(()=>null);if(W?.ok){let A=(await W.json()).sessions.find((D)=>D.id.endsWith(w)||D.id===w);if(A)G=A.id}}let E;try{E=await fetch(`${O7()}/sessions/${G}`,{headers:N7()})}catch{return console.error("Cannot connect to orc API.")}if(E.status===404)return console.error(`Session not found: ${w}`);if(!E.ok)return console.error(`API error: ${E.status}`);let J=await E.json();if(console.log(`Session: ${J.id}`),console.log(`Agent: ${J.agent}`),console.log(`When: ${new Date(J.created_at).toLocaleString()} (${WM(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(`
|
|
507
|
-
Summary:`),console.log(` ${J.summary}`);if(X.events&&J.events.length>0){let W=Number(X.limit),Y=J.events.slice(0,W);console.log(`
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
`)
|
|
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),np(w)}clear(){this._buffer=void 0}}function np($){return RT.parse(JSON.parse($))}function jV($){return JSON.stringify($)+`
|
|
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.
|
|
580
|
+
`);let X=async(G)=>{process.stdout.write(`
|
|
581
|
+
[orc] ${G} - shutting down...
|
|
582
|
+
`),nL(),await F3(),await KN(),Qj(),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=lA();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.`),Qj()}}),$.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 Kj(){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 Xv,readFileSync as Gv,writeFileSync as Jv}from"fs";import{homedir as Av}from"os";import{join as Dv}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 Nv($){return{active:"\u25CF",paused:"\u25D0",archived:"\u25CB"}[$]??"?"}function Wv($){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 Ov($){return{todo:"\u25CB",doing:"\u25D0",review:"\u25C9",changes_requested:"\u21A9",blocked:"\u2298",done:"\u25CF",cancelled:"\u2715"}[$]??"?"}function Uv($){return{low:"\u2193",normal:"\u2192",high:"\u2191",critical:"\u203C"}[$]??" "}function Pj(){return Dv(Av(),".orc","config.json")}function Vj(){let $=Pj();if(!Xv($))return{};return JSON.parse(Gv($,"utf-8"))}function K9($){Jv(Pj(),`${JSON.stringify($,null,2)}
|
|
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(`
|
|
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
|
+
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
|
+
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 xj(){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=Mv(X?.tasks??[],"status");console.log(`
|
|
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 Mv($,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 gj(){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=yj(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(q9(F.padEnd(50,"\u2500"),H));for(let j of L)console.log(yj(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(` ${q9(S9(G.status),G.status)} ${VE(G.title,"1")}`),console.log(),A("ID",G.id),A("Status",`${S9(G.status)} ${G.status}`),A("Priority",`${uj(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 Rv={review:"33",changes_requested:"33",doing:"36",blocked:"31",todo:"2",done:"32",cancelled:"2"};function q9($,w){return VE($,Rv[w]??"0")}function S9($){return{todo:"\u25CB",doing:"\u25D0",review:"\u25C9",changes_requested:"\u21A9",blocked:"\u2298",done:"\u25CF",cancelled:"\u2715"}[$]??"?"}function uj($){return{low:"\u2193",normal:"\u2192",high:"\u2191",critical:"\u203C"}[$]??" "}function yj($,w){let E=S9($.status),X=uj($.priority),G=$.id.slice(-6),J=$.title.length>40?`${$.title.slice(0,39)}\u2026`:$.title,A=` ${q9(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 lp=tp(dp(import.meta.url)),sp=JSON.parse(pp(ip(lp,"..","package.json"),"utf-8")),m$=new $$().name("orc").description("Human + AI Orchestration Hub").version(sp.version).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(gj());m$.addCommand(qj());m$.addCommand(bj());m$.addCommand(Sj());m$.addCommand(fj());m$.addCommand(Ij());m$.addCommand(Kj());m$.addCommand(Zj());m$.addCommand(xj());m$.addCommand(_j());m$.command("api").description("Start the API server (use --port / --host / --db / --secret to configure)").action(async()=>{await Promise.resolve().then(() => (I9(),Q9)),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:kX},{label:"daemon log",path:`${tw}/daemon.log`}];for(let X of w)if(rp(X.path)){let G=Math.round(op(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=lA();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 IV().then(() => QV);await $()});m$.parseAsync(process.argv).catch(($)=>{console.error($ instanceof Error?$.message:$),process.exit(1)});
|