@onyxsecurity/mcp-gateway 1.0.59 → 1.0.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ import{generateCodeChallenge as e,generateCodeVerifier as t}from"./pkce-CbP4rU3z.js";export{e as generateCodeChallenge,t as generateCodeVerifier};
@@ -1,2 +1,2 @@
1
1
  import{createHash as e,randomBytes as t}from"node:crypto";async function n(t){let n=e(`sha256`).update(t).digest();return i(n)}function r(){let e=t(32);return i(e)}function i(e){return e.toString(`base64`).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}export{n as generateCodeChallenge,r as generateCodeVerifier};
2
- //# sourceMappingURL=pkce-ANRIC6ce.js.map
2
+ //# sourceMappingURL=pkce-CbP4rU3z.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"pkce-ANRIC6ce.js","names":[],"sources":["../src/auth/pkce.ts"],"sourcesContent":["import { createHash, randomBytes } from \"node:crypto\";\n\n/**\n * Generates a code challenge from a code verifier using SHA-256.\n * This implements the S256 code challenge method as per RFC 7636.\n *\n * @param verifier The code verifier to hash\n * @returns The base64url-encoded SHA-256 hash of the verifier\n */\nexport async function generateCodeChallenge(verifier: string): Promise<string> {\n const hash = createHash(\"sha256\").update(verifier).digest();\n return base64UrlEncode(hash);\n}\n\n/**\n * Generates a cryptographically secure code verifier for PKCE.\n * The verifier is a random string of 43-128 characters using URL-safe characters.\n *\n * @returns A random code verifier string\n */\nexport function generateCodeVerifier(): string {\n // Generate 32 bytes of random data (will result in 43 base64url chars)\n const randomData = randomBytes(32);\n return base64UrlEncode(randomData);\n}\n\n/**\n * Encodes a buffer as base64url (URL-safe base64 without padding).\n *\n * @param buffer The buffer to encode\n * @returns The base64url-encoded string\n */\nfunction base64UrlEncode(buffer: Buffer): string {\n return buffer\n .toString(\"base64\")\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\")\n .replace(/=/g, \"\");\n}\n\n"],"mappings":"0DASA,eAAsB,EAAsB,EAAmC,CAC7E,IAAM,EAAO,EAAW,SAAS,CAAC,OAAO,EAAS,CAAC,QAAQ,CAC3D,OAAO,EAAgB,EAAK,CAS9B,SAAgB,GAA+B,CAE7C,IAAM,EAAa,EAAY,GAAG,CAClC,OAAO,EAAgB,EAAW,CASpC,SAAS,EAAgB,EAAwB,CAC/C,OAAO,EACJ,SAAS,SAAS,CAClB,QAAQ,MAAO,IAAI,CACnB,QAAQ,MAAO,IAAI,CACnB,QAAQ,KAAM,GAAG"}
1
+ {"version":3,"file":"pkce-CbP4rU3z.js","names":[],"sources":["../src/auth/pkce.ts"],"sourcesContent":["import { createHash, randomBytes } from \"node:crypto\";\n\n/**\n * Generates a code challenge from a code verifier using SHA-256.\n * This implements the S256 code challenge method as per RFC 7636.\n *\n * @param verifier The code verifier to hash\n * @returns The base64url-encoded SHA-256 hash of the verifier\n */\nexport async function generateCodeChallenge(verifier: string): Promise<string> {\n const hash = createHash(\"sha256\").update(verifier).digest();\n return base64UrlEncode(hash);\n}\n\n/**\n * Generates a cryptographically secure code verifier for PKCE.\n * The verifier is a random string of 43-128 characters using URL-safe characters.\n *\n * @returns A random code verifier string\n */\nexport function generateCodeVerifier(): string {\n // Generate 32 bytes of random data (will result in 43 base64url chars)\n const randomData = randomBytes(32);\n return base64UrlEncode(randomData);\n}\n\n/**\n * Encodes a buffer as base64url (URL-safe base64 without padding).\n *\n * @param buffer The buffer to encode\n * @returns The base64url-encoded string\n */\nfunction base64UrlEncode(buffer: Buffer): string {\n return buffer\n .toString(\"base64\")\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\")\n .replace(/=/g, \"\");\n}\n\n"],"mappings":"0DASA,eAAsB,EAAsB,EAAmC,CAC7E,IAAM,EAAO,EAAW,SAAS,CAAC,OAAO,EAAS,CAAC,QAAQ,CAC3D,OAAO,EAAgB,EAAK,CAS9B,SAAgB,GAA+B,CAE7C,IAAM,EAAa,EAAY,GAAG,CAClC,OAAO,EAAgB,EAAW,CASpC,SAAS,EAAgB,EAAwB,CAC/C,OAAO,EACJ,SAAS,SAAS,CAClB,QAAQ,MAAO,IAAI,CACnB,QAAQ,MAAO,IAAI,CACnB,QAAQ,KAAM,GAAG"}
@@ -0,0 +1,9 @@
1
+ import{__commonJSMin as e,__require as t,__toESM as n}from"./chunk-CrDKVgUD.js";import{randomUUID as r}from"crypto";import{AsyncLocalStorage as i}from"node:async_hooks";import{randomUUID as a}from"node:crypto";import{chownSync as o,existsSync as s,mkdirSync as c}from"node:fs";import{join as l,sep as u}from"node:path";import d from"winston";import f from"winston-daily-rotate-file";import p from"env-var";import{arch as m,homedir as h,hostname as g,platform as ee}from"node:os";import"dotenv/config";import{chown as te}from"node:fs/promises";var _;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(_||={});var ne;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(ne||={});const v=_.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),y=e=>{switch(typeof e){case`undefined`:return v.undefined;case`string`:return v.string;case`number`:return Number.isNaN(e)?v.nan:v.number;case`boolean`:return v.boolean;case`function`:return v.function;case`bigint`:return v.bigint;case`symbol`:return v.symbol;case`object`:return Array.isArray(e)?v.array:e===null?v.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?v.promise:typeof Map<`u`&&e instanceof Map?v.map:typeof Set<`u`&&e instanceof Set?v.set:typeof Date<`u`&&e instanceof Date?v.date:v.object;default:return v.unknown}},b=_.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`]);var x=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,_.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t={},n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};x.create=e=>new x(e);var S=(e,t)=>{let n;switch(e.code){case b.invalid_type:n=e.received===v.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case b.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,_.jsonStringifyReplacer)}`;break;case b.unrecognized_keys:n=`Unrecognized key(s) in object: ${_.joinValues(e.keys,`, `)}`;break;case b.invalid_union:n=`Invalid input`;break;case b.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${_.joinValues(e.options)}`;break;case b.invalid_enum_value:n=`Invalid enum value. Expected ${_.joinValues(e.options)}, received '${e.received}'`;break;case b.invalid_arguments:n=`Invalid function arguments`;break;case b.invalid_return_type:n=`Invalid function return type`;break;case b.invalid_date:n=`Invalid date`;break;case b.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:_.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case b.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case b.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case b.custom:n=`Invalid input`;break;case b.invalid_intersection_types:n=`Intersection results could not be merged`;break;case b.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case b.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,_.assertNever(e)}return{message:n}};let re=S;function C(){return re}const w=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function T(e,t){let n=C(),r=w({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===S?void 0:S].filter(e=>!!e)});e.common.issues.push(r)}var E=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return D;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return D;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}};const D=Object.freeze({status:`aborted`}),ie=e=>({status:`dirty`,value:e}),O=e=>({status:`valid`,value:e}),ae=e=>e.status===`aborted`,oe=e=>e.status===`dirty`,k=e=>e.status===`valid`,se=e=>typeof Promise<`u`&&e instanceof Promise;var A;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(A||={});var j=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const ce=(e,t)=>{if(k(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){return this._error||=new x(e.common.issues),this._error}}};function M(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var N=class{get description(){return this._def.description}_getType(e){return y(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:y(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new E,ctx:{common:e.parent.common,data:e.data,parsedType:y(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(se(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:y(e)},r=this._parseSync({data:e,path:n.path,parent:n});return ce(n,r)}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:y(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return k(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>k(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:y(e)},r=this._parse({data:e,path:n.path,parent:n}),i=await(se(r)?r:Promise.resolve(r));return ce(n,i)}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:b.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new ut({schema:this,typeName:P.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,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:e=>this[`~validate`](e)}}optional(){return dt.create(this,this._def)}nullable(){return ft.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ge.create(this)}promise(){return lt.create(this,this._def)}or(e){return Je.create([this,e],this._def)}and(e){return Qe.create(this,e,this._def)}transform(e){return new ut({...M(this._def),schema:this,typeName:P.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new pt({...M(this._def),innerType:this,defaultValue:t,typeName:P.ZodDefault})}brand(){return new gt({typeName:P.ZodBranded,type:this,...M(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new mt({...M(this._def),innerType:this,catchValue:t,typeName:P.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return _t.create(this,e)}readonly(){return vt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const le=/^c[^\s-]{8,}$/i,ue=/^[0-9a-z]+$/,de=/^[0-9A-HJKMNP-TV-Z]{26}$/i,fe=/^[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,pe=/^[a-z0-9_-]{21}$/i,me=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,he=/^[-+]?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)?)??$/,ge=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let _e;const ve=/^(?:(?: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])$/,ye=/^(?:(?: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])$/,be=/^(([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]))$/,xe=/^(([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])$/,Se=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ce=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,we=`((\\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])))`,Te=RegExp(`^${we}$`);function Ee(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function De(e){return RegExp(`^${Ee(e)}$`)}function Oe(e){let t=`${we}T${Ee(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function ke(e,t){return!!((t===`v4`||!t)&&ve.test(e)||(t===`v6`||!t)&&be.test(e))}function Ae(e,t){if(!me.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function je(e,t){return!!((t===`v4`||!t)&&ye.test(e)||(t===`v6`||!t)&&xe.test(e))}var Me=class e extends N{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==v.string){let t=this._getOrReturnCtx(e);return T(t,{code:b.invalid_type,expected:v.string,received:t.parsedType}),D}let t=new E,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),T(n,{code:b.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),T(n,{code:b.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?T(n,{code:b.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&T(n,{code:b.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)ge.test(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{validation:`email`,code:b.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)_e||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),_e.test(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{validation:`emoji`,code:b.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)fe.test(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{validation:`uuid`,code:b.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)pe.test(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{validation:`nanoid`,code:b.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)le.test(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{validation:`cuid`,code:b.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)ue.test(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{validation:`cuid2`,code:b.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)de.test(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{validation:`ulid`,code:b.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),T(n,{validation:`url`,code:b.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{validation:`regex`,code:b.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),T(n,{code:b.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),T(n,{code:b.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),T(n,{code:b.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?Oe(r).test(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:b.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?Te.test(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:b.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?De(r).test(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:b.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?he.test(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{validation:`duration`,code:b.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?ke(e.data,r.version)||(n=this._getOrReturnCtx(e,n),T(n,{validation:`ip`,code:b.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Ae(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),T(n,{validation:`jwt`,code:b.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?je(e.data,r.version)||(n=this._getOrReturnCtx(e,n),T(n,{validation:`cidr`,code:b.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Se.test(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{validation:`base64`,code:b.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Ce.test(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{validation:`base64url`,code:b.invalid_string,message:r.message}),t.dirty()):_.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:b.invalid_string,...A.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...A.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...A.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...A.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...A.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...A.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...A.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...A.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...A.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...A.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...A.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...A.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...A.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...A.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...A.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...A.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...A.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...A.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...A.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...A.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...A.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...A.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...A.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...A.errToObj(t)})}nonempty(e){return this.min(1,A.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Me.create=e=>new Me({checks:[],typeName:P.ZodString,coerce:e?.coerce??!1,...M(e)});function Ne(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r,a=Number.parseInt(e.toFixed(i).replace(`.`,``)),o=Number.parseInt(t.toFixed(i).replace(`.`,``));return a%o/10**i}var Pe=class e extends N{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==v.number){let t=this._getOrReturnCtx(e);return T(t,{code:b.invalid_type,expected:v.number,received:t.parsedType}),D}let t,n=new E;for(let r of this._def.checks)r.kind===`int`?_.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),T(t,{code:b.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),T(t,{code:b.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),T(t,{code:b.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Ne(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),T(t,{code:b.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),T(t,{code:b.not_finite,message:r.message}),n.dirty()):_.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,A.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,A.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,A.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,A.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:A.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:A.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:A.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:A.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:A.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:A.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:A.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:A.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:A.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:A.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&_.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};Pe.create=e=>new Pe({checks:[],typeName:P.ZodNumber,coerce:e?.coerce||!1,...M(e)});var Fe=class e extends N{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==v.bigint)return this._getInvalidInput(e);let t,n=new E;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),T(t,{code:b.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),T(t,{code:b.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),T(t,{code:b.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):_.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return T(t,{code:b.invalid_type,expected:v.bigint,received:t.parsedType}),D}gte(e,t){return this.setLimit(`min`,e,!0,A.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,A.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,A.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,A.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:A.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:A.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:A.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:A.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:A.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:A.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Fe.create=e=>new Fe({checks:[],typeName:P.ZodBigInt,coerce:e?.coerce??!1,...M(e)});var Ie=class extends N{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==v.boolean){let t=this._getOrReturnCtx(e);return T(t,{code:b.invalid_type,expected:v.boolean,received:t.parsedType}),D}return O(e.data)}};Ie.create=e=>new Ie({typeName:P.ZodBoolean,coerce:e?.coerce||!1,...M(e)});var Le=class e extends N{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==v.date){let t=this._getOrReturnCtx(e);return T(t,{code:b.invalid_type,expected:v.date,received:t.parsedType}),D}if(Number.isNaN(e.data.getTime())){let t=this._getOrReturnCtx(e);return T(t,{code:b.invalid_date}),D}let t=new E,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),T(n,{code:b.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),T(n,{code:b.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):_.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:A.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:A.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};Le.create=e=>new Le({checks:[],coerce:e?.coerce||!1,typeName:P.ZodDate,...M(e)});var Re=class extends N{_parse(e){if(this._getType(e)!==v.symbol){let t=this._getOrReturnCtx(e);return T(t,{code:b.invalid_type,expected:v.symbol,received:t.parsedType}),D}return O(e.data)}};Re.create=e=>new Re({typeName:P.ZodSymbol,...M(e)});var ze=class extends N{_parse(e){if(this._getType(e)!==v.undefined){let t=this._getOrReturnCtx(e);return T(t,{code:b.invalid_type,expected:v.undefined,received:t.parsedType}),D}return O(e.data)}};ze.create=e=>new ze({typeName:P.ZodUndefined,...M(e)});var Be=class extends N{_parse(e){if(this._getType(e)!==v.null){let t=this._getOrReturnCtx(e);return T(t,{code:b.invalid_type,expected:v.null,received:t.parsedType}),D}return O(e.data)}};Be.create=e=>new Be({typeName:P.ZodNull,...M(e)});var Ve=class extends N{constructor(){super(...arguments),this._any=!0}_parse(e){return O(e.data)}};Ve.create=e=>new Ve({typeName:P.ZodAny,...M(e)});var He=class extends N{constructor(){super(...arguments),this._unknown=!0}_parse(e){return O(e.data)}};He.create=e=>new He({typeName:P.ZodUnknown,...M(e)});var Ue=class extends N{_parse(e){let t=this._getOrReturnCtx(e);return T(t,{code:b.invalid_type,expected:v.never,received:t.parsedType}),D}};Ue.create=e=>new Ue({typeName:P.ZodNever,...M(e)});var We=class extends N{_parse(e){if(this._getType(e)!==v.undefined){let t=this._getOrReturnCtx(e);return T(t,{code:b.invalid_type,expected:v.void,received:t.parsedType}),D}return O(e.data)}};We.create=e=>new We({typeName:P.ZodVoid,...M(e)});var Ge=class e extends N{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==v.array)return T(t,{code:b.invalid_type,expected:v.array,received:t.parsedType}),D;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(T(t,{code:e?b.too_big:b.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(T(t,{code:b.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(T(t,{code:b.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new j(t,e,t.path,n)))).then(e=>E.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new j(t,e,t.path,n)));return E.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:A.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:A.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:A.toString(n)}})}nonempty(e){return this.min(1,e)}};Ge.create=(e,t)=>new Ge({type:e,minLength:null,maxLength:null,exactLength:null,typeName:P.ZodArray,...M(t)});function Ke(e){if(e instanceof qe){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=dt.create(Ke(r))}return new qe({...e._def,shape:()=>t})}else if(e instanceof Ge)return new Ge({...e._def,type:Ke(e.element)});else if(e instanceof dt)return dt.create(Ke(e.unwrap()));else if(e instanceof ft)return ft.create(Ke(e.unwrap()));else if(e instanceof $e)return $e.create(e.items.map(e=>Ke(e)));else return e}var qe=class e extends N{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=_.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==v.object){let t=this._getOrReturnCtx(e);return T(t,{code:b.invalid_type,expected:v.object,received:t.parsedType}),D}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ue&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new j(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Ue){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(T(n,{code:b.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new j(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>E.mergeObjectSync(t,e)):E.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return A.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:A.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:P.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of _.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of _.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return Ke(this)}partial(t){let n={};for(let e of _.objectKeys(this.shape)){let r=this.shape[e];t&&!t[e]?n[e]=r:n[e]=r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of _.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof dt;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return ot(_.objectKeys(this.shape))}};qe.create=(e,t)=>new qe({shape:()=>e,unknownKeys:`strip`,catchall:Ue.create(),typeName:P.ZodObject,...M(t)}),qe.strictCreate=(e,t)=>new qe({shape:()=>e,unknownKeys:`strict`,catchall:Ue.create(),typeName:P.ZodObject,...M(t)}),qe.lazycreate=(e,t)=>new qe({shape:e,unknownKeys:`strip`,catchall:Ue.create(),typeName:P.ZodObject,...M(t)});var Je=class extends N{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new x(e.ctx.common.issues));return T(t,{code:b.invalid_union,unionErrors:n}),D}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new x(e));return T(t,{code:b.invalid_union,unionErrors:i}),D}}get options(){return this._def.options}};Je.create=(e,t)=>new Je({options:e,typeName:P.ZodUnion,...M(t)});const Ye=e=>e instanceof it?Ye(e.schema):e instanceof ut?Ye(e.innerType()):e instanceof at?[e.value]:e instanceof st?e.options:e instanceof ct?_.objectValues(e.enum):e instanceof pt?Ye(e._def.innerType):e instanceof ze?[void 0]:e instanceof Be?[null]:e instanceof dt?[void 0,...Ye(e.unwrap())]:e instanceof ft?[null,...Ye(e.unwrap())]:e instanceof gt||e instanceof vt?Ye(e.unwrap()):e instanceof mt?Ye(e._def.innerType):[];var Xe=class e extends N{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==v.object)return T(t,{code:b.invalid_type,expected:v.object,received:t.parsedType}),D;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(T(t,{code:b.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),D)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=Ye(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:P.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...M(r)})}};function Ze(e,t){let n=y(e),r=y(t);if(e===t)return{valid:!0,data:e};if(n===v.object&&r===v.object){let n=_.objectKeys(t),r=_.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Ze(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===v.array&&r===v.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=Ze(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===v.date&&r===v.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var Qe=class extends N{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(ae(e)||ae(r))return D;let i=Ze(e.value,r.value);return i.valid?((oe(e)||oe(r))&&t.dirty(),{status:t.value,value:i.data}):(T(n,{code:b.invalid_intersection_types}),D)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Qe.create=(e,t,n)=>new Qe({left:e,right:t,typeName:P.ZodIntersection,...M(n)});var $e=class e extends N{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==v.array)return T(n,{code:b.invalid_type,expected:v.array,received:n.parsedType}),D;if(n.data.length<this._def.items.length)return T(n,{code:b.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),D;!this._def.rest&&n.data.length>this._def.items.length&&(T(n,{code:b.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new j(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>E.mergeArray(t,e)):E.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};$e.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new $e({items:e,typeName:P.ZodTuple,rest:null,...M(t)})};var et=class e extends N{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==v.object)return T(n,{code:b.invalid_type,expected:v.object,received:n.parsedType}),D;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new j(n,e,n.path,e)),value:a._parse(new j(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?E.mergeObjectAsync(t,r):E.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof N?new e({keyType:t,valueType:n,typeName:P.ZodRecord,...M(r)}):new e({keyType:Me.create(),valueType:t,typeName:P.ZodRecord,...M(n)})}},tt=class extends N{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==v.map)return T(n,{code:b.invalid_type,expected:v.map,received:n.parsedType}),D;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new j(n,e,n.path,[a,`key`])),value:i._parse(new j(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return D;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return D;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};tt.create=(e,t,n)=>new tt({valueType:t,keyType:e,typeName:P.ZodMap,...M(n)});var nt=class e extends N{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==v.set)return T(n,{code:b.invalid_type,expected:v.set,received:n.parsedType}),D;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(T(n,{code:b.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(T(n,{code:b.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return D;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new j(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:A.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:A.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};nt.create=(e,t)=>new nt({valueType:e,minSize:null,maxSize:null,typeName:P.ZodSet,...M(t)});var rt=class e extends N{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==v.function)return T(t,{code:b.invalid_type,expected:v.function,received:t.parsedType}),D;function n(e,n){return w({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,C(),S].filter(e=>!!e),issueData:{code:b.invalid_arguments,argumentsError:n}})}function r(e,n){return w({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,C(),S].filter(e=>!!e),issueData:{code:b.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof lt){let e=this;return O(async function(...t){let o=new x([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}else{let e=this;return O(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new x([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new x([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:$e.create(t).rest(He.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||$e.create([]).rest(He.create()),returns:n||He.create(),typeName:P.ZodFunction,...M(r)})}},it=class extends N{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};it.create=(e,t)=>new it({getter:e,typeName:P.ZodLazy,...M(t)});var at=class extends N{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return T(t,{received:t.data,code:b.invalid_literal,expected:this._def.value}),D}return{status:`valid`,value:e.data}}get value(){return this._def.value}};at.create=(e,t)=>new at({value:e,typeName:P.ZodLiteral,...M(t)});function ot(e,t){return new st({values:e,typeName:P.ZodEnum,...M(t)})}var st=class e extends N{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return T(t,{expected:_.joinValues(n),received:t.parsedType,code:b.invalid_type}),D}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return T(t,{received:t.data,code:b.invalid_enum_value,options:n}),D}return O(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};st.create=ot;var ct=class extends N{_parse(e){let t=_.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==v.string&&n.parsedType!==v.number){let e=_.objectValues(t);return T(n,{expected:_.joinValues(e),received:n.parsedType,code:b.invalid_type}),D}if(this._cache||=new Set(_.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=_.objectValues(t);return T(n,{received:n.data,code:b.invalid_enum_value,options:e}),D}return O(e.data)}get enum(){return this._def.values}};ct.create=(e,t)=>new ct({values:e,typeName:P.ZodNativeEnum,...M(t)});var lt=class extends N{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==v.promise&&t.common.async===!1)return T(t,{code:b.invalid_type,expected:v.promise,received:t.parsedType}),D;let n=t.parsedType===v.promise?t.data:Promise.resolve(t.data);return O(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};lt.create=(e,t)=>new lt({type:e,typeName:P.ZodPromise,...M(t)});var ut=class extends N{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===P.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{T(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return D;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?D:r.status===`dirty`||t.value===`dirty`?ie(r.value):r});{if(t.value===`aborted`)return D;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?D:r.status===`dirty`||t.value===`dirty`?ie(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?D:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?D:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`)if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!k(e))return D;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>k(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):D);_.assertNever(r)}};ut.create=(e,t,n)=>new ut({schema:e,typeName:P.ZodEffects,effect:t,...M(n)}),ut.createWithPreprocess=(e,t,n)=>new ut({schema:t,effect:{type:`preprocess`,transform:e},typeName:P.ZodEffects,...M(n)});var dt=class extends N{_parse(e){return this._getType(e)===v.undefined?O(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};dt.create=(e,t)=>new dt({innerType:e,typeName:P.ZodOptional,...M(t)});var ft=class extends N{_parse(e){return this._getType(e)===v.null?O(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ft.create=(e,t)=>new ft({innerType:e,typeName:P.ZodNullable,...M(t)});var pt=class extends N{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===v.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};pt.create=(e,t)=>new pt({innerType:e,typeName:P.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...M(t)});var mt=class extends N{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return se(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new x(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new x(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};mt.create=(e,t)=>new mt({innerType:e,typeName:P.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...M(t)});var ht=class extends N{_parse(e){if(this._getType(e)!==v.nan){let t=this._getOrReturnCtx(e);return T(t,{code:b.invalid_type,expected:v.nan,received:t.parsedType}),D}return{status:`valid`,value:e.data}}};ht.create=e=>new ht({typeName:P.ZodNaN,...M(e)});var gt=class extends N{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},_t=class e extends N{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?D:e.status===`dirty`?(t.dirty(),ie(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?D:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:P.ZodPipeline})}},vt=class extends N{_parse(e){let t=this._def.innerType._parse(e),n=e=>(k(e)&&(e.value=Object.freeze(e.value)),e);return se(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};vt.create=(e,t)=>new vt({innerType:e,typeName:P.ZodReadonly,...M(t)}),qe.lazycreate;var P;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(P||={});const F=Me.create,I=Pe.create;ht.create,Fe.create;const L=Ie.create;Le.create,Re.create,ze.create,Be.create;const yt=Ve.create,bt=He.create;Ue.create,We.create;const R=Ge.create,z=qe.create;qe.strictCreate;const B=Je.create,xt=Xe.create;Qe.create,$e.create;const St=et.create;tt.create,nt.create,rt.create,it.create;const V=at.create,Ct=st.create;ct.create,lt.create,ut.create;const H=dt.create;ft.create,ut.createWithPreprocess,_t.create;const wt=D,Tt=`2025-06-18`,Et=`2025-03-26`,Dt=[Tt,`2025-03-26`,`2024-11-05`,`2024-10-07`],Ot=B([F(),I().int()]),kt=F(),At=z({progressToken:H(Ot)}).passthrough(),U=z({_meta:H(At)}).passthrough(),W=z({method:F(),params:H(U)}),jt=z({_meta:H(z({}).passthrough())}).passthrough(),Mt=z({method:F(),params:H(jt)}),G=z({_meta:H(z({}).passthrough())}).passthrough(),Nt=B([F(),I().int()]),Pt=z({jsonrpc:V(`2.0`),id:Nt}).merge(W).strict(),Ft=e=>Pt.safeParse(e).success,It=z({jsonrpc:V(`2.0`)}).merge(Mt).strict(),Lt=e=>It.safeParse(e).success,Rt=z({jsonrpc:V(`2.0`),id:Nt,result:G}).strict(),zt=e=>Rt.safeParse(e).success;var Bt;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`})(Bt||={});const Vt=z({jsonrpc:V(`2.0`),id:Nt,error:z({code:I().int(),message:F(),data:H(bt())})}).strict(),Ht=e=>Vt.safeParse(e).success,Ut=B([Pt,It,Rt,Vt]),Wt=G.strict(),Gt=Mt.extend({method:V(`notifications/cancelled`),params:jt.extend({requestId:Nt,reason:F().optional()})}),Kt=z({src:F(),mimeType:H(F()),sizes:H(F())}).passthrough(),qt=z({name:F(),title:H(F())}).passthrough(),Jt=qt.extend({version:F(),websiteUrl:H(F()),icons:H(R(Kt))}),Yt=z({experimental:H(z({}).passthrough()),sampling:H(z({}).passthrough()),elicitation:H(z({}).passthrough()),roots:H(z({listChanged:H(L())}).passthrough())}).passthrough(),Xt=W.extend({method:V(`initialize`),params:U.extend({protocolVersion:F(),capabilities:Yt,clientInfo:Jt})}),Zt=e=>Xt.safeParse(e).success,Qt=z({experimental:H(z({}).passthrough()),logging:H(z({}).passthrough()),completions:H(z({}).passthrough()),prompts:H(z({listChanged:H(L())}).passthrough()),resources:H(z({subscribe:H(L()),listChanged:H(L())}).passthrough()),tools:H(z({listChanged:H(L())}).passthrough())}).passthrough(),$t=G.extend({protocolVersion:F(),capabilities:Qt,serverInfo:Jt,instructions:H(F())}),en=Mt.extend({method:V(`notifications/initialized`)}),tn=e=>en.safeParse(e).success,nn=W.extend({method:V(`ping`)}),rn=z({progress:I(),total:H(I()),message:H(F())}).passthrough(),an=Mt.extend({method:V(`notifications/progress`),params:jt.merge(rn).extend({progressToken:Ot})}),on=W.extend({params:U.extend({cursor:H(kt)}).optional()}),sn=G.extend({nextCursor:H(kt)}),cn=z({uri:F(),mimeType:H(F()),_meta:H(z({}).passthrough())}).passthrough(),ln=cn.extend({text:F()}),un=F().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),dn=cn.extend({blob:un}),fn=qt.extend({uri:F(),description:H(F()),mimeType:H(F()),icons:H(R(Kt)),_meta:H(z({}).passthrough())}),pn=qt.extend({uriTemplate:F(),description:H(F()),mimeType:H(F()),_meta:H(z({}).passthrough())}),mn=on.extend({method:V(`resources/list`)}),hn=sn.extend({resources:R(fn)}),gn=on.extend({method:V(`resources/templates/list`)}),_n=sn.extend({resourceTemplates:R(pn)}),vn=W.extend({method:V(`resources/read`),params:U.extend({uri:F()})}),yn=G.extend({contents:R(B([ln,dn]))}),bn=Mt.extend({method:V(`notifications/resources/list_changed`)}),xn=W.extend({method:V(`resources/subscribe`),params:U.extend({uri:F()})}),Sn=W.extend({method:V(`resources/unsubscribe`),params:U.extend({uri:F()})}),Cn=Mt.extend({method:V(`notifications/resources/updated`),params:jt.extend({uri:F()})}),wn=z({name:F(),description:H(F()),required:H(L())}).passthrough(),Tn=qt.extend({description:H(F()),arguments:H(R(wn)),icons:H(R(Kt)),_meta:H(z({}).passthrough())}),En=on.extend({method:V(`prompts/list`)}),Dn=sn.extend({prompts:R(Tn)}),On=W.extend({method:V(`prompts/get`),params:U.extend({name:F(),arguments:H(St(F()))})}),kn=z({type:V(`text`),text:F(),_meta:H(z({}).passthrough())}).passthrough(),An=z({type:V(`image`),data:un,mimeType:F(),_meta:H(z({}).passthrough())}).passthrough(),jn=z({type:V(`audio`),data:un,mimeType:F(),_meta:H(z({}).passthrough())}).passthrough(),Mn=z({type:V(`resource`),resource:B([ln,dn]),_meta:H(z({}).passthrough())}).passthrough(),Nn=fn.extend({type:V(`resource_link`)}),Pn=B([kn,An,jn,Nn,Mn]),Fn=z({role:Ct([`user`,`assistant`]),content:Pn}).passthrough(),In=G.extend({description:H(F()),messages:R(Fn)}),Ln=Mt.extend({method:V(`notifications/prompts/list_changed`)}),Rn=z({title:H(F()),readOnlyHint:H(L()),destructiveHint:H(L()),idempotentHint:H(L()),openWorldHint:H(L())}).passthrough(),zn=qt.extend({description:H(F()),inputSchema:z({type:V(`object`),properties:H(z({}).passthrough()),required:H(R(F()))}).passthrough(),outputSchema:H(z({type:V(`object`),properties:H(z({}).passthrough()),required:H(R(F()))}).passthrough()),annotations:H(Rn),icons:H(R(Kt)),_meta:H(z({}).passthrough())}),Bn=on.extend({method:V(`tools/list`)}),Vn=sn.extend({tools:R(zn)}),Hn=G.extend({content:R(Pn).default([]),structuredContent:z({}).passthrough().optional(),isError:H(L())});Hn.or(G.extend({toolResult:bt()}));const Un=W.extend({method:V(`tools/call`),params:U.extend({name:F(),arguments:H(St(bt()))})}),Wn=Mt.extend({method:V(`notifications/tools/list_changed`)}),Gn=Ct([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Kn=W.extend({method:V(`logging/setLevel`),params:U.extend({level:Gn})}),qn=Mt.extend({method:V(`notifications/message`),params:jt.extend({level:Gn,logger:H(F()),data:bt()})}),Jn=z({name:F().optional()}).passthrough(),Yn=z({hints:H(R(Jn)),costPriority:H(I().min(0).max(1)),speedPriority:H(I().min(0).max(1)),intelligencePriority:H(I().min(0).max(1))}).passthrough(),Xn=z({role:Ct([`user`,`assistant`]),content:B([kn,An,jn])}).passthrough(),Zn=W.extend({method:V(`sampling/createMessage`),params:U.extend({messages:R(Xn),systemPrompt:H(F()),includeContext:H(Ct([`none`,`thisServer`,`allServers`])),temperature:H(I()),maxTokens:I().int(),stopSequences:H(R(F())),metadata:H(z({}).passthrough()),modelPreferences:H(Yn)})}),Qn=G.extend({model:F(),stopReason:H(Ct([`endTurn`,`stopSequence`,`maxTokens`]).or(F())),role:Ct([`user`,`assistant`]),content:xt(`type`,[kn,An,jn])}),$n=z({type:V(`boolean`),title:H(F()),description:H(F()),default:H(L())}).passthrough(),er=z({type:V(`string`),title:H(F()),description:H(F()),minLength:H(I()),maxLength:H(I()),format:H(Ct([`email`,`uri`,`date`,`date-time`]))}).passthrough(),tr=z({type:Ct([`number`,`integer`]),title:H(F()),description:H(F()),minimum:H(I()),maximum:H(I())}).passthrough(),nr=z({type:V(`string`),title:H(F()),description:H(F()),enum:R(F()),enumNames:H(R(F()))}).passthrough(),rr=B([$n,er,tr,nr]),ir=W.extend({method:V(`elicitation/create`),params:U.extend({message:F(),requestedSchema:z({type:V(`object`),properties:St(F(),rr),required:H(R(F()))}).passthrough()})}),ar=G.extend({action:Ct([`accept`,`decline`,`cancel`]),content:H(St(F(),bt()))}),or=z({type:V(`ref/resource`),uri:F()}).passthrough(),sr=z({type:V(`ref/prompt`),name:F()}).passthrough(),cr=W.extend({method:V(`completion/complete`),params:U.extend({ref:B([sr,or]),argument:z({name:F(),value:F()}).passthrough(),context:H(z({arguments:H(St(F(),F()))}))})}),lr=G.extend({completion:z({values:R(F()).max(100),total:H(I().int()),hasMore:H(L())}).passthrough()}),ur=z({uri:F().startsWith(`file://`),name:H(F()),_meta:H(z({}).passthrough())}).passthrough(),dr=W.extend({method:V(`roots/list`)}),fr=G.extend({roots:R(ur)}),pr=Mt.extend({method:V(`notifications/roots/list_changed`)});B([nn,Xt,cr,Kn,On,En,mn,gn,vn,xn,Sn,Un,Bn]),B([Gt,an,en,pr]),B([Wt,Qn,ar,fr]),B([nn,Zn,ir,dr]),B([Gt,an,qn,Cn,bn,Wn,Ln]),B([Wt,$t,lr,In,Dn,hn,_n,yn,Hn,Vn]);var mr=class extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}};const hr={APP_VERSION:`1.0.61`},K=p.get,gr=hr.APP_VERSION,_r=e=>{let t={};if(e){let n=e.split(`,`);for(let e of n){let[n,...r]=e.split(`:`);n&&r.length>0&&(t[n.trim()]=r.join(`:`).trim())}}return t},vr=e=>{try{let t=new URL(e),n=t.pathname.split(`/`).filter(Boolean)[0]===`ingest`?`/ingest`:``;return`${t.protocol}//${t.host}${n}/endpoint-logs`}catch{return null}},yr=/\/guard\/evaluate\/v1(\/?)$/,br=e=>{try{let t=new URL(e),n=t.pathname.replace(yr,`/access-control/authorize$1`);return n===t.pathname?(console.warn(`[mcp-gateway] Warning: SCANNER_URL does not contain expected path "/guard/evaluate/v1". Access control URL derivation skipped. Current path: "${t.pathname}". Please set MCP_GATEWAY_ACCESS_CONTROL_URL explicitly.`),null):(t.pathname=n,t.toString())}catch(e){return console.warn(`[mcp-gateway] Warning: Failed to parse SCANNER_URL as valid URL: ${e instanceof Error?e.message:String(e)}. Please set MCP_GATEWAY_ACCESS_CONTROL_URL explicitly.`),null}},xr=r(),Sr=K(`MCP_GATEWAY_DEBUG`).default(`false`).asBool(),Cr=K(`MCP_GATEWAY_SCANNER_URL`).default(``).asString()||null,wr=K(`MCP_GATEWAY_SCANNER_API_KEY`).default(``).asString()||void 0,Tr=K(`MCP_GATEWAY_MIRROR_URL`).default(``).asString()||null,Er=(()=>{let e=K(`MCP_GATEWAY_SCANNER_HEADERS`).required(!1).asString();return e?_r(e):{}})(),Dr=K(`MCP_GATEWAY_SCANNER_TIMEOUT_MS`).default(`20000`).asIntPositive(),Or=K(`MCP_GATEWAY_SCANNER_FAIL_OPEN`).default(`true`).asBool(),kr=K(`MCP_GATEWAY_COMMAND`).default(`mcp-gateway`).asString(),Ar=K(`CLIENT_APP_NAME`).default(``).asString(),jr=K(`MCP_GATEWAY_LOG_DIR`).default(l(h(),`.onyx`,`mcp-gateway`,`logs`)).asString(),Mr=K(`MCP_GATEWAY_OAUTH_DIR`).default(l(h(),`.onyx`,`mcp-gateway`,`oauth`)).asString(),Nr=(()=>K(`MCP_GATEWAY_ACCESS_CONTROL_URL`).default(``).asString()||(Cr?br(Cr):null))(),Pr=(()=>{let e=K(`MCP_GATEWAY_ACCESS_CONTROL_HEADERS`).required(!1).asString();return e?_r(e):{}})(),Fr=K(`MCP_GATEWAY_ACCESS_CONTROL_TIMEOUT_MS`).default(`3000`).asIntPositive(),Ir=K(`MCP_GATEWAY_OAUTH_PROVIDERS_URL`).default(``).asString()||null,Lr=K(`MCP_GATEWAY_OAUTH_PROVIDERS_TIMEOUT_MS`).default(`5000`).asIntPositive(),Rr=K(`MCP_GATEWAY_LOG_INGEST_ENABLED`).default(`true`).asBool(),zr=K(`MCP_GATEWAY_LOG_INGEST_TIMEOUT_MS`).default(`5000`).asIntPositive(),Br=(()=>K(`MCP_GATEWAY_LOG_INGEST_URL`).default(``).asString()||(Tr?vr(Tr):Cr?vr(Cr):null))(),q={accessControl:{enabled:!!(Nr&&wr),headers:Pr,timeoutMs:Fr,url:Nr},appVersion:gr,clientAppName:Ar,debug:Sr,logDir:jr,logIngest:{apiKey:wr,enabled:Rr&&!!(Br&&wr),timeoutMs:zr,url:Br},oauthDir:Mr,oauthProviders:{apiKey:wr,enabled:!!(Ir&&wr),timeoutMs:Lr,url:Ir},proxyCommand:kr,scanner:{apiKey:wr,enabled:!!Cr,failOpen:Or,headers:Er,timeoutMs:Dr,url:Cr}};async function Vr(e){let t=Wr();if(!t)return;let n=Ur(e);if(!n){await te(e,t.uid,t.gid);return}for(let e of n)await te(e,t.uid,t.gid)}function Hr(e){let t=Wr();if(!t)return;let n=Ur(e);if(!n){o(e,t.uid,t.gid);return}for(let e of n)o(e,t.uid,t.gid)}function Ur(e){if(!e.startsWith(u))return;let t=e.split(u),n=t.indexOf(`.onyx`);if(n===-1)return;let r=[];for(let e=n;e<t.length;e++)r.push(t.slice(0,e+1).join(u));return r}function Wr(){if(typeof process.getuid!=`function`||process.getuid()!==0)return;let e=process.env.SUDO_UID,t=process.env.SUDO_GID;if(!e||!t)return;let n=parseInt(e,10),r=parseInt(t,10);if(!(isNaN(n)||isNaN(r)))return{gid:r,uid:n}}var Gr=e(((exports,n)=>{n.exports=t(`util`).deprecate})),Kr=e(((exports,n)=>{n.exports=t(`stream`)})),qr=e(((exports,t)=>{function n(e,t){var n=this,a=this._readableState&&this._readableState.destroyed,s=this._writableState&&this._writableState.destroyed;return a||s?(t?t(e):e&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(o,this,e)):process.nextTick(o,this,e)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(e){!t&&e?n._writableState?n._writableState.errorEmitted?process.nextTick(i,n):(n._writableState.errorEmitted=!0,process.nextTick(r,n,e)):process.nextTick(r,n,e):t?(process.nextTick(i,n),t(e)):process.nextTick(i,n)}),this)}function r(e,t){o(e,t),i(e)}function i(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit(`close`)}function a(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function o(e,t){e.emit(`error`,t)}function s(e,t){var n=e._readableState,r=e._writableState;n&&n.autoDestroy||r&&r.autoDestroy?e.destroy(t):e.emit(`error`,t)}t.exports={destroy:n,undestroy:a,errorOrDestroy:s}})),Jr=e(((exports,t)=>{let n={};function r(e,t,r){r||=Error;function i(e,n,r){return typeof t==`string`?t:t(e,n,r)}class a extends r{constructor(e,t,n){super(i(e,t,n))}}a.prototype.name=r.name,a.prototype.code=e,n[e]=a}function i(e,t){if(Array.isArray(e)){let n=e.length;return e=e.map(e=>String(e)),n>2?`one of ${t} ${e.slice(0,n-1).join(`, `)}, or `+e[n-1]:n===2?`one of ${t} ${e[0]} or ${e[1]}`:`of ${t} ${e[0]}`}else return`of ${t} ${String(e)}`}function a(e,t,n){return e.substr(!n||n<0?0:+n,t.length)===t}function o(e,t,n){return(n===void 0||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t}function s(e,t,n){return typeof n!=`number`&&(n=0),n+t.length>e.length?!1:e.indexOf(t,n)!==-1}r(`ERR_INVALID_OPT_VALUE`,function(e,t){return`The value "`+t+`" is invalid for option "`+e+`"`},TypeError),r(`ERR_INVALID_ARG_TYPE`,function(e,t,n){let r;typeof t==`string`&&a(t,`not `)?(r=`must not be`,t=t.replace(/^not /,``)):r=`must be`;let c;if(o(e,` argument`))c=`The ${e} ${r} ${i(t,`type`)}`;else{let n=s(e,`.`)?`property`:`argument`;c=`The "${e}" ${n} ${r} ${i(t,`type`)}`}return c+=`. Received type ${typeof n}`,c},TypeError),r(`ERR_STREAM_PUSH_AFTER_EOF`,`stream.push() after EOF`),r(`ERR_METHOD_NOT_IMPLEMENTED`,function(e){return`The `+e+` method is not implemented`}),r(`ERR_STREAM_PREMATURE_CLOSE`,`Premature close`),r(`ERR_STREAM_DESTROYED`,function(e){return`Cannot call `+e+` after a stream was destroyed`}),r(`ERR_MULTIPLE_CALLBACK`,`Callback called multiple times`),r(`ERR_STREAM_CANNOT_PIPE`,`Cannot pipe, not readable`),r(`ERR_STREAM_WRITE_AFTER_END`,`write after end`),r(`ERR_STREAM_NULL_VALUES`,`May not write null values to stream`,TypeError),r(`ERR_UNKNOWN_ENCODING`,function(e){return`Unknown encoding: `+e},TypeError),r(`ERR_STREAM_UNSHIFT_AFTER_END_EVENT`,`stream.unshift() after end event`),t.exports.codes=n})),Yr=e(((exports,t)=>{var n=Jr().codes.ERR_INVALID_OPT_VALUE;function r(e,t,n){return e.highWaterMark==null?t?e[n]:null:e.highWaterMark}function i(e,t,i,a){var o=r(t,a,i);if(o!=null){if(!(isFinite(o)&&Math.floor(o)===o)||o<0)throw new n(a?i:`highWaterMark`,o);return Math.floor(o)}return e.objectMode?16:16*1024}t.exports={getHighWaterMark:i}})),Xr=e(((exports,t)=>{typeof Object.create==`function`?t.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:t.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}})),Zr=e(((exports,n)=>{try{var r=t(`util`);if(typeof r.inherits!=`function`)throw``;n.exports=r.inherits}catch{n.exports=Xr()}})),Qr=e(((exports,n)=>{function r(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function i(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?r(Object(n),!0).forEach(function(t){a(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):r(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function a(e,t,n){return t=l(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function s(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,l(r.key),r)}}function c(e,t,n){return t&&s(e.prototype,t),n&&s(e,n),Object.defineProperty(e,`prototype`,{writable:!1}),e}function l(e){var t=u(e,`string`);return typeof t==`symbol`?t:String(t)}function u(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var d=t(`buffer`),f=d.Buffer,p=t(`util`),m=p.inspect,h=m&&m.custom||`inspect`;function g(e,t,n){f.prototype.copy.call(e,t,n)}n.exports=function(){function e(){o(this,e),this.head=null,this.tail=null,this.length=0}return c(e,[{key:`push`,value:function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:`unshift`,value:function(e){var t={data:e,next:this.head};this.length===0&&(this.tail=t),this.head=t,++this.length}},{key:`shift`,value:function(){if(this.length!==0){var e=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,e}}},{key:`clear`,value:function(){this.head=this.tail=null,this.length=0}},{key:`join`,value:function(e){if(this.length===0)return``;for(var t=this.head,n=``+t.data;t=t.next;)n+=e+t.data;return n}},{key:`concat`,value:function(e){if(this.length===0)return f.alloc(0);for(var t=f.allocUnsafe(e>>>0),n=this.head,r=0;n;)g(n.data,t,r),r+=n.data.length,n=n.next;return t}},{key:`consume`,value:function(e,t){var n;return e<this.head.data.length?(n=this.head.data.slice(0,e),this.head.data=this.head.data.slice(e)):n=e===this.head.data.length?this.shift():t?this._getString(e):this._getBuffer(e),n}},{key:`first`,value:function(){return this.head.data}},{key:`_getString`,value:function(e){var t=this.head,n=1,r=t.data;for(e-=r.length;t=t.next;){var i=t.data,a=e>i.length?i.length:e;if(a===i.length?r+=i:r+=i.slice(0,e),e-=a,e===0){a===i.length?(++n,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=i.slice(a));break}++n}return this.length-=n,r}},{key:`_getBuffer`,value:function(e){var t=f.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var i=n.data,a=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,a),e-=a,e===0){a===i.length?(++r,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=i.slice(a));break}++r}return this.length-=r,t}},{key:h,value:function(e,t){return m(this,i(i({},t),{},{depth:0,customInspect:!1}))}}]),e}()})),$r=e(((exports,n)=>{
2
+ /*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
3
+ var r=t(`buffer`),i=r.Buffer;function a(e,t){for(var n in e)t[n]=e[n]}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?n.exports=r:(a(r,exports),exports.Buffer=o);function o(e,t,n){return i(e,t,n)}o.prototype=Object.create(i.prototype),a(i,o),o.from=function(e,t,n){if(typeof e==`number`)throw TypeError(`Argument must not be a number`);return i(e,t,n)},o.alloc=function(e,t,n){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);var r=i(e);return t===void 0?r.fill(0):typeof n==`string`?r.fill(t,n):r.fill(t),r},o.allocUnsafe=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return i(e)},o.allocUnsafeSlow=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return r.SlowBuffer(e)}})),ei=e((exports=>{var t=$r().Buffer,n=t.isEncoding||function(e){switch(e=``+e,e&&e.toLowerCase()){case`hex`:case`utf8`:case`utf-8`:case`ascii`:case`binary`:case`base64`:case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:case`raw`:return!0;default:return!1}};function r(e){if(!e)return`utf8`;for(var t;;)switch(e){case`utf8`:case`utf-8`:return`utf8`;case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return`utf16le`;case`latin1`:case`binary`:return`latin1`;case`base64`:case`ascii`:case`hex`:return e;default:if(t)return;e=(``+e).toLowerCase(),t=!0}}function i(e){var i=r(e);if(typeof i!=`string`&&(t.isEncoding===n||!n(e)))throw Error(`Unknown encoding: `+e);return i||e}exports.StringDecoder=a;function a(e){this.encoding=i(e);var n;switch(this.encoding){case`utf16le`:this.text=f,this.end=p,n=4;break;case`utf8`:this.fillLast=l,n=4;break;case`base64`:this.text=m,this.end=h,n=3;break;default:this.write=g,this.end=ee;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=t.allocUnsafe(n)}a.prototype.write=function(e){if(e.length===0)return``;var t,n;if(this.lastNeed){if(t=this.fillLast(e),t===void 0)return``;n=this.lastNeed,this.lastNeed=0}else n=0;return n<e.length?t?t+this.text(e,n):this.text(e,n):t||``},a.prototype.end=d,a.prototype.text=u,a.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length};function o(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function s(e,t,n){var r=t.length-1;if(r<n)return 0;var i=o(t[r]);return i>=0?(i>0&&(e.lastNeed=i-1),i):--r<n||i===-2?0:(i=o(t[r]),i>=0?(i>0&&(e.lastNeed=i-2),i):--r<n||i===-2?0:(i=o(t[r]),i>=0?(i>0&&(i===2?i=0:e.lastNeed=i-3),i):0))}function c(e,t,n){if((t[0]&192)!=128)return e.lastNeed=0,`�`;if(e.lastNeed>1&&t.length>1){if((t[1]&192)!=128)return e.lastNeed=1,`�`;if(e.lastNeed>2&&t.length>2&&(t[2]&192)!=128)return e.lastNeed=2,`�`}}function l(e){var t=this.lastTotal-this.lastNeed,n=c(this,e,t);if(n!==void 0)return n;if(this.lastNeed<=e.length)return e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,t,0,e.length),this.lastNeed-=e.length}function u(e,t){var n=s(this,e,t);if(!this.lastNeed)return e.toString(`utf8`,t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString(`utf8`,t,r)}function d(e){var t=e&&e.length?this.write(e):``;return this.lastNeed?t+`�`:t}function f(e,t){if((e.length-t)%2==0){var n=e.toString(`utf16le`,t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString(`utf16le`,t,e.length-1)}function p(e){var t=e&&e.length?this.write(e):``;if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString(`utf16le`,0,n)}return t}function m(e,t){var n=(e.length-t)%3;return n===0?e.toString(`base64`,t):(this.lastNeed=3-n,this.lastTotal=3,n===1?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString(`base64`,t,e.length-n))}function h(e){var t=e&&e.length?this.write(e):``;return this.lastNeed?t+this.lastChar.toString(`base64`,0,3-this.lastNeed):t}function g(e){return e.toString(this.encoding)}function ee(e){return e&&e.length?this.write(e):``}})),ti=e(((exports,t)=>{var n=Jr().codes.ERR_STREAM_PREMATURE_CLOSE;function r(e){var t=!1;return function(){if(!t){t=!0;var n=[...arguments];e.apply(this,n)}}}function i(){}function a(e){return e.setHeader&&typeof e.abort==`function`}function o(e,t,s){if(typeof t==`function`)return o(e,null,t);t||={},s=r(s||i);var c=t.readable||t.readable!==!1&&e.readable,l=t.writable||t.writable!==!1&&e.writable,u=function(){e.writable||f()},d=e._writableState&&e._writableState.finished,f=function(){l=!1,d=!0,c||s.call(e)},p=e._readableState&&e._readableState.endEmitted,m=function(){c=!1,p=!0,l||s.call(e)},h=function(t){s.call(e,t)},g=function(){var t;if(c&&!p)return(!e._readableState||!e._readableState.ended)&&(t=new n),s.call(e,t);if(l&&!d)return(!e._writableState||!e._writableState.ended)&&(t=new n),s.call(e,t)},ee=function(){e.req.on(`finish`,f)};return a(e)?(e.on(`complete`,f),e.on(`abort`,g),e.req?ee():e.on(`request`,ee)):l&&!e._writableState&&(e.on(`end`,u),e.on(`close`,u)),e.on(`end`,m),e.on(`finish`,f),t.error!==!1&&e.on(`error`,h),e.on(`close`,g),function(){e.removeListener(`complete`,f),e.removeListener(`abort`,g),e.removeListener(`request`,ee),e.req&&e.req.removeListener(`finish`,f),e.removeListener(`end`,u),e.removeListener(`close`,u),e.removeListener(`finish`,f),e.removeListener(`end`,m),e.removeListener(`error`,h),e.removeListener(`close`,g)}}t.exports=o})),ni=e(((exports,t)=>{var n;function r(e,t,n){return t=i(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e){var t=a(e,`string`);return typeof t==`symbol`?t:String(t)}function a(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var o=ti(),s=Symbol(`lastResolve`),c=Symbol(`lastReject`),l=Symbol(`error`),u=Symbol(`ended`),d=Symbol(`lastPromise`),f=Symbol(`handlePromise`),p=Symbol(`stream`);function m(e,t){return{value:e,done:t}}function h(e){var t=e[s];if(t!==null){var n=e[p].read();n!==null&&(e[d]=null,e[s]=null,e[c]=null,t(m(n,!1)))}}function g(e){process.nextTick(h,e)}function ee(e,t){return function(n,r){e.then(function(){if(t[u]){n(m(void 0,!0));return}t[f](n,r)},r)}}var te=Object.getPrototypeOf(function(){}),_=Object.setPrototypeOf((n={get stream(){return this[p]},next:function(){var e=this,t=this[l];if(t!==null)return Promise.reject(t);if(this[u])return Promise.resolve(m(void 0,!0));if(this[p].destroyed)return new Promise(function(t,n){process.nextTick(function(){e[l]?n(e[l]):t(m(void 0,!0))})});var n=this[d],r;if(n)r=new Promise(ee(n,this));else{var i=this[p].read();if(i!==null)return Promise.resolve(m(i,!1));r=new Promise(this[f])}return this[d]=r,r}},r(n,Symbol.asyncIterator,function(){return this}),r(n,`return`,function(){var e=this;return new Promise(function(t,n){e[p].destroy(null,function(e){if(e){n(e);return}t(m(void 0,!0))})})}),n),te);t.exports=function(e){var t,n=Object.create(_,(t={},r(t,p,{value:e,writable:!0}),r(t,s,{value:null,writable:!0}),r(t,c,{value:null,writable:!0}),r(t,l,{value:null,writable:!0}),r(t,u,{value:e._readableState.endEmitted,writable:!0}),r(t,f,{value:function(e,t){var r=n[p].read();r?(n[d]=null,n[s]=null,n[c]=null,e(m(r,!1))):(n[s]=e,n[c]=t)},writable:!0}),t));return n[d]=null,o(e,function(e){if(e&&e.code!==`ERR_STREAM_PREMATURE_CLOSE`){var t=n[c];t!==null&&(n[d]=null,n[s]=null,n[c]=null,t(e)),n[l]=e;return}var r=n[s];r!==null&&(n[d]=null,n[s]=null,n[c]=null,r(m(void 0,!0))),n[u]=!0}),e.on(`readable`,g.bind(null,n)),n}})),ri=e(((exports,t)=>{function n(e,t,n,r,i,a,o){try{var s=e[a](o),c=s.value}catch(e){n(e);return}s.done?t(c):Promise.resolve(c).then(r,i)}function r(e){return function(){var t=this,r=arguments;return new Promise(function(i,a){var o=e.apply(t,r);function s(e){n(o,i,a,s,c,`next`,e)}function c(e){n(o,i,a,s,c,`throw`,e)}s(void 0)})}}function i(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function a(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?i(Object(n),!0).forEach(function(t){o(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):i(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function o(e,t,n){return t=s(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function s(e){var t=c(e,`string`);return typeof t==`symbol`?t:String(t)}function c(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var l=Jr().codes.ERR_INVALID_ARG_TYPE;function u(e,t,n){var i;if(t&&typeof t.next==`function`)i=t;else if(t&&t[Symbol.asyncIterator])i=t[Symbol.asyncIterator]();else if(t&&t[Symbol.iterator])i=t[Symbol.iterator]();else throw new l(`iterable`,[`Iterable`],t);var o=new e(a({objectMode:!0},n)),s=!1;o._read=function(){s||(s=!0,c())};function c(){return u.apply(this,arguments)}function u(){return u=r(function*(){try{var e=yield i.next(),t=e.value;e.done?o.push(null):o.push(yield t)?c():s=!1}catch(e){o.destroy(e)}}),u.apply(this,arguments)}return o}t.exports=u})),ii=e(((exports,n)=>{n.exports=w;var r;w.ReadableState=C,t(`events`).EventEmitter;var i=function(e,t){return e.listeners(t).length},a=Kr(),o=t(`buffer`).Buffer,s=(typeof global<`u`?global:typeof window<`u`?window:typeof self<`u`?self:{}).Uint8Array||function(){};function c(e){return o.from(e)}function l(e){return o.isBuffer(e)||e instanceof s}var u=t(`util`),d=u&&u.debuglog?u.debuglog(`stream`):function(){},f=Qr(),p=qr(),m=Yr(),h=m.getHighWaterMark,g=Jr().codes,ee=g.ERR_INVALID_ARG_TYPE,te=g.ERR_STREAM_PUSH_AFTER_EOF,_=g.ERR_METHOD_NOT_IMPLEMENTED,ne=g.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,v,y,b;Zr()(w,a);var x=p.errorOrDestroy,S=[`error`,`close`,`destroy`,`pause`,`resume`];function re(e,t,n){if(typeof e.prependListener==`function`)return e.prependListener(t,n);!e._events||!e._events[t]?e.on(t,n):Array.isArray(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]}function C(e,t,n){r||=ai(),e||={},typeof n!=`boolean`&&(n=t instanceof r),this.objectMode=!!e.objectMode,n&&(this.objectMode=this.objectMode||!!e.readableObjectMode),this.highWaterMark=h(this,e,`readableHighWaterMark`,n),this.buffer=new f,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=e.emitClose!==!1,this.autoDestroy=!!e.autoDestroy,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||`utf8`,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(v||=ei().StringDecoder,this.decoder=new v(e.encoding),this.encoding=e.encoding)}function w(e){if(r||=ai(),!(this instanceof w))return new w(e);var t=this instanceof r;this._readableState=new C(e,this,t),this.readable=!0,e&&(typeof e.read==`function`&&(this._read=e.read),typeof e.destroy==`function`&&(this._destroy=e.destroy)),a.call(this)}Object.defineProperty(w.prototype,`destroyed`,{enumerable:!1,get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),w.prototype.destroy=p.destroy,w.prototype._undestroy=p.undestroy,w.prototype._destroy=function(e,t){t(e)},w.prototype.push=function(e,t){var n=this._readableState,r;return n.objectMode?r=!0:typeof e==`string`&&(t||=n.defaultEncoding,t!==n.encoding&&(e=o.from(e,t),t=``),r=!0),T(this,e,t,!1,r)},w.prototype.unshift=function(e){return T(this,e,null,!0,!1)};function T(e,t,n,r,i){d(`readableAddChunk`,t);var a=e._readableState;if(t===null)a.reading=!1,oe(e,a);else{var s;if(i||(s=D(a,t)),s)x(e,s);else if(a.objectMode||t&&t.length>0)if(typeof t!=`string`&&!a.objectMode&&Object.getPrototypeOf(t)!==o.prototype&&(t=c(t)),r)a.endEmitted?x(e,new ne):E(e,a,t,!0);else if(a.ended)x(e,new te);else if(a.destroyed)return!1;else a.reading=!1,a.decoder&&!n?(t=a.decoder.write(t),a.objectMode||t.length!==0?E(e,a,t,!1):A(e,a)):E(e,a,t,!1);else r||(a.reading=!1,A(e,a))}return!a.ended&&(a.length<a.highWaterMark||a.length===0)}function E(e,t,n,r){t.flowing&&t.length===0&&!t.sync?(t.awaitDrain=0,e.emit(`data`,n)):(t.length+=t.objectMode?1:n.length,r?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&k(e)),A(e,t)}function D(e,t){var n;return!l(t)&&typeof t!=`string`&&t!==void 0&&!e.objectMode&&(n=new ee(`chunk`,[`string`,`Buffer`,`Uint8Array`],t)),n}w.prototype.isPaused=function(){return this._readableState.flowing===!1},w.prototype.setEncoding=function(e){v||=ei().StringDecoder;var t=new v(e);this._readableState.decoder=t,this._readableState.encoding=this._readableState.decoder.encoding;for(var n=this._readableState.buffer.head,r=``;n!==null;)r+=t.write(n.data),n=n.next;return this._readableState.buffer.clear(),r!==``&&this._readableState.buffer.push(r),this._readableState.length=r.length,this};var ie=1073741824;function O(e){return e>=ie?e=ie:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function ae(e,t){return e<=0||t.length===0&&t.ended?0:t.objectMode?1:e===e?(e>t.highWaterMark&&(t.highWaterMark=O(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0)):t.flowing&&t.length?t.buffer.head.data.length:t.length}w.prototype.read=function(e){d(`read`,e),e=parseInt(e,10);var t=this._readableState,n=e;if(e!==0&&(t.emittedReadable=!1),e===0&&t.needReadable&&((t.highWaterMark===0?t.length>0:t.length>=t.highWaterMark)||t.ended))return d(`read: emitReadable`,t.length,t.ended),t.length===0&&t.ended?pe(this):k(this),null;if(e=ae(e,t),e===0&&t.ended)return t.length===0&&pe(this),null;var r=t.needReadable;d(`need readable`,r),(t.length===0||t.length-e<t.highWaterMark)&&(r=!0,d(`length less than watermark`,r)),t.ended||t.reading?(r=!1,d(`reading or ended`,r)):r&&(d(`do read`),t.reading=!0,t.sync=!0,t.length===0&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=ae(n,t)));var i=e>0?fe(e,t):null;return i===null?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),t.length===0&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&pe(this)),i!==null&&this.emit(`data`,i),i};function oe(e,t){if(d(`onEofChunk`),!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?k(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,se(e)))}}function k(e){var t=e._readableState;d(`emitReadable`,t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(d(`emitReadable`,t.flowing),t.emittedReadable=!0,process.nextTick(se,e))}function se(e){var t=e._readableState;d(`emitReadable_`,t.destroyed,t.length,t.ended),!t.destroyed&&(t.length||t.ended)&&(e.emit(`readable`),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,de(e)}function A(e,t){t.readingMore||(t.readingMore=!0,process.nextTick(j,e,t))}function j(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&t.length===0);){var n=t.length;if(d(`maybeReadMore read 0`),e.read(0),n===t.length)break}t.readingMore=!1}w.prototype._read=function(e){x(this,new _(`_read()`))},w.prototype.pipe=function(e,t){var n=this,r=this._readableState;switch(r.pipesCount){case 0:r.pipes=e;break;case 1:r.pipes=[r.pipes,e];break;default:r.pipes.push(e);break}r.pipesCount+=1,d(`pipe count=%d opts=%j`,r.pipesCount,t);var a=(!t||t.end!==!1)&&e!==process.stdout&&e!==process.stderr?s:g;r.endEmitted?process.nextTick(a):n.once(`end`,a),e.on(`unpipe`,o);function o(e,t){d(`onunpipe`),e===n&&t&&t.hasUnpiped===!1&&(t.hasUnpiped=!0,u())}function s(){d(`onend`),e.end()}var c=ce(n);e.on(`drain`,c);var l=!1;function u(){d(`cleanup`),e.removeListener(`close`,m),e.removeListener(`finish`,h),e.removeListener(`drain`,c),e.removeListener(`error`,p),e.removeListener(`unpipe`,o),n.removeListener(`end`,s),n.removeListener(`end`,g),n.removeListener(`data`,f),l=!0,r.awaitDrain&&(!e._writableState||e._writableState.needDrain)&&c()}n.on(`data`,f);function f(t){d(`ondata`);var i=e.write(t);d(`dest.write`,i),i===!1&&((r.pipesCount===1&&r.pipes===e||r.pipesCount>1&&he(r.pipes,e)!==-1)&&!l&&(d(`false write response, pause`,r.awaitDrain),r.awaitDrain++),n.pause())}function p(t){d(`onerror`,t),g(),e.removeListener(`error`,p),i(e,`error`)===0&&x(e,t)}re(e,`error`,p);function m(){e.removeListener(`finish`,h),g()}e.once(`close`,m);function h(){d(`onfinish`),e.removeListener(`close`,m),g()}e.once(`finish`,h);function g(){d(`unpipe`),n.unpipe(e)}return e.emit(`pipe`,n),r.flowing||(d(`pipe resume`),n.resume()),e};function ce(e){return function(){var t=e._readableState;d(`pipeOnDrain`,t.awaitDrain),t.awaitDrain&&t.awaitDrain--,t.awaitDrain===0&&i(e,`data`)&&(t.flowing=!0,de(e))}}w.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(t.pipesCount===0)return this;if(t.pipesCount===1)return e&&e!==t.pipes?this:(e||=t.pipes,t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit(`unpipe`,this,n),this);if(!e){var r=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var a=0;a<i;a++)r[a].emit(`unpipe`,this,{hasUnpiped:!1});return this}var o=he(t.pipes,e);return o===-1?this:(t.pipes.splice(o,1),--t.pipesCount,t.pipesCount===1&&(t.pipes=t.pipes[0]),e.emit(`unpipe`,this,n),this)},w.prototype.on=function(e,t){var n=a.prototype.on.call(this,e,t),r=this._readableState;return e===`data`?(r.readableListening=this.listenerCount(`readable`)>0,r.flowing!==!1&&this.resume()):e===`readable`&&!r.endEmitted&&!r.readableListening&&(r.readableListening=r.needReadable=!0,r.flowing=!1,r.emittedReadable=!1,d(`on readable`,r.length,r.reading),r.length?k(this):r.reading||process.nextTick(N,this)),n},w.prototype.addListener=w.prototype.on,w.prototype.removeListener=function(e,t){var n=a.prototype.removeListener.call(this,e,t);return e===`readable`&&process.nextTick(M,this),n},w.prototype.removeAllListeners=function(e){var t=a.prototype.removeAllListeners.apply(this,arguments);return(e===`readable`||e===void 0)&&process.nextTick(M,this),t};function M(e){var t=e._readableState;t.readableListening=e.listenerCount(`readable`)>0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount(`data`)>0&&e.resume()}function N(e){d(`readable nexttick read 0`),e.read(0)}w.prototype.resume=function(){var e=this._readableState;return e.flowing||(d(`resume`),e.flowing=!e.readableListening,le(this,e)),e.paused=!1,this};function le(e,t){t.resumeScheduled||(t.resumeScheduled=!0,process.nextTick(ue,e,t))}function ue(e,t){d(`resume`,t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit(`resume`),de(e),t.flowing&&!t.reading&&e.read(0)}w.prototype.pause=function(){return d(`call pause flowing=%j`,this._readableState.flowing),this._readableState.flowing!==!1&&(d(`pause`),this._readableState.flowing=!1,this.emit(`pause`)),this._readableState.paused=!0,this};function de(e){var t=e._readableState;for(d(`flow`,t.flowing);t.flowing&&e.read()!==null;);}w.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var i in e.on(`end`,function(){if(d(`wrapped end`),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)}),e.on(`data`,function(i){d(`wrapped data`),n.decoder&&(i=n.decoder.write(i)),!(n.objectMode&&i==null)&&(!n.objectMode&&(!i||!i.length)||t.push(i)||(r=!0,e.pause()))}),e)this[i]===void 0&&typeof e[i]==`function`&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));for(var a=0;a<S.length;a++)e.on(S[a],this.emit.bind(this,S[a]));return this._read=function(t){d(`wrapped _read`,t),r&&(r=!1,e.resume())},this},typeof Symbol==`function`&&(w.prototype[Symbol.asyncIterator]=function(){return y===void 0&&(y=ni()),y(this)}),Object.defineProperty(w.prototype,`readableHighWaterMark`,{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(w.prototype,`readableBuffer`,{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(w.prototype,`readableFlowing`,{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),w._fromList=fe,Object.defineProperty(w.prototype,`readableLength`,{enumerable:!1,get:function(){return this._readableState.length}});function fe(e,t){if(t.length===0)return null;var n;return t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(``):t.buffer.length===1?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n}function pe(e){var t=e._readableState;d(`endReadable`,t.endEmitted),t.endEmitted||(t.ended=!0,process.nextTick(me,t,e))}function me(e,t){if(d(`endReadableNT`,e.endEmitted,e.length),!e.endEmitted&&e.length===0&&(e.endEmitted=!0,t.readable=!1,t.emit(`end`),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy()}}typeof Symbol==`function`&&(w.from=function(e,t){return b===void 0&&(b=ri()),b(w,e,t)});function he(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}})),ai=e(((exports,t)=>{var n=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=c;var r=ii(),i=oi();Zr()(c,r);for(var a=n(i.prototype),o=0;o<a.length;o++){var s=a[o];c.prototype[s]||(c.prototype[s]=i.prototype[s])}function c(e){if(!(this instanceof c))return new c(e);r.call(this,e),i.call(this,e),this.allowHalfOpen=!0,e&&(e.readable===!1&&(this.readable=!1),e.writable===!1&&(this.writable=!1),e.allowHalfOpen===!1&&(this.allowHalfOpen=!1,this.once(`end`,l)))}Object.defineProperty(c.prototype,`writableHighWaterMark`,{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(c.prototype,`writableBuffer`,{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(c.prototype,`writableLength`,{enumerable:!1,get:function(){return this._writableState.length}});function l(){this._writableState.ended||process.nextTick(u,this)}function u(e){e.end()}Object.defineProperty(c.prototype,`destroyed`,{enumerable:!1,get:function(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set:function(e){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=e,this._writableState.destroyed=e)}})})),oi=e(((exports,n)=>{n.exports=C;function r(e){var t=this;this.next=null,this.entry=null,this.finish=function(){ue(t,e)}}var i;C.WritableState=S;var a={deprecate:Gr()},o=Kr(),s=t(`buffer`).Buffer,c=(typeof global<`u`?global:typeof window<`u`?window:typeof self<`u`?self:{}).Uint8Array||function(){};function l(e){return s.from(e)}function u(e){return s.isBuffer(e)||e instanceof c}var d=qr(),f=Yr(),p=f.getHighWaterMark,m=Jr().codes,h=m.ERR_INVALID_ARG_TYPE,g=m.ERR_METHOD_NOT_IMPLEMENTED,ee=m.ERR_MULTIPLE_CALLBACK,te=m.ERR_STREAM_CANNOT_PIPE,_=m.ERR_STREAM_DESTROYED,ne=m.ERR_STREAM_NULL_VALUES,v=m.ERR_STREAM_WRITE_AFTER_END,y=m.ERR_UNKNOWN_ENCODING,b=d.errorOrDestroy;Zr()(C,o);function x(){}function S(e,t,n){i||=ai(),e||={},typeof n!=`boolean`&&(n=t instanceof i),this.objectMode=!!e.objectMode,n&&(this.objectMode=this.objectMode||!!e.writableObjectMode),this.highWaterMark=p(this,e,`writableHighWaterMark`,n),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1,this.decodeStrings=e.decodeStrings!==!1,this.defaultEncoding=e.defaultEncoding||`utf8`,this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){oe(t,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=e.emitClose!==!1,this.autoDestroy=!!e.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new r(this)}S.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},(function(){try{Object.defineProperty(S.prototype,`buffer`,{get:a.deprecate(function(){return this.getBuffer()},`_writableState.buffer is deprecated. Use _writableState.getBuffer instead.`,`DEP0003`)})}catch{}})();var re;typeof Symbol==`function`&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==`function`?(re=Function.prototype[Symbol.hasInstance],Object.defineProperty(C,Symbol.hasInstance,{value:function(e){return re.call(this,e)?!0:this===C?e&&e._writableState instanceof S:!1}})):re=function(e){return e instanceof this};function C(e){i||=ai();var t=this instanceof i;if(!t&&!re.call(C,this))return new C(e);this._writableState=new S(e,this,t),this.writable=!0,e&&(typeof e.write==`function`&&(this._write=e.write),typeof e.writev==`function`&&(this._writev=e.writev),typeof e.destroy==`function`&&(this._destroy=e.destroy),typeof e.final==`function`&&(this._final=e.final)),o.call(this)}C.prototype.pipe=function(){b(this,new te)};function w(e,t){var n=new v;b(e,n),process.nextTick(t,n)}function T(e,t,n,r){var i;return n===null?i=new ne:typeof n!=`string`&&!t.objectMode&&(i=new h(`chunk`,[`string`,`Buffer`],n)),i?(b(e,i),process.nextTick(r,i),!1):!0}C.prototype.write=function(e,t,n){var r=this._writableState,i=!1,a=!r.objectMode&&u(e);return a&&!s.isBuffer(e)&&(e=l(e)),typeof t==`function`&&(n=t,t=null),a?t=`buffer`:t||=r.defaultEncoding,typeof n!=`function`&&(n=x),r.ending?w(this,n):(a||T(this,r,e,n))&&(r.pendingcb++,i=D(this,r,a,e,t,n)),i},C.prototype.cork=function(){this._writableState.corked++},C.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest&&A(this,e))},C.prototype.setDefaultEncoding=function(e){if(typeof e==`string`&&(e=e.toLowerCase()),!([`hex`,`utf8`,`utf-8`,`ascii`,`binary`,`base64`,`ucs2`,`ucs-2`,`utf16le`,`utf-16le`,`raw`].indexOf((e+``).toLowerCase())>-1))throw new y(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(C.prototype,`writableBuffer`,{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function E(e,t,n){return!e.objectMode&&e.decodeStrings!==!1&&typeof t==`string`&&(t=s.from(t,n)),t}Object.defineProperty(C.prototype,`writableHighWaterMark`,{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function D(e,t,n,r,i,a){if(!n){var o=E(t,r,i);r!==o&&(n=!0,i=`buffer`,r=o)}var s=t.objectMode?1:r.length;t.length+=s;var c=t.length<t.highWaterMark;if(c||(t.needDrain=!0),t.writing||t.corked){var l=t.lastBufferedRequest;t.lastBufferedRequest={chunk:r,encoding:i,isBuf:n,callback:a,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else ie(e,t,!1,s,r,i,a);return c}function ie(e,t,n,r,i,a,o){t.writelen=r,t.writecb=o,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new _(`write`)):n?e._writev(i,t.onwrite):e._write(i,a,t.onwrite),t.sync=!1}function O(e,t,n,r,i){--t.pendingcb,n?(process.nextTick(i,r),process.nextTick(N,e,t),e._writableState.errorEmitted=!0,b(e,r)):(i(r),e._writableState.errorEmitted=!0,b(e,r),N(e,t))}function ae(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function oe(e,t){var n=e._writableState,r=n.sync,i=n.writecb;if(typeof i!=`function`)throw new ee;if(ae(n),t)O(e,n,r,t,i);else{var a=j(n)||e.destroyed;!a&&!n.corked&&!n.bufferProcessing&&n.bufferedRequest&&A(e,n),r?process.nextTick(k,e,n,a,i):k(e,n,a,i)}}function k(e,t,n,r){n||se(e,t),t.pendingcb--,r(),N(e,t)}function se(e,t){t.length===0&&t.needDrain&&(t.needDrain=!1,e.emit(`drain`))}function A(e,t){t.bufferProcessing=!0;var n=t.bufferedRequest;if(e._writev&&n&&n.next){var i=t.bufferedRequestCount,a=Array(i),o=t.corkedRequestsFree;o.entry=n;for(var s=0,c=!0;n;)a[s]=n,n.isBuf||(c=!1),n=n.next,s+=1;a.allBuffers=c,ie(e,t,!0,t.length,a,``,o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new r(t),t.bufferedRequestCount=0}else{for(;n;){var l=n.chunk,u=n.encoding,d=n.callback,f=t.objectMode?1:l.length;if(ie(e,t,!1,f,l,u,d),n=n.next,t.bufferedRequestCount--,t.writing)break}n===null&&(t.lastBufferedRequest=null)}t.bufferedRequest=n,t.bufferProcessing=!1}C.prototype._write=function(e,t,n){n(new g(`_write()`))},C.prototype._writev=null,C.prototype.end=function(e,t,n){var r=this._writableState;return typeof e==`function`?(n=e,e=null,t=null):typeof t==`function`&&(n=t,t=null),e!=null&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||le(this,r,n),this},Object.defineProperty(C.prototype,`writableLength`,{enumerable:!1,get:function(){return this._writableState.length}});function j(e){return e.ending&&e.length===0&&e.bufferedRequest===null&&!e.finished&&!e.writing}function ce(e,t){e._final(function(n){t.pendingcb--,n&&b(e,n),t.prefinished=!0,e.emit(`prefinish`),N(e,t)})}function M(e,t){!t.prefinished&&!t.finalCalled&&(typeof e._final==`function`&&!t.destroyed?(t.pendingcb++,t.finalCalled=!0,process.nextTick(ce,e,t)):(t.prefinished=!0,e.emit(`prefinish`)))}function N(e,t){var n=j(t);if(n&&(M(e,t),t.pendingcb===0&&(t.finished=!0,e.emit(`finish`),t.autoDestroy))){var r=e._readableState;(!r||r.autoDestroy&&r.endEmitted)&&e.destroy()}return n}function le(e,t,n){t.ending=!0,N(e,t),n&&(t.finished?process.nextTick(n):e.once(`finish`,n)),t.ended=!0,e.writable=!1}function ue(e,t,n){var r=e.entry;for(e.entry=null;r;){var i=r.callback;t.pendingcb--,i(n),r=r.next}t.corkedRequestsFree.next=e}Object.defineProperty(C.prototype,`destroyed`,{enumerable:!1,get:function(){return this._writableState===void 0?!1:this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),C.prototype.destroy=d.destroy,C.prototype._undestroy=d.undestroy,C.prototype._destroy=function(e,t){t(e)}})),si=e((exports=>{exports.levels={error:0,warn:1,help:2,data:3,info:4,debug:5,prompt:6,verbose:7,input:8,silly:9},exports.colors={error:`red`,warn:`yellow`,help:`cyan`,data:`grey`,info:`green`,debug:`blue`,prompt:`grey`,verbose:`cyan`,input:`grey`,silly:`magenta`}})),ci=e((exports=>{exports.levels={error:0,warn:1,info:2,http:3,verbose:4,debug:5,silly:6},exports.colors={error:`red`,warn:`yellow`,info:`green`,http:`green`,verbose:`cyan`,debug:`blue`,silly:`magenta`}})),li=e((exports=>{exports.levels={emerg:0,alert:1,crit:2,error:3,warning:4,notice:5,info:6,debug:7},exports.colors={emerg:`red`,alert:`yellow`,crit:`red`,error:`red`,warning:`red`,notice:`yellow`,info:`green`,debug:`blue`}})),ui=e((exports=>{Object.defineProperty(exports,`cli`,{value:si()}),Object.defineProperty(exports,`npm`,{value:ci()}),Object.defineProperty(exports,`syslog`,{value:li()})})),di=e((exports=>{Object.defineProperty(exports,`LEVEL`,{value:Symbol.for(`level`)}),Object.defineProperty(exports,`MESSAGE`,{value:Symbol.for(`message`)}),Object.defineProperty(exports,`SPLAT`,{value:Symbol.for(`splat`)}),Object.defineProperty(exports,`configs`,{value:ui()})})),fi=e(((exports,n)=>{let r=t(`util`),i=oi(),{LEVEL:a}=di(),o=n.exports=function(e={}){i.call(this,{objectMode:!0,highWaterMark:e.highWaterMark}),this.format=e.format,this.level=e.level,this.handleExceptions=e.handleExceptions,this.handleRejections=e.handleRejections,this.silent=e.silent,e.log&&(this.log=e.log),e.logv&&(this.logv=e.logv),e.close&&(this.close=e.close),this.once(`pipe`,e=>{this.levels=e.levels,this.parent=e}),this.once(`unpipe`,e=>{e===this.parent&&(this.parent=null,this.close&&this.close())})};r.inherits(o,i),o.prototype._write=function(e,t,n){if(this.silent||e.exception===!0&&!this.handleExceptions)return n(null);let r=this.level||this.parent&&this.parent.level;if(!r||this.levels[r]>=this.levels[e[a]]){if(e&&!this.format)return this.log(e,n);let t,r;try{r=this.format.transform(Object.assign({},e),this.format.options)}catch(e){t=e}if(t||!r){if(n(),t)throw t;return}return this.log(r,n)}return this._writableState.sync=!1,n(null)},o.prototype._writev=function(e,t){if(this.logv){let n=e.filter(this._accept,this);return n.length?this.logv(n,t):t(null)}for(let n=0;n<e.length;n++){if(!this._accept(e[n]))continue;if(e[n].chunk&&!this.format){this.log(e[n].chunk,e[n].callback);continue}let r,i;try{i=this.format.transform(Object.assign({},e[n].chunk),this.format.options)}catch(e){r=e}if(r||!i){if(e[n].callback(),r)throw t(null),r}else this.log(i,e[n].callback)}return t(null)},o.prototype._accept=function(e){let t=e.chunk;if(this.silent)return!1;let n=this.level||this.parent&&this.parent.level;return!!((t.exception===!0||!n||this.levels[n]>=this.levels[t[a]])&&(this.handleExceptions||t.exception!==!0))},o.prototype._nop=function(){}})),pi=e(((exports,n)=>{let r=t(`util`),{LEVEL:i}=di(),a=fi(),o=n.exports=function(e={}){if(a.call(this,e),!e.transport||typeof e.transport.log!=`function`)throw Error(`Invalid transport, must be an object with a log method.`);this.transport=e.transport,this.level=this.level||e.transport.level,this.handleExceptions=this.handleExceptions||e.transport.handleExceptions,this._deprecated();function t(e){this.emit(`error`,e,this.transport)}this.transport.__winstonError||(this.transport.__winstonError=t.bind(this),this.transport.on(`error`,this.transport.__winstonError))};r.inherits(o,a),o.prototype._write=function(e,t,n){if(this.silent||e.exception===!0&&!this.handleExceptions)return n(null);(!this.level||this.levels[this.level]>=this.levels[e[i]])&&this.transport.log(e[i],e.message,e,this._nop),n(null)},o.prototype._writev=function(e,t){for(let t=0;t<e.length;t++)this._accept(e[t])&&(this.transport.log(e[t].chunk[i],e[t].chunk.message,e[t].chunk,this._nop),e[t].callback());return t(null)},o.prototype._deprecated=function(){console.error([`${this.transport.name} is a legacy winston transport. Consider upgrading: `,`- Upgrade docs: https://github.com/winstonjs/winston/blob/master/UPGRADE-3.0.md`].join(`
4
+ `))},o.prototype.close=function(){this.transport.close&&this.transport.close(),this.transport.__winstonError&&(this.transport.removeListener(`error`,this.transport.__winstonError),this.transport.__winstonError=null)}})),mi=n(e(((exports,t)=>{t.exports=fi(),t.exports.LegacyTransportStream=pi()}))(),1);const hi=new Set([`apikey`,`auth`,`credential`,`key`,`password`,`secret`,`token`]);var gi=class extends mi.default{apiKey;extraAttributes;httpTimeout;ingestUrl;pendingRequests=new Set;constructor(e){super({}),this.apiKey=e.apiKey,this.ingestUrl=e.ingestUrl,this.httpTimeout=e.httpTimeout??5e3;let t=g()||`unknown`;this.extraAttributes={arch:m(),hostname:t,instance:`mcp-gateway-${t}`,os:ee(),source:`onyx-mcp-gateway`,version:q.appVersion,workload:`mcp-gateway`}}async flush(e=5e3){let t=Array.from(this.pendingRequests);t.length!==0&&await Promise.race([Promise.all(t),new Promise(t=>setTimeout(t,e))])}log(e,t){setImmediate(()=>this.emit(`logged`,e));let n=this.enrichEntry(e),r=this.sendEntry(n);this.pendingRequests.add(r),r.finally(()=>this.pendingRequests.delete(r)),t()}enrichEntry(e){let t={...this.extraAttributes,level:(e.level||`info`).toUpperCase(),message:e.message||``,timestamp:e.timestamp||new Date().toISOString()};for(let[n,r]of Object.entries(e)){if([`level`,`message`,`timestamp`].includes(n))continue;hi.has(n.toLowerCase())?t[n]=`[REDACTED]`:t[n]=vi(r)}return t}async sendEntry(e){let t=new AbortController,n=setTimeout(()=>t.abort(),this.httpTimeout);try{let n=_i(e);await(await fetch(this.ingestUrl,{body:n,headers:{apikey:this.apiKey,"Content-Type":`application/json`,"x-source-type":`endpoint-logs`},method:`POST`,signal:t.signal})).text()}catch{}finally{clearTimeout(n)}}};function _i(e){try{return JSON.stringify(e)}catch(t){let n={_serializationError:!0,level:`ERROR`,message:`[Log entry could not be serialized]`,originalError:t instanceof Error?t.message:String(t),timestamp:new Date().toISOString()};if(e&&typeof e==`object`)for(let t of[`level`,`message`,`timestamp`,`source`,`workload`]){let r=e[t];typeof r==`string`&&(n[t]=r)}return JSON.stringify(n)}}function vi(e,t=0,n=new WeakSet){if(t>10)return`[max depth exceeded]`;if(e==null)return e;let r=typeof e;if(r===`string`||r===`number`||r===`boolean`)return r===`number`&&(Number.isNaN(e)||!Number.isFinite(e))?String(e):e;if(r===`function`)return`[Function: ${e.name||`anonymous`}]`;if(r===`symbol`)return`[Symbol: ${e.description||``}]`;if(r===`bigint`)return String(e);if(r===`object`){if(n.has(e))return`[Circular]`;if(n.add(e),e instanceof Date)return e.toISOString();if(e instanceof Error)return{message:e.message,name:e.name,stack:e.stack};if(e instanceof RegExp)return e.toString();if(e instanceof Map){let r={};for(let[i,a]of e){let e=typeof i==`string`?i:String(i);r[e]=vi(a,t+1,n)}return r}if(e instanceof Set)return Array.from(e).map(e=>vi(e,t+1,n));if(Array.isArray(e))return e.map(e=>vi(e,t+1,n));if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer)return`[Binary Data]`;let r={},i;try{i=Object.keys(e)}catch{return`[Object with inaccessible keys]`}for(let a of i){if(hi.has(a.toLowerCase())){r[a]=`[REDACTED]`;continue}try{let i=e[a];r[a]=vi(i,t+1,n)}catch{r[a]=`[Unserializable]`}}return r}return`[Unknown Type]`}const yi=a(),bi=new i;function xi(e,t){return bi.run({traceId:e},t)}let Si=yi;function Ci(e){let t=e?.traceparent;if(t){let e=t.split(`-`);if(e.length>=2&&e[1])return e[1]}}function wi(){return bi.getStore()?.traceId??Si}function Ti(e){Si=e}const Ei=q.logDir,Di=q.debug?`debug`:`info`;let Oi=!1;try{s(Ei)||c(Ei,{recursive:!0}),Oi=!0;try{Hr(Ei)}catch{}}catch(e){let t=e instanceof Error?e.message:String(e),n=t.includes(`EACCES`)||t.includes(`permission denied`);console.error(`[mcp-gateway] WARNING: Failed to create log directory: ${Ei}`),console.error(`[mcp-gateway] Error: ${t}`),n&&(console.error(`[mcp-gateway] This appears to be a permission issue. Possible solutions:`),console.error(`[mcp-gateway] 1. Fix directory permissions: sudo chown -R $USER ~/.onyx`),console.error(`[mcp-gateway] 2. Use a different log directory: export MCP_GATEWAY_LOG_DIR=/tmp/mcp-gateway-logs`)),console.error(`[mcp-gateway] File logging will be disabled. The gateway will continue to function.`)}const ki=d.format.combine(d.format.timestamp(),d.format.errors({stack:!0}),d.format.json());let Ai=null;const ji=[];let Mi=null;Oi&&(Mi=new f({datePattern:`YYYY-MM-DD`,filename:l(Ei,`mcp-gateway-%DATE%.log`),format:ki,handleExceptions:!1,handleRejections:!1,level:Di,maxFiles:10,maxSize:`10m`}),ji.push(Mi));let Ni=null;const Pi=q.logIngest.enabled&&q.logIngest.url&&q.logIngest.apiKey;Pi&&(Ni=new gi({apiKey:q.logIngest.apiKey,httpTimeout:q.logIngest.timeoutMs,ingestUrl:q.logIngest.url}),ji.push(Ni));const Fi=d.format(e=>(e.traceId=wi(),e)),Ii=d.createLogger({defaultMeta:{service:`mcp-gateway`,version:q.appVersion},format:d.format.combine(Fi(),d.format.errors({stack:!0})),level:Di,transports:ji}),Li=e=>{let[t,...n]=e;if(typeof t!=`string`)return{message:String(t??``),meta:void 0,sessionData:Ai||void 0};if(n.length>0&&n[0]&&typeof n[0]==`object`&&`proxyType`in n[0]){let e=n[0],r=n[1];return{message:t,meta:r,sessionData:e}}let r=n[0];return{message:t,meta:r,sessionData:Ai||void 0}},Ri={debug:(...e)=>{let{message:t,meta:n,sessionData:r}=Li(e);Ii.debug(t,{sessionData:r,...n})},error:(...e)=>{let{message:t,meta:n,sessionData:r}=Li(e);Ii.error(t,{sessionData:r,...n})},getSessionData:()=>Ai,getTraceId:()=>wi(),info:(...e)=>{let{message:t,meta:n,sessionData:r}=Li(e);Ii.info(t,{sessionData:r,...n})},setSessionData:e=>{Ai=e,Ri.debug(`Session data set for logger`,e)},setTraceId:e=>{Ti(e),Ri.debug(`Trace ID updated for logger`,{traceId:e})},warn:(...e)=>{let{message:t,meta:n,sessionData:r}=Li(e);Ii.warn(t,{sessionData:r,...n})}};let zi=null;const Bi=e=>zi||(zi=(async()=>{let t=[];Ni&&t.push(Ni.flush(e)),Mi?t.push(new Promise(t=>{let n=!1,r=()=>{n||(n=!0,t())};setTimeout(()=>{Ii.once(`finish`,r),Ii.once(`error`,r),Ii.end()},50).unref(),e&&e>0&&setTimeout(r,e).unref()})):t.push(new Promise(e=>setImmediate(e))),await Promise.all(t)})(),zi);Ri.info(`MCP Gateway logger initialized`,{debug:q.debug,fileLoggingEnabled:Oi,ingestLoggingEnabled:Pi,logDir:Ei,logLevel:Di});var Vi=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function Hi(e){}function Ui(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=Hi,onError:n=Hi,onRetry:r=Hi,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=Wi(`${a}${t}`);for(let e of n)d(e);a=r,o=!1}function d(e){if(e===``){p();return}if(e.startsWith(`:`)){i&&i(e.slice(e.startsWith(`: `)?2:1));return}let t=e.indexOf(`:`);if(t!==-1){let n=e.slice(0,t),r=e[t+1]===` `?2:1,i=e.slice(t+r);f(n,i,e);return}f(e,``,e)}function f(e,t,i){switch(e){case`event`:l=t;break;case`data`:c=`${c}${t}
5
+ `;break;case`id`:s=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new Vi(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new Vi(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}));break}}function p(){c.length>0&&t({id:s,event:l||void 0,data:c.endsWith(`
6
+ `)?c.slice(0,-1):c}),s=void 0,c=``,l=``}function m(e={}){a&&e.consume&&d(a),o=!0,s=void 0,c=``,l=``,a=``}return{feed:u,reset:m}}function Wi(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e.indexOf(`\r`,r),a=e.indexOf(`
7
+ `,r),o=-1;if(i!==-1&&a!==-1?o=Math.min(i,a):i===-1?a!==-1&&(o=a):o=i===e.length-1?-1:i,o===-1){n=e.slice(r);break}else{let n=e.slice(r,o);t.push(n),r=o+1,e[r-1]===`\r`&&e[r]===`
8
+ `&&r++}}return[t,n]}var Gi=class extends Event{constructor(e,t){super(e),this.code=t?.code??void 0,this.message=t?.message??void 0}[Symbol.for(`nodejs.util.inspect.custom`)](e,t,n){return n(Ji(this),t)}[Symbol.for(`Deno.customInspect`)](e,t){return e(Ji(this),t)}};function Ki(e){let t=globalThis.DOMException;return typeof t==`function`?new t(e,`SyntaxError`):SyntaxError(e)}function qi(e){return e instanceof Error?`errors`in e&&Array.isArray(e.errors)?e.errors.map(qi).join(`, `):`cause`in e&&e.cause instanceof Error?`${e}: ${qi(e.cause)}`:e.message:`${e}`}function Ji(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var Yi=e=>{throw TypeError(e)},Xi=(e,t,n)=>t.has(e)||Yi(`Cannot `+n),J=(e,t,n)=>(Xi(e,t,`read from private field`),n?n.call(e):t.get(e)),Y=(e,t,n)=>t.has(e)?Yi(`Cannot add the same private member more than once`):t instanceof WeakSet?t.add(e):t.set(e,n),X=(e,t,n,r)=>(Xi(e,t,`write to private field`),t.set(e,n),n),Zi=(e,t,n)=>(Xi(e,t,`access private method`),n),Z,Qi,$i,ea,ta,na,ra,ia,aa,oa,sa,ca,la,ua,da,fa,pa,ma,ha,ga,_a,va,ya,ba=class extends EventTarget{constructor(e,t){super(),Y(this,ua),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Y(this,Z),Y(this,Qi),Y(this,$i),Y(this,ea),Y(this,ta),Y(this,na),Y(this,ra),Y(this,ia,null),Y(this,aa),Y(this,oa),Y(this,sa,null),Y(this,ca,null),Y(this,la,null),Y(this,fa,async e=>{var t;J(this,oa).reset();let{body:n,redirected:r,status:i,headers:a}=e;if(i===204){Zi(this,ua,_a).call(this,`Server sent HTTP 204, not reconnecting`,204),this.close();return}if(r?X(this,$i,new URL(e.url)):X(this,$i,void 0),i!==200){Zi(this,ua,_a).call(this,`Non-200 status code (${i})`,i);return}if(!(a.get(`content-type`)||``).startsWith(`text/event-stream`)){Zi(this,ua,_a).call(this,`Invalid content type, expected "text/event-stream"`,i);return}if(J(this,Z)===this.CLOSED)return;X(this,Z,this.OPEN);let o=new Event(`open`);if((t=J(this,la))==null||t.call(this,o),this.dispatchEvent(o),typeof n!=`object`||!n||!(`getReader`in n)){Zi(this,ua,_a).call(this,`Invalid response body, expected a web ReadableStream`,i),this.close();return}let s=new TextDecoder,c=n.getReader(),l=!0;do{let{done:e,value:t}=await c.read();t&&J(this,oa).feed(s.decode(t,{stream:!e})),e&&(l=!1,J(this,oa).reset(),Zi(this,ua,va).call(this))}while(l)}),Y(this,pa,e=>{X(this,aa,void 0),!(e.name===`AbortError`||e.type===`aborted`)&&Zi(this,ua,va).call(this,qi(e))}),Y(this,ha,e=>{typeof e.id==`string`&&X(this,ia,e.id);let t=new MessageEvent(e.event||`message`,{data:e.data,origin:J(this,$i)?J(this,$i).origin:J(this,Qi).origin,lastEventId:e.id||``});J(this,ca)&&(!e.event||e.event===`message`)&&J(this,ca).call(this,t),this.dispatchEvent(t)}),Y(this,ga,e=>{X(this,na,e)}),Y(this,ya,()=>{X(this,ra,void 0),J(this,Z)===this.CONNECTING&&Zi(this,ua,da).call(this)});try{if(e instanceof URL)X(this,Qi,e);else if(typeof e==`string`)X(this,Qi,new URL(e,xa()));else throw Error(`Invalid URL`)}catch{throw Ki(`An invalid or illegal string was specified`)}X(this,oa,Ui({onEvent:J(this,ha),onRetry:J(this,ga)})),X(this,Z,this.CONNECTING),X(this,na,3e3),X(this,ta,t?.fetch??globalThis.fetch),X(this,ea,t?.withCredentials??!1),Zi(this,ua,da).call(this)}get readyState(){return J(this,Z)}get url(){return J(this,Qi).href}get withCredentials(){return J(this,ea)}get onerror(){return J(this,sa)}set onerror(e){X(this,sa,e)}get onmessage(){return J(this,ca)}set onmessage(e){X(this,ca,e)}get onopen(){return J(this,la)}set onopen(e){X(this,la,e)}addEventListener(e,t,n){let r=t;super.addEventListener(e,r,n)}removeEventListener(e,t,n){let r=t;super.removeEventListener(e,r,n)}close(){J(this,ra)&&clearTimeout(J(this,ra)),J(this,Z)!==this.CLOSED&&(J(this,aa)&&J(this,aa).abort(),X(this,Z,this.CLOSED),X(this,aa,void 0))}};Z=new WeakMap,Qi=new WeakMap,$i=new WeakMap,ea=new WeakMap,ta=new WeakMap,na=new WeakMap,ra=new WeakMap,ia=new WeakMap,aa=new WeakMap,oa=new WeakMap,sa=new WeakMap,ca=new WeakMap,la=new WeakMap,ua=new WeakSet,da=function(){X(this,Z,this.CONNECTING),X(this,aa,new AbortController),J(this,ta)(J(this,Qi),Zi(this,ua,ma).call(this)).then(J(this,fa)).catch(J(this,pa))},fa=new WeakMap,pa=new WeakMap,ma=function(){let e={mode:`cors`,redirect:`follow`,headers:{Accept:`text/event-stream`,...J(this,ia)?{"Last-Event-ID":J(this,ia)}:void 0},cache:`no-store`,signal:J(this,aa)?.signal};return`window`in globalThis&&(e.credentials=this.withCredentials?`include`:`same-origin`),e},ha=new WeakMap,ga=new WeakMap,_a=function(e,t){var n;J(this,Z)!==this.CLOSED&&X(this,Z,this.CLOSED);let r=new Gi(`error`,{code:t,message:e});(n=J(this,sa))==null||n.call(this,r),this.dispatchEvent(r)},va=function(e,t){var n;if(J(this,Z)===this.CLOSED)return;X(this,Z,this.CONNECTING);let r=new Gi(`error`,{code:t,message:e});(n=J(this,sa))==null||n.call(this,r),this.dispatchEvent(r),X(this,ra,setTimeout(J(this,ya),J(this,na)))},ya=new WeakMap,ba.CONNECTING=0,ba.OPEN=1,ba.CLOSED=2;function xa(){let e=`document`in globalThis?globalThis.document:void 0;return e&&typeof e==`object`&&`baseURI`in e&&typeof e.baseURI==`string`?e.baseURI:void 0}let Sa;Sa=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function Ca(e){return(await Sa).getRandomValues(new Uint8Array(e))}async function wa(e){let t=``,n=await Ca(e);for(let r=0;r<e;r++){let e=n[r]%66;t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e]}return t}async function Ta(e){return await wa(e)}async function Ea(e){let t=await(await Sa).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function Da(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await Ta(e),n=await Ea(t);return{code_verifier:t,code_challenge:n}}const Q=F().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:b.custom,message:`URL must be parseable`,fatal:!0}),wt}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),Oa=z({resource:F().url(),authorization_servers:R(Q).optional(),jwks_uri:F().url().optional(),scopes_supported:R(F()).optional(),bearer_methods_supported:R(F()).optional(),resource_signing_alg_values_supported:R(F()).optional(),resource_name:F().optional(),resource_documentation:F().optional(),resource_policy_uri:F().url().optional(),resource_tos_uri:F().url().optional(),tls_client_certificate_bound_access_tokens:L().optional(),authorization_details_types_supported:R(F()).optional(),dpop_signing_alg_values_supported:R(F()).optional(),dpop_bound_access_tokens_required:L().optional()}).passthrough(),ka=z({issuer:F(),authorization_endpoint:Q,token_endpoint:Q,registration_endpoint:Q.optional(),scopes_supported:R(F()).optional(),response_types_supported:R(F()),response_modes_supported:R(F()).optional(),grant_types_supported:R(F()).optional(),token_endpoint_auth_methods_supported:R(F()).optional(),token_endpoint_auth_signing_alg_values_supported:R(F()).optional(),service_documentation:Q.optional(),revocation_endpoint:Q.optional(),revocation_endpoint_auth_methods_supported:R(F()).optional(),revocation_endpoint_auth_signing_alg_values_supported:R(F()).optional(),introspection_endpoint:F().optional(),introspection_endpoint_auth_methods_supported:R(F()).optional(),introspection_endpoint_auth_signing_alg_values_supported:R(F()).optional(),code_challenge_methods_supported:R(F()).optional()}).passthrough(),Aa=z({issuer:F(),authorization_endpoint:Q,token_endpoint:Q,userinfo_endpoint:Q.optional(),jwks_uri:Q,registration_endpoint:Q.optional(),scopes_supported:R(F()).optional(),response_types_supported:R(F()),response_modes_supported:R(F()).optional(),grant_types_supported:R(F()).optional(),acr_values_supported:R(F()).optional(),subject_types_supported:R(F()),id_token_signing_alg_values_supported:R(F()),id_token_encryption_alg_values_supported:R(F()).optional(),id_token_encryption_enc_values_supported:R(F()).optional(),userinfo_signing_alg_values_supported:R(F()).optional(),userinfo_encryption_alg_values_supported:R(F()).optional(),userinfo_encryption_enc_values_supported:R(F()).optional(),request_object_signing_alg_values_supported:R(F()).optional(),request_object_encryption_alg_values_supported:R(F()).optional(),request_object_encryption_enc_values_supported:R(F()).optional(),token_endpoint_auth_methods_supported:R(F()).optional(),token_endpoint_auth_signing_alg_values_supported:R(F()).optional(),display_values_supported:R(F()).optional(),claim_types_supported:R(F()).optional(),claims_supported:R(F()).optional(),service_documentation:F().optional(),claims_locales_supported:R(F()).optional(),ui_locales_supported:R(F()).optional(),claims_parameter_supported:L().optional(),request_parameter_supported:L().optional(),request_uri_parameter_supported:L().optional(),require_request_uri_registration:L().optional(),op_policy_uri:Q.optional(),op_tos_uri:Q.optional()}).passthrough().merge(ka.pick({code_challenge_methods_supported:!0})),ja=z({access_token:F(),id_token:F().optional(),token_type:F(),expires_in:I().optional(),scope:F().optional(),refresh_token:F().optional()}).strip(),Ma=z({error:F(),error_description:F().optional(),error_uri:F().optional()}),Na=z({redirect_uris:R(Q),token_endpoint_auth_method:F().optional(),grant_types:R(F()).optional(),response_types:R(F()).optional(),client_name:F().optional(),client_uri:Q.optional(),logo_uri:Q.optional(),scope:F().optional(),contacts:R(F()).optional(),tos_uri:Q.optional(),policy_uri:F().optional(),jwks_uri:Q.optional(),jwks:yt().optional(),software_id:F().optional(),software_version:F().optional(),software_statement:F().optional()}).strip(),Pa=z({client_id:F(),client_secret:F().optional(),client_id_issued_at:I().optional(),client_secret_expires_at:I().optional()}).strip(),Fa=Na.merge(Pa);z({error:F(),error_description:F().optional()}).strip(),z({token:F(),token_type_hint:F().optional()}).strip();function Ia(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function La({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var $=class extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},Ra=class extends ${};Ra.errorCode=`invalid_request`;var za=class extends ${};za.errorCode=`invalid_client`;var Ba=class extends ${};Ba.errorCode=`invalid_grant`;var Va=class extends ${};Va.errorCode=`unauthorized_client`;var Ha=class extends ${};Ha.errorCode=`unsupported_grant_type`;var Ua=class extends ${};Ua.errorCode=`invalid_scope`;var Wa=class extends ${};Wa.errorCode=`access_denied`;var Ga=class extends ${};Ga.errorCode=`server_error`;var Ka=class extends ${};Ka.errorCode=`temporarily_unavailable`;var qa=class extends ${};qa.errorCode=`unsupported_response_type`;var Ja=class extends ${};Ja.errorCode=`unsupported_token_type`;var Ya=class extends ${};Ya.errorCode=`invalid_token`;var Xa=class extends ${};Xa.errorCode=`method_not_allowed`;var Za=class extends ${};Za.errorCode=`too_many_requests`;var Qa=class extends ${};Qa.errorCode=`invalid_client_metadata`;var $a=class extends ${};$a.errorCode=`insufficient_scope`;const eo={[Ra.errorCode]:Ra,[za.errorCode]:za,[Ba.errorCode]:Ba,[Va.errorCode]:Va,[Ha.errorCode]:Ha,[Ua.errorCode]:Ua,[Wa.errorCode]:Wa,[Ga.errorCode]:Ga,[Ka.errorCode]:Ka,[qa.errorCode]:qa,[Ja.errorCode]:Ja,[Ya.errorCode]:Ya,[Xa.errorCode]:Xa,[Za.errorCode]:Za,[Qa.errorCode]:Qa,[$a.errorCode]:$a};var to=class extends Error{constructor(e){super(e??`Unauthorized`)}};function no(e,t){let n=e.client_secret!==void 0;return t.length===0?n?`client_secret_post`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function ro(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:io(i,a,n);return;case`client_secret_post`:ao(i,a,r);return;case`none`:oo(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function io(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function ao(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function oo(e,t){t.set(`client_id`,e)}async function so(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=Ma.parse(JSON.parse(n));return new(eo[e]||Ga)(t||``,r)}catch(e){let r=`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`;return new Ga(r)}}async function co(e,t){try{return await lo(e,t)}catch(n){if(n instanceof za||n instanceof Va)return await e.invalidateCredentials?.call(e,`all`),await lo(e,t);if(n instanceof Ba)return await e.invalidateCredentials?.call(e,`tokens`),await lo(e,t);throw n}}async function lo(e,{serverUrl:t,authorizationCode:n,scope:r,resourceMetadataUrl:i,fetchFn:a}){let o,s;try{o=await po(t,{resourceMetadataUrl:i},a),o.authorization_servers&&o.authorization_servers.length>0&&(s=o.authorization_servers[0])}catch{}s||=t;let c=await uo(t,e,o),l=await bo(s,{fetchFn:a}),u=await Promise.resolve(e.clientInformation());if(!u){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);let t=await wo(s,{metadata:l,clientMetadata:e.clientMetadata,fetchFn:a});await e.saveClientInformation(t),u=t}if(n!==void 0){let t=await e.codeVerifier(),r=await So(s,{metadata:l,clientInformation:u,authorizationCode:n,codeVerifier:t,redirectUri:e.redirectUrl,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(r),`AUTHORIZED`}let d=await e.tokens();if(d?.refresh_token)try{let t=await Co(s,{metadata:l,clientInformation:u,refreshToken:d.refresh_token,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(t),`AUTHORIZED`}catch(e){if(!(!(e instanceof $)||e instanceof Ga))throw e}let f=e.state?await e.state():void 0,{authorizationUrl:p,codeVerifier:m}=await xo(s,{metadata:l,clientInformation:u,state:f,redirectUrl:e.redirectUrl,scope:r||e.clientMetadata.scope,resource:c});return await e.saveCodeVerifier(m),await e.redirectToAuthorization(p),`REDIRECT`}async function uo(e,t,n){let r=Ia(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!La({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}function fo(e){let t=e.headers.get(`WWW-Authenticate`);if(!t)return;let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return;let i=/resource_metadata="([^"]*)"/.exec(t);if(i)try{return new URL(i[1])}catch{return}}async function po(e,t,n=fetch){let r=await vo(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return Oa.parse(await r.json())}async function mo(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?mo(e,void 0,n):void 0;throw r}}function ho(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function go(e,t,n=fetch){return await mo(e,{"MCP-Protocol-Version":t},n)}function _o(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function vo(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??Tt,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=ho(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await go(o,a,n);if(!r?.metadataUrl&&_o(s,i.pathname)){let e=new URL(`/.well-known/${t}`,i);s=await go(e,a,n)}return s}function yo(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:`oidc`}),r.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function bo(e,{fetchFn:t=fetch,protocolVersion:n=Tt}={}){let r={"MCP-Protocol-Version":n},i=yo(e);for(let{url:e,type:n}of i){let i=await mo(e,r,t);if(!i)continue;if(!i.ok){if(i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}if(n===`oauth`)return ka.parse(await i.json());{let t=Aa.parse(await i.json());if(!t.code_challenge_methods_supported?.includes(`S256`))throw Error(`Incompatible OIDC provider at ${e}: does not support S256 code challenge method required by MCP specification`);return t}}}async function xo(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s=`code`,c=`S256`,l;if(t){if(l=new URL(t.authorization_endpoint),!t.response_types_supported.includes(s))throw Error(`Incompatible auth server: does not support response type ${s}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(c))throw Error(`Incompatible auth server: does not support code challenge method ${c}`)}else l=new URL(`/authorize`,e);let u=await Da(),d=u.code_verifier,f=u.code_challenge;return l.searchParams.set(`response_type`,s),l.searchParams.set(`client_id`,n.client_id),l.searchParams.set(`code_challenge`,f),l.searchParams.set(`code_challenge_method`,c),l.searchParams.set(`redirect_uri`,String(r)),a&&l.searchParams.set(`state`,a),i&&l.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&l.searchParams.append(`prompt`,`consent`),o&&l.searchParams.set(`resource`,o.href),{authorizationUrl:l,codeVerifier:d}}async function So(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:a,resource:o,addClientAuthentication:s,fetchFn:c}){let l=`authorization_code`,u=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(l))throw Error(`Incompatible auth server: does not support grant type ${l}`);let d=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),f=new URLSearchParams({grant_type:l,code:r,code_verifier:i,redirect_uri:String(a)});if(s)s(d,f,e,t);else{let e=t?.token_endpoint_auth_methods_supported??[],r=no(n,e);ro(r,n,d,f)}o&&f.set(`resource`,o.href);let p=await(c??fetch)(u,{method:`POST`,headers:d,body:f});if(!p.ok)throw await so(p);return ja.parse(await p.json())}async function Co(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){let s=`refresh_token`,c;if(t){if(c=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(s))throw Error(`Incompatible auth server: does not support grant type ${s}`)}else c=new URL(`/token`,e);let l=new Headers({"Content-Type":`application/x-www-form-urlencoded`}),u=new URLSearchParams({grant_type:s,refresh_token:r});if(a)a(l,u,e,t);else{let e=t?.token_endpoint_auth_methods_supported??[],r=no(n,e);ro(r,n,l,u)}i&&u.set(`resource`,i.href);let d=await(o??fetch)(c,{method:`POST`,headers:l,body:u});if(!d.ok)throw await so(d);return ja.parse({refresh_token:r,...await d.json()})}async function wo(e,{metadata:t,clientMetadata:n,fetchFn:r}){let i;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);i=new URL(t.registration_endpoint)}else i=new URL(`/register`,e);let a=await(r??fetch)(i,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});if(!a.ok)throw await so(a);return Fa.parse(await a.json())}var To=class extends Error{constructor(e,t,n){super(`SSE error: ${t}`),this.code=e,this.event=n}},Eo=class{constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._eventSourceInit=t?.eventSourceInit,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch}async _authThenStart(){var e;if(!this._authProvider)throw new to(`No auth provider`);let t;try{t=await co(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(t){throw(e=this.onerror)==null||e.call(this,t),t}if(t!==`AUTHORIZED`)throw new to;return await this._startOrAuth()}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}return this._protocolVersion&&(e[`mcp-protocol-version`]=this._protocolVersion),new Headers({...e,...this._requestInit?.headers})}_startOrAuth(){let e=(this===null||this===void 0?void 0:this._eventSourceInit)?.fetch??this._fetch??fetch;return new Promise((t,n)=>{this._eventSource=new ba(this._url.href,{...this._eventSourceInit,fetch:async(t,n)=>{let r=await this._commonHeaders();r.set(`Accept`,`text/event-stream`);let i=await e(t,{...n,headers:r});return i.status===401&&i.headers.has(`www-authenticate`)&&(this._resourceMetadataUrl=fo(i)),i}}),this._abortController=new AbortController,this._eventSource.onerror=e=>{var r;if(e.code===401&&this._authProvider){this._authThenStart().then(t,n);return}let i=new To(e.code,e.message,e);n(i),(r=this.onerror)==null||r.call(this,i)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener(`endpoint`,e=>{var r;let i=e;try{if(this._endpoint=new URL(i.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(e){n(e),(r=this.onerror)==null||r.call(this,e),this.close();return}t()}),this._eventSource.onmessage=e=>{var t,n;let r=e,i;try{i=Ut.parse(JSON.parse(r.data))}catch(e){(t=this.onerror)==null||t.call(this,e);return}(n=this.onmessage)==null||n.call(this,i)}})}async start(){if(this._eventSource)throw Error(`SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.`);return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new to(`No auth provider`);if(await co(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!==`AUTHORIZED`)throw new to(`Failed to authorize`)}async close(){var e,t,n;(e=this._abortController)==null||e.abort(),(t=this._eventSource)==null||t.close(),(n=this.onclose)==null||n.call(this)}async send(e){var t;if(!this._endpoint)throw Error(`Not connected`);try{let t=await this._commonHeaders();t.set(`content-type`,`application/json`);let n={...this._requestInit,method:`POST`,headers:t,body:JSON.stringify(e),signal:this._abortController?.signal},r=await(this._fetch??fetch)(this._endpoint,n);if(!r.ok){if(r.status===401&&this._authProvider){if(this._resourceMetadataUrl=fo(r),await co(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!==`AUTHORIZED`)throw new to;return this.send(e)}let t=await r.text().catch(()=>null);throw Error(`Error POSTing to endpoint (HTTP ${r.status}): ${t}`)}}catch(e){throw(t=this.onerror)==null||t.call(this,e),e}}setProtocolVersion(e){this._protocolVersion=e}},Do=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=Ui({onEvent:e=>{i.enqueue(e)},onError(t){e===`terminate`?i.error(t):typeof e==`function`&&e(t)},onRetry:t,onComment:n})},transform(e){r.feed(e)}})}};const Oo={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};var ko=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},Ao=class{constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??Oo}async _authThenStart(){var e;if(!this._authProvider)throw new to(`No auth provider`);let t;try{t=await co(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(t){throw(e=this.onerror)==null||e.call(this,t),t}if(t!==`AUTHORIZED`)throw new to;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._sessionId&&(e[`mcp-session-id`]=this._sessionId),this._protocolVersion&&(e[`mcp-protocol-version`]=this._protocolVersion);let t=this._normalizeHeaders(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){var t;let{resumptionToken:n}=e;try{let t=await this._commonHeaders();t.set(`Accept`,`text/event-stream`),n&&t.set(`last-event-id`,n);let r=await(this._fetch??fetch)(this._url,{method:`GET`,headers:t,signal:this._abortController?.signal});if(!r.ok){if(r.status===401&&this._authProvider)return await this._authThenStart();if(r.status===405)return;throw new ko(r.status,`Failed to open SSE stream: ${r.statusText}`)}this._handleSseStream(r.body,e,!0)}catch(e){throw(t=this.onerror)==null||t.call(this,e),e}}_getNextReconnectionDelay(e){let t=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*n**+e,r)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,t=0){var n;let r=this._reconnectionOptions.maxRetries;if(r>0&&t>=r){(n=this.onerror)==null||n.call(this,Error(`Maximum reconnection attempts (${r}) exceeded.`));return}let i=this._getNextReconnectionDelay(t);setTimeout(()=>{this._startOrAuthSse(e).catch(n=>{var r;(r=this.onerror)==null||r.call(this,Error(`Failed to reconnect SSE stream: ${n instanceof Error?n.message:String(n)}`)),this._scheduleReconnection(e,t+1)})},i)}_handleSseStream(e,t,n){if(!e)return;let{onresumptiontoken:r,replayMessageId:i}=t,a;(async()=>{var t,o,s,c;try{let n=e.pipeThrough(new TextDecoderStream).pipeThrough(new Do).getReader();for(;;){let{value:e,done:s}=await n.read();if(s)break;if(e.id&&(a=e.id,r?.(e.id)),!e.event||e.event===`message`)try{let n=Ut.parse(JSON.parse(e.data));i!==void 0&&zt(n)&&(n.id=i),(t=this.onmessage)==null||t.call(this,n)}catch(e){(o=this.onerror)==null||o.call(this,e)}}}catch(e){if((s=this.onerror)==null||s.call(this,Error(`SSE stream disconnected: ${e}`)),n&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){(c=this.onerror)==null||c.call(this,Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw Error(`StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.`);this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new to(`No auth provider`);if(await co(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!==`AUTHORIZED`)throw new to(`Failed to authorize`)}async close(){var e,t;(e=this._abortController)==null||e.abort(),(t=this.onclose)==null||t.call(this)}async send(e,t){var n,r;try{let{resumptionToken:r,onresumptiontoken:i}=t||{};if(r){this._startOrAuthSse({resumptionToken:r,replayMessageId:Ft(e)?e.id:void 0}).catch(e=>this.onerror?.call(this,e));return}let a=await this._commonHeaders();a.set(`content-type`,`application/json`),a.set(`accept`,`application/json, text/event-stream`);let o={...this._requestInit,method:`POST`,headers:a,body:JSON.stringify(e),signal:this._abortController?.signal},s=await(this._fetch??fetch)(this._url,o),c=s.headers.get(`mcp-session-id`);if(c&&(this._sessionId=c),!s.ok){if(s.status===401&&this._authProvider){if(this._resourceMetadataUrl=fo(s),await co(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!==`AUTHORIZED`)throw new to;return this.send(e)}let t=await s.text().catch(()=>null);throw Error(`Error POSTing to endpoint (HTTP ${s.status}): ${t}`)}if(s.status===202){tn(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.call(this,e));return}let l=(Array.isArray(e)?e:[e]).filter(e=>`method`in e&&`id`in e&&e.id!==void 0).length>0,u=s.headers.get(`content-type`);if(l)if(u?.includes(`text/event-stream`))this._handleSseStream(s.body,{onresumptiontoken:i},!1);else if(u?.includes(`application/json`)){let e=await s.json(),t=Array.isArray(e)?e.map(e=>Ut.parse(e)):[Ut.parse(e)];for(let e of t)(n=this.onmessage)==null||n.call(this,e)}else throw new ko(-1,`Unexpected content type: ${u}`)}catch(e){throw(r=this.onerror)==null||r.call(this,e),e}}get sessionId(){return this._sessionId}async terminateSession(){var e;if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:`DELETE`,headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,t);if(!n.ok&&n.status!==405)throw new ko(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(t){throw(e=this.onerror)==null||e.call(this,t),t}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}};export{Un as CallToolRequestSchema,Hn as CallToolResultSchema,Gt as CancelledNotificationSchema,cr as CompleteRequestSchema,lr as CompleteResultSchema,Qn as CreateMessageResultSchema,Et as DEFAULT_NEGOTIATED_PROTOCOL_VERSION,ar as ElicitResultSchema,Wt as EmptyResultSchema,Bt as ErrorCode,On as GetPromptRequestSchema,In as GetPromptResultSchema,Xt as InitializeRequestSchema,$t as InitializeResultSchema,en as InitializedNotificationSchema,Ut as JSONRPCMessageSchema,Tt as LATEST_PROTOCOL_VERSION,En as ListPromptsRequestSchema,Dn as ListPromptsResultSchema,gn as ListResourceTemplatesRequestSchema,_n as ListResourceTemplatesResultSchema,mn as ListResourcesRequestSchema,hn as ListResourcesResultSchema,fr as ListRootsResultSchema,Bn as ListToolsRequestSchema,Vn as ListToolsResultSchema,Gn as LoggingLevelSchema,qn as LoggingMessageNotificationSchema,mr as McpError,nn as PingRequestSchema,an as ProgressNotificationSchema,vn as ReadResourceRequestSchema,yn as ReadResourceResultSchema,Cn as ResourceUpdatedNotificationSchema,xr as SESSION_ID,Eo as SSEClientTransport,Dt as SUPPORTED_PROTOCOL_VERSIONS,Kn as SetLevelRequestSchema,Ao as StreamableHTTPClientTransport,xn as SubscribeRequestSchema,to as UnauthorizedError,Sn as UnsubscribeRequestSchema,Vr as chownToRealUser,q as config,Ui as createParser,bo as discoverAuthorizationServerMetadata,po as discoverOAuthProtectedResourceMetadata,So as exchangeAuthorization,Ci as extractTraceIdFromHeaders,Bi as flushLogs,yi as gatewayCorrelationId,Zt as isInitializeRequest,Ht as isJSONRPCError,Lt as isJSONRPCNotification,Ft as isJSONRPCRequest,zt as isJSONRPCResponse,Ri as logger,Co as refreshAuthorization,wo as registerClient,Zr as require_inherits,xi as runWithTraceContextAsync,xo as startAuthorization};
9
+ //# sourceMappingURL=streamableHttp-DM0LA7pR.js.map