mcp-proxy
Version:
A TypeScript SSE proxy for MCP servers that use stdio transport.
1 lines • 1.53 MB
Source Map (JSON)
{"version":3,"file":"stdio-DBuYn6eo.mjs","names":["config: AuthConfig","headers: Record<string, string>","params: string[]","error","def","_","_","object","key","str","isPlainObject","def","i","config","initializer","def","util.jsonStringifyReplacer","issue","error","i","core.$ZodAsyncError","util.finalizeIssue","core.config","parse","errors.$ZodRealError","parseAsync","errors.$ZodError","safeParse","safeParseAsync","duration","version","_emoji","date","time","datetime","string","regex","number","boolean","_null","def","inst","util.floatSafeRemainder","util.NUMBER_FORMAT_RANGES","regexes.integer","util.nullish","util.getLengthableOrigin","regexes.lowercase","regexes.uppercase","util.escapeRegex","line","def","util.aborted","checks","_","core.$ZodAsyncError","result","safeParse","safeParseAsync","regexes.string","regexes.guid","regexes.uuid","regexes.email","url","regexes.emoji","regexes.nanoid","regexes.cuid","regexes.cuid2","regexes.ulid","regexes.xid","regexes.ksuid","regexes.datetime","regexes.date","regexes.time","regexes.duration","regexes.ipv4","inst","regexes.ipv6","regexes.cidrv4","regexes.cidrv6","regexes.base64","base64","regexes.base64url","regexes.e164","regexes.number","regexes.boolean","regexes.null","util.prefixIssues","i","key","util.cached","util.optionalKeys","util.esc","isObject","util.isObject","allowsEval","util.allowsEval","r","util.finalizeIssue","core.config","util.cleanRegex","results","map","left","right","util.isPlainObject","util.getEnumValues","util.escapeRegex","util.issue","util.normalizeParams","_null","checks.$ZodCheckLessThan","checks.$ZodCheckGreaterThan","checks.$ZodCheckMultipleOf","checks.$ZodCheckMaxLength","checks.$ZodCheckMinLength","checks.$ZodCheckLengthEquals","checks.$ZodCheckRegex","checks.$ZodCheckLowerCase","checks.$ZodCheckUpperCase","checks.$ZodCheckIncludes","checks.$ZodCheckStartsWith","checks.$ZodCheckEndsWith","checks.$ZodCheckOverwrite","def","core._isoDateTime","date","core._isoDate","core._isoTime","core._isoDuration","core.formatError","core.flattenError","issue","issues","core.$constructor","parse","safeParse","def","core.clone","parse.parse","parse.safeParse","parse.parseAsync","parse.safeParseAsync","check","checks.overwrite","checks.regex","checks.includes","checks.startsWith","checks.endsWith","checks.minLength","checks.maxLength","checks.length","checks.lowercase","checks.uppercase","checks.trim","checks.normalize","checks.toLowerCase","checks.toUpperCase","core._email","core._url","core._jwt","core._emoji","core._guid","core._uuid","core._uuidv4","core._uuidv6","core._uuidv7","core._nanoid","core._cuid","core._cuid2","core._ulid","core._base64","core._base64url","core._xid","core._ksuid","core._ipv4","core._ipv6","core._cidrv4","core._cidrv6","core._e164","iso.datetime","iso.date","iso.time","iso.duration","core._string","checks.gt","checks.gte","checks.lt","checks.lte","checks.multipleOf","core._number","core._int","core._boolean","core._null","core._any","core._unknown","core._never","core._array","util.extend","util.merge","util.pick","util.omit","util.partial","util.required","util.normalizeParams","issue","util.issue","output","core.$ZodCheck","core._custom","core._refine","z.custom","z.union","z.string","z.number","z.looseObject","z.null","z.object","z\n .object","z.optional","z\n .looseObject","z\n .object","z.literal","z.unknown","z.array","z.intersection","z.boolean","z.record","z.preprocess","z\n .object","z.enum","z.iso.datetime","z.discriminatedUnion","bytes","format","parse","str","i","str","i","deprecate","key","line","error","map","codes","status","inherits","toIdentifier","str","createError","status","i","key","Buffer","str","mergeModules","key","module","Buffer","iconv","str","i","Buffer","iconv","str","i","detectEncoding","Buffer","str","i","iconv","Buffer","iconv","str","i","Buffer","i","iconv","str","Buffer","i","iconv","bytes","str","mergeModules","module","Buffer","streamModule","Buffer","iconv","str","key","getDecoder","streamModule","unpipe","i","getRawBody","buffer","i","parse","string","key","MAXIMUM_MESSAGE_SIZE","URL","error","error","_a","_","streamId","bodyParts: Buffer[]","body: string","error","params: string[]","fixedHeaders: http.OutgoingHttpHeaders","key","defaultCorsOptions: CorsOptions","finalCorsOptions: CorsOptions","body: unknown","transport: StreamableHTTPServerTransport","server: T","activeTransport:\n | {\n server: T;\n transport: StreamableHTTPServerTransport;\n }\n | undefined","activeTransport: SSEServerTransport | undefined","activeSSETransports: Record<string, SSEServerTransport>","activeStreamTransports: Record<\n string,\n {\n server: T;\n transport: StreamableHTTPServerTransport;\n }\n >","z4mini.safeParse","def","status","error","_a","_b","task","resolve","jsonrpcNotification","status","key","names","i","key","code_1","def","code_1","names","error","i","key","codegen_1","code_1","key","str","mergeValues","codegen_1","codegen_1","util_1","names_1","error","i","errors_1","codegen_1","names_1","rules_1","applicability_1","errors_1","codegen_1","util_1","codegen_1","util_1","key","i","codegen_1","util_1","names_1","util_2","i","codegen_1","names_1","code_1","errors_1","def","_a","codegen_1","util_1","equal","i","key","traverse","key","i","str","util_1","equal","key","normalize","dataType_1","codegen_1","names_1","resolve_1","util_1","key","ValidationError","def","resolve_1","codegen_1","validation_error_1","names_1","resolve_1","util_1","validate_1","resolve","isUUID","isIPv4","i","nonSimpleDomain","buffer","normalizeIPv6","ipv6","str","removeDotSegments","normalizeComponentEncoding","esc","recomposeAuthority","getSchemeHandler","http","SCHEMES","uri","relative","equal","uri","validate_1","codegen_1","validation_error_1","ref_error_1","compile_1","dataType_1","util_1","str","optimize","Ajv","key","def","i","format","regex","log","def","ref_error_1","code_1","codegen_1","names_1","compile_1","util_1","def","codegen_1","ops","KWDs","def","codegen_1","def","str","codegen_1","util_1","def","code_1","codegen_1","def","codegen_1","def","code_1","codegen_1","util_1","def","codegen_1","def","codegen_1","util_1","equal_1","def","i","codegen_1","util_1","equal_1","def","codegen_1","util_1","def","i","codegen_1","util_1","def","i","codegen_1","util_1","code_1","def","i","items_1","def","codegen_1","util_1","code_1","additionalItems_1","def","codegen_1","util_1","def","i","codegen_1","util_1","code_1","def","key","codegen_1","util_1","def","key","code_1","codegen_1","util_1","def","key","validate_1","code_1","util_1","additionalProperties_1","def","codegen_1","util_1","def","key","util_1","def","def","codegen_1","util_1","def","i","util_1","def","i","codegen_1","util_1","def","util_1","def","codegen_1","def","format","fmtDef","core_1","codegen_1","ref_error_1","i","required","Ajv","codegen_1","str","time","codegen_1","format","fmtDef","Ajv","error","key","_a","_b","_c","error","_a","error","line"],"sources":["../src/authentication.ts","../src/InMemoryEventStore.ts","../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/core.js","../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/util.js","../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/errors.js","../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/parse.js","../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/regexes.js","../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/checks.js","../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/doc.js","../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/versions.js","../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/schemas.js","../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/registries.js","../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/api.js","../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/iso.js","../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/errors.js","../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/parse.js","../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/schemas.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.24.3_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js","../src/proxyServer.ts","../node_modules/.pnpm/bytes@3.1.2/node_modules/bytes/index.js","../node_modules/.pnpm/depd@2.0.0/node_modules/depd/index.js","../node_modules/.pnpm/setprototypeof@1.2.0/node_modules/setprototypeof/index.js","../node_modules/.pnpm/statuses@2.0.1/node_modules/statuses/codes.json","../node_modules/.pnpm/statuses@2.0.1/node_modules/statuses/index.js","../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits_browser.js","../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits.js","../node_modules/.pnpm/toidentifier@1.0.1/node_modules/toidentifier/index.js","../node_modules/.pnpm/http-errors@2.0.0/node_modules/http-errors/index.js","../node_modules/.pnpm/safer-buffer@2.1.2/node_modules/safer-buffer/safer.js","../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/lib/bom-handling.js","../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/lib/helpers/merge-exports.js","../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/encodings/internal.js","../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/encodings/utf32.js","../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/encodings/utf16.js","../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/encodings/utf7.js","../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/encodings/sbcs-codec.js","../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/encodings/sbcs-data.js","../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/encodings/sbcs-data-generated.js","../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/encodings/dbcs-codec.js","../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/encodings/tables/shiftjis.json","../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/encodings/tables/eucjp.json","../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/encodings/tables/cp936.json","../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/encodings/tables/gbk-added.json","../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json","../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/encodings/tables/cp949.json","../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/encodings/tables/cp950.json","../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/encodings/tables/big5-added.json","../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/encodings/dbcs-data.js","../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/encodings/index.js","../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/lib/streams.js","../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/lib/index.js","../node_modules/.pnpm/unpipe@1.0.0/node_modules/unpipe/index.js","../node_modules/.pnpm/raw-body@3.0.1/node_modules/raw-body/index.js","../node_modules/.pnpm/content-type@1.0.5/node_modules/content-type/index.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.24.3_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/sse.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.24.3_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/streamableHttp.js","../src/startHTTPServer.ts","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.24.3_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.24.3_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.24.3_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.24.3_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/codegen/code.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/codegen/scope.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/codegen/index.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/util.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/names.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/errors.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/validate/boolSchema.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/rules.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/validate/applicability.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/validate/dataType.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/validate/defaults.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/code.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/validate/keyword.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/validate/subschema.js","../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js","../node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/resolve.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/validate/index.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/runtime/validation_error.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/ref_error.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/index.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/refs/data.json","../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/utils.js","../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/schemes.js","../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/index.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/runtime/uri.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/core.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/core/id.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/core/ref.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/core/index.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/validation/limitNumber.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/validation/multipleOf.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/runtime/ucs2length.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/validation/limitLength.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/validation/pattern.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/validation/limitProperties.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/validation/required.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/validation/limitItems.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/runtime/equal.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/validation/const.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/validation/enum.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/validation/index.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/applicator/items.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/applicator/items2020.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/applicator/contains.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/applicator/dependencies.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/applicator/properties.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/applicator/not.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/applicator/anyOf.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/applicator/oneOf.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/applicator/allOf.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/applicator/if.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/applicator/thenElse.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/applicator/index.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/format/format.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/format/index.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/metadata.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/draft7.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/discriminator/types.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/vocabularies/discriminator/index.js","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/refs/json-schema-draft-07.json","../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/ajv.js","../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.17.1/node_modules/ajv-formats/dist/formats.js","../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.17.1/node_modules/ajv-formats/dist/limit.js","../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.17.1/node_modules/ajv-formats/dist/index.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.24.3_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.24.3_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.24.3_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.24.3_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.24.3_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.24.3_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.24.3_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js"],"sourcesContent":["import type { IncomingMessage } from \"http\";\n\nexport interface AuthConfig {\n apiKey?: string;\n oauth?: {\n error?: string;\n error_description?: string;\n error_uri?: string;\n protectedResource?: {\n resource?: string;\n };\n realm?: string;\n scope?: string;\n };\n}\n\nexport class AuthenticationMiddleware {\n constructor(private config: AuthConfig = {}) {}\n\n getScopeChallengeResponse(\n requiredScopes: string[],\n errorDescription?: string,\n requestId?: unknown,\n ): { body: string; headers: Record<string, string>; statusCode: number } {\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n\n // Build WWW-Authenticate header with all required parameters\n if (this.config.oauth?.protectedResource?.resource) {\n const parts = [\n \"Bearer\",\n 'error=\"insufficient_scope\"',\n `scope=\"${requiredScopes.join(\" \")}\"`,\n `resource_metadata=\"${this.config.oauth.protectedResource.resource}/.well-known/oauth-protected-resource\"`,\n ];\n\n if (errorDescription) {\n // Escape quotes in description\n const escaped = errorDescription.replace(/\"/g, '\\\\\"');\n parts.push(`error_description=\"${escaped}\"`);\n }\n\n headers[\"WWW-Authenticate\"] = parts.join(\", \");\n }\n\n return {\n body: JSON.stringify({\n error: {\n code: -32001, // Custom error code for insufficient scope\n data: {\n error: \"insufficient_scope\",\n required_scopes: requiredScopes,\n },\n message: errorDescription || \"Insufficient scope\",\n },\n id: requestId ?? null,\n jsonrpc: \"2.0\",\n }),\n headers,\n statusCode: 403,\n };\n }\n\n getUnauthorizedResponse(options?: {\n error?: string;\n error_description?: string;\n error_uri?: string;\n scope?: string;\n }): { body: string; headers: Record<string, string> } {\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n\n // Build WWW-Authenticate header if OAuth config is available\n if (this.config.oauth) {\n const params: string[] = [];\n\n // Add realm if configured\n if (this.config.oauth.realm) {\n params.push(`realm=\"${this.config.oauth.realm}\"`);\n }\n\n // Add resource_metadata if configured\n if (this.config.oauth.protectedResource?.resource) {\n params.push(\n `resource_metadata=\"${this.config.oauth.protectedResource.resource}/.well-known/oauth-protected-resource\"`,\n );\n }\n\n // Add error from options or config (options takes precedence)\n const error =\n options?.error || this.config.oauth.error || \"invalid_token\";\n params.push(`error=\"${error}\"`);\n\n // Add error_description from options or config (options takes precedence)\n const error_description =\n options?.error_description ||\n this.config.oauth.error_description ||\n \"Unauthorized: Invalid or missing API key\";\n // Escape quotes in error description\n const escaped = error_description.replace(/\"/g, '\\\\\"');\n params.push(`error_description=\"${escaped}\"`);\n\n // Add error_uri from options or config (options takes precedence)\n const error_uri = options?.error_uri || this.config.oauth.error_uri;\n if (error_uri) {\n params.push(`error_uri=\"${error_uri}\"`);\n }\n\n // Add scope from options or config (options takes precedence)\n const scope = options?.scope || this.config.oauth.scope;\n if (scope) {\n params.push(`scope=\"${scope}\"`);\n }\n\n if (params.length > 0) {\n headers[\"WWW-Authenticate\"] = `Bearer ${params.join(\", \")}`;\n }\n }\n\n return {\n body: JSON.stringify({\n error: {\n code: 401,\n message:\n options?.error_description ||\n \"Unauthorized: Invalid or missing API key\",\n },\n id: null,\n jsonrpc: \"2.0\",\n }),\n headers,\n };\n }\n\n validateRequest(req: IncomingMessage): boolean {\n // No auth required if no API key configured (backward compatibility)\n if (!this.config.apiKey) {\n return true;\n }\n\n // Check X-API-Key header (case-insensitive)\n // Node.js http module automatically converts all header names to lowercase\n const apiKey = req.headers[\"x-api-key\"];\n\n if (!apiKey || typeof apiKey !== \"string\") {\n return false;\n }\n\n return apiKey === this.config.apiKey;\n }\n}\n","/**\n * This is a copy of the InMemoryEventStore from the typescript-sdk\n * https://github.com/modelcontextprotocol/typescript-sdk/blob/main/src/examples/shared/inMemoryEventStore.ts\n */\n\nimport type { EventStore } from \"@modelcontextprotocol/sdk/server/streamableHttp.js\";\nimport type { JSONRPCMessage } from \"@modelcontextprotocol/sdk/types.js\";\n\n/**\n * Simple in-memory implementation of the EventStore interface for resumability\n * This is primarily intended for examples and testing, not for production use\n * where a persistent storage solution would be more appropriate.\n */\nexport class InMemoryEventStore implements EventStore {\n private events: Map<string, { message: JSONRPCMessage; streamId: string }> =\n new Map();\n private lastTimestamp = 0;\n private lastTimestampCounter = 0;\n\n /**\n * Replays events that occurred after a specific event ID\n * Implements EventStore.replayEventsAfter\n */\n async replayEventsAfter(\n lastEventId: string,\n {\n send,\n }: { send: (eventId: string, message: JSONRPCMessage) => Promise<void> },\n ): Promise<string> {\n if (!lastEventId || !this.events.has(lastEventId)) {\n return \"\";\n }\n\n // Extract the stream ID from the event ID\n const streamId = this.getStreamIdFromEventId(lastEventId);\n\n if (!streamId) {\n return \"\";\n }\n\n let foundLastEvent = false;\n\n // Sort events by eventId for chronological ordering\n const sortedEvents = [...this.events.entries()].sort((a, b) =>\n a[0].localeCompare(b[0]),\n );\n\n for (const [\n eventId,\n { message, streamId: eventStreamId },\n ] of sortedEvents) {\n // Only include events from the same stream\n if (eventStreamId !== streamId) {\n continue;\n }\n\n // Start sending events after we find the lastEventId\n if (eventId === lastEventId) {\n foundLastEvent = true;\n continue;\n }\n\n if (foundLastEvent) {\n await send(eventId, message);\n }\n }\n\n return streamId;\n }\n\n /**\n * Stores an event with a generated event ID\n * Implements EventStore.storeEvent\n */\n async storeEvent(streamId: string, message: JSONRPCMessage): Promise<string> {\n const eventId = this.generateEventId(streamId);\n\n this.events.set(eventId, { message, streamId });\n\n return eventId;\n }\n\n /**\n * Generates a monotonic unique event ID in\n * `${streamId}_${timestamp}_${counter}_${random}` format.\n */\n private generateEventId(streamId: string): string {\n const now = Date.now();\n\n if (now === this.lastTimestamp) {\n this.lastTimestampCounter++;\n } else {\n this.lastTimestampCounter = 0;\n this.lastTimestamp = now;\n }\n\n const timestamp = now.toString();\n const counter = this.lastTimestampCounter.toString(36).padStart(4, \"0\");\n const random = Math.random().toString(36).substring(2, 5);\n\n return `${streamId}_${timestamp}_${counter}_${random}`;\n }\n\n /**\n * Extracts the stream ID from an event ID\n */\n private getStreamIdFromEventId(eventId: string): string {\n const parts = eventId.split(\"_\");\n\n return parts.length > 0 ? parts[0] : \"\";\n }\n}\n","/** A special constant with type `never` */\nexport const NEVER = Object.freeze({\n status: \"aborted\",\n});\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, params) {\n function init(inst, def) {\n var _a;\n Object.defineProperty(inst, \"_zod\", {\n value: inst._zod ?? {},\n enumerable: false,\n });\n (_a = inst._zod).traits ?? (_a.traits = new Set());\n inst._zod.traits.add(name);\n initializer(inst, def);\n // support prototype modifications\n for (const k in _.prototype) {\n if (!(k in inst))\n Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) });\n }\n inst._zod.constr = _;\n inst._zod.def = def;\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n var _a;\n const inst = params?.Parent ? new Definition() : this;\n init(inst, def);\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n for (const fn of inst._zod.deferred) {\n fn();\n }\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport const globalConfig = {};\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n","// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error();\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\nexport function cached(getter) {\n const set = false;\n return {\n get value() {\n if (!set) {\n const value = getter();\n Object.defineProperty(this, \"value\", { value });\n return value;\n }\n throw new Error(\"cached value already set\");\n },\n };\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepDecCount = (step.toString().split(\".\")[1] || \"\").length;\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nexport function defineLazy(object, key, getter) {\n const set = false;\n Object.defineProperty(object, key, {\n get() {\n if (!set) {\n const value = getter();\n object[key] = value;\n return value;\n }\n throw new Error(\"cached value already set\");\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport const captureStackTrace = Error.captureStackTrace\n ? Error.captureStackTrace\n : (..._args) => { };\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = cached(() => {\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = new Set([\"string\", \"number\", \"bigint\", \"boolean\", \"symbol\", \"undefined\"]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin === \"optional\" && shape[k]._zod.optout === \"optional\";\n });\n}\nexport const NUMBER_FORMAT_RANGES = {\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n};\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const newShape = {};\n const currDef = schema._zod.def; //.shape;\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // pick key\n newShape[key] = currDef.shape[key];\n }\n return clone(schema, {\n ...schema._zod.def,\n shape: newShape,\n checks: [],\n });\n}\nexport function omit(schema, mask) {\n const newShape = { ...schema._zod.def.shape };\n const currDef = schema._zod.def; //.shape;\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n delete newShape[key];\n }\n return clone(schema, {\n ...schema._zod.def,\n shape: newShape,\n checks: [],\n });\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const def = {\n ...schema._zod.def,\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n checks: [], // delete existing checks\n };\n return clone(schema, def);\n}\nexport function merge(a, b) {\n return clone(a, {\n ...a._zod.def,\n get shape() {\n const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n catchall: b._zod.def.catchall,\n checks: [], // delete existing checks\n });\n}\nexport function partial(Class, schema, mask) {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in oldShape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n else {\n for (const key in oldShape) {\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n return clone(schema, {\n ...schema._zod.def,\n shape,\n checks: [],\n });\n}\nexport function required(Class, schema, mask) {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n else {\n for (const key in oldShape) {\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n return clone(schema, {\n ...schema._zod.def,\n shape,\n // optional: [],\n checks: [],\n });\n}\nexport function aborted(x, startIndex = 0) {\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true)\n return true;\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\nexport function finalizeIssue(iss, ctx, config) {\n const full = { ...iss, path: iss.path ?? [] };\n // for backwards compatibility\n if (!iss.message) {\n const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\";\n full.message = message;\n }\n // delete (full as any).def;\n delete full.inst;\n delete full.continue;\n if (!ctx?.reportInput) {\n delete full.input;\n }\n return full;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n Object.defineProperty(inst, \"_zod\", {\n value: inst._zod,\n enumerable: false,\n });\n Object.defineProperty(inst, \"issues\", {\n value: def,\n enumerable: false,\n });\n Object.defineProperty(inst, \"message\", {\n get() {\n return JSON.stringify(def, util.jsonStringifyReplacer, 2);\n },\n enumerable: true,\n // configurable: false,\n });\n Object.defineProperty(inst, \"toString\", {\n value: () => inst.message,\n enumerable: false,\n });\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, { Parent: Error });\nexport function flattenError(error, mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of error.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n}\nexport function formatError(error, _mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues });\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues });\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(error);\n return fieldErrors;\n}\nexport function treeifyError(error, _mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const result = { errors: [] };\n const processError = (error, path = []) => {\n var _a, _b;\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n // regular union error\n issue.errors.map((issues) => processError({ issues }, issue.path));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, issue.path);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, issue.path);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n result.errors.push(mapper(issue));\n continue;\n }\n let curr = result;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (typeof el === \"string\") {\n curr.properties ?? (curr.properties = {});\n (_a = curr.properties)[el] ?? (_a[el] = { errors: [] });\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_b = curr.items)[el] ?? (_b[el] = { errors: [] });\n curr = curr.items[el];\n }\n if (terminal) {\n curr.errors.push(mapper(issue));\n }\n i++;\n }\n }\n }\n };\n processError(error);\n return result;\n}\n/** Format a ZodError as a human-readable stri